• 沒有找到結果。

AWS IoT Things Graph

N/A
N/A
Protected

Academic year: 2022

Share "AWS IoT Things Graph"

Copied!
265
0
0

加載中.... (立即查看全文)

全文

(1)

AWS IoT Things Graph

User Guide

(2)

AWS IoT Things Graph: User Guide

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.

(3)

Table of Contents

What is AWS IoT Things Graph? ... 1

Model, flow, and mapping ... 1

How AWS IoT Things Graph works ... 2

Step 1: Build a flow ... 2

Step 2: Create the flow configuration ... 3

Step 3: Deploy ... 5

How do I get started? ... 5

How a flow works ... 6

How a flow configuration works ... 6

Contents of a flow configuration ... 7

How to create a flow configuration ... 8

Namespaces ... 8

Getting started ... 9

Getting started with AWS IoT Things Graph in the cloud ... 9

Prepare for cloud deployments ... 9

Cloud flow examples ... 10

Getting started with AWS IoT Things Graph in AWS IoT Greengrass ... 20

Setting up your environment for AWS IoT Greengrass deployments ... 21

AWS IoT Greengrass flow examples ... 22

Using the example mock devices ... 52

What the mock devices do ... 52

Motion sensor ... 53

Camera ... 54

Screen ... 55

Adapting the mock devices ... 55

Modeling entities ... 57

Modeling by device communication protocol ... 57

MQTT ... 57

Modbus ... 59

MQTT device modeling 101 ... 62

Creating your abstract device model ... 63

Creating your device's capability (motion sensor) ... 64

Creating your device's capability (camera) ... 65

Creating your device definitions ... 66

Modbus device modeling 101 ... 68

Creating your abstract device model ... 69

Creating the definition for your device ... 72

Service modeling 101 ... 73

Modeling an AWS service ... 74

Modeling an AWS Lambda function ... 77

Creating and uploading entities ... 80

Step 1. Define the entities ... 80

Step 2. Upload the entity definitions ... 82

Step 3. Associate devices with things ... 86

Versioning and entity modeling ... 88

Uploading entities ... 88

Synchronizing with the public namespace ... 88

Viewing models and things in the AWS IoT Things Graph console ... 88

Models list ... 89

Model details ... 89

Model definition ... 89

Associating things with devices ... 90

Creating and deploying flows ... 91

Creating and deploying flows (AWS IoT Greengrass) ... 91

(4)

Create and deploy a flow (CLI) ... 92

Create and deploy a flow (AWS IoT Things Graph console) ... 95

Creating and deploying flows (cloud) ... 99

Create and deploy a flow (CLI) ... 100

Create and deploy a flow (AWS IoT Things Graph console) ... 103

Revising flows ... 107

Adding triggers to flows ... 108

Time-based triggers ... 108

Device triggers ... 109

Triggers and flow configurations ... 110

Working with choice nodes ... 110

Create the flow ... 111

Configure events and choice node logic ... 113

Using conditional logic in choice nodes ... 120

Working with systems and flow configurations ... 125

Creating systems ... 125

Creating flow configurations (AWS IoT Greengrass) ... 126

Creating a flow configuration in the AWS CLI ... 126

Creating a flow configuration in the AWS IoT Things Graph console ... 129

Creating flow configurations (cloud) ... 133

Creating a flow configuration in the AWS CLI ... 134

Creating a flow configuration in the AWS IoT Things Graph console ... 136

Viewing flow configurations and flow executions in the AWS IoT Things Graph console ... 141

Flow configurations ... 141

Flow executions ... 142

Managing lifecycles for AWS IoT Things Graph entities, flows, systems, and deployments ... 144

Namespace management ... 144

Deleting systems, flows, and namespaces ... 145

Deleting flow configurations ... 146

Security ... 147

Security in AWS IoT Things Graph ... 147

IAM role for flow execution in cloud deployments ... 148

IAM role for flow execution in AWS IoT Greengrass deployments ... 148

Security in AWS IoT Greengrass deployments ... 149

MQTT subscriptions ... 150

Security in AWS IoT Things Graph namespaces ... 150

Data protection ... 151

Data encryption ... 151

Encryption at Rest ... 151

Encryption in transit ... 152

Key management ... 152

Internetwork traffic privacy ... 152

Data retention ... 152

Identity and access management ... 153

Audience ... 153

Authenticating with identities ... 153

Managing access using policies ... 155

How AWS IoT Things Graph works with IAM ... 157

Identity-based policy examples ... 161

Troubleshooting ... 164

Monitoring AWS IoT Things Graph ... 166

Monitoring with CloudWatch ... 166

Logging AWS IoT Things Graph API calls with AWS CloudTrail ... 168

Compliance validation ... 175

Resilience ... 175

Infrastructure security ... 176

Configuration and vulnerability analysis ... 176

(5)

AWS IoT Greengrass environments ... 176

Lifecycle management ... 176

Security best practices ... 176

Example device and service definitions ... 178

Aukru HCSR501 motion sensor ... 178

Raspberry Pi camera ... 179

Raspberry Pi camera (for Amazon Rekognition) ... 180

Raspberry Pi screen ... 181

HW Group Damocles Mini ... 182

CoolAutomation CoolMasterNet ... 187

Deuta AL-511-00 IP-DALI-BRIDGE V2 ... 198

Amazon Rekognition DetectFaces API ... 205

getS3Lambda ... 206

wordCount ... 207

saveResponse ... 208

Deploying and running AWS IoT Things Graph on AWS IoT Greengrass ... 209

AWS IoT Greengrass deployments ... 209

Verifying flows in your AWS IoT Greengrass group ... 210

Troubleshoot issues with AWS IoT Things Graph ... 212

General deployment issues with AWS IoT Things Graph ... 212

Modbus flow deployment issues with AWS IoT Things Graph ... 213

AWS IoT Things Graph Data Model reference ... 214

What is the AWS IoT Things Graph Data Model? ... 214

GraphQL syntax ... 215

AWS IoT Things Graph Data Model and GraphQL ... 217

Type ... 217

Query ... 217

Using directives ... 218

Creating a device with GraphQL ... 220

AWS IoT Things Graph Data Model core constructs ... 221

Built-in data types ... 221

URN ID scheme ... 222

Properties ... 224

Enum types ... 226

Expressions ... 226

IoT domain constructs ... 233

State ... 233

Mapping ... 234

Event ... 239

Action ... 239

Capability ... 239

Device model ... 240

Device ... 240

Service ... 242

Workflow ... 245

System ... 248

Trigger ... 250

Deployments ... 251

Tagging your AWS IoT Things Graph resources ... 254

Tag basics ... 254

Tag restrictions and limitations ... 254

Using tags with IAM policies ... 255

AWS CloudFormation support for AWS IoT Things Graph ... 256

Create resources ... 256

Glossary ... 257 ... cclx

(6)

What is AWS IoT Things Graph?

AWS IoT Things Graph is an orchestration service that simplifies development of IoT applications. These applications can use different devices and web services from different manufacturers that otherwise can't speak with each other because they use different protocols, data formats, and message syntaxes.

For example, a home security application can contain cameras, door and window sensors, and motion sensors from a variety of manufacturers that might not conform to the same IoT standards. As a result, these cameras and sensors aren't necessarily designed to communicate with each other. The application builder has to expend significant development effort to translate messages and actions from one device to another. This drives up software development costs and increases the time to market.

Additionally, the device vendor used might be different for each installation. Each time the device vendor changes, the development effort needs to be repeated. Customers prefer to have a large catalog of supported devices so that they can pick the most cost-effective alternative.

Lastly, in many sites, the flow may use web services and run in the cloud. In other sites, the automation flows need to be deployed on the edge gateways (such as AWS IoT Greengrass). Designing flows that can run either in the cloud or on edge gateways is difficult. AWS IoT Things Graph manages the interactions between the devices, ensuring that the necessary transformations take place.

Communicating through Models

AWS IoT Things Graph can communicate with the different devices and web services and orchestrate interactions between them through the use of reusable abstractions known as models. Models define the supported actions and events generated by the devices. They also describe how to invoke those actions and read the generated events. With AWS IoT Things Graph, application builders need to specify only the sequence of interactions in their application using models and the corresponding devices and web services. AWS IoT Things Graph uses the models to identify the protocols, addressing schemes, and data formats that the different devices use. It does all the necessary translating of messages between the devices and web services. This enables the flow to execute in the expected order.

Flow Design Interface

AWS IoT Things Graph offers a visual drag-and-drop flow design interface that drastically reduces the application development time. Application builders can define interactions graphically, and build their applications using just a few actions. The visual interface includes models that implement conditional operations such as if-then-else and logical operators such as AND/OR. This enables you to easily create multistep automation flows. Also, AWS IoT Things Graph enables you to replace devices in the system with newer versions as they become available, without doing additional work to integrate them into your application.

Prebuilt Models

The AWS IoT Things Graph console contains prebuilt models for commonly used devices, such as cameras and motion sensors, and web services, such as Amazon Rekognition and AWS Lambda. Application builders can also use AWS IoT Things Graph to create their own models for their devices. After you build an application, you can deploy your it to the AWS Cloud to orchestrate interactions between web services and devices connected to the AWS IoT cloud. You can also deploy it to an AWS IoT Greengrass-enabled device to orchestrate interactions between locally connected devices and web services.

Model, flow, and mapping

There are three key concepts in AWS IoT Things Graph: model, mapping, and flow.

(7)

Device and Service Model

Device and service models are representations of the agents that interact in a flow. Device and service models generically define the attributes, inputs, and outputs of the devices and services that interact with each other in flows. AWS IoT Things Graph enables you to define device and service interactions without considering the low-level implementations of devices produced by different manufacturers.

Flow

A flow (or workflow) consists of device models and services. Flows define how the devices and services interact with each other after a triggering event occurs. A flow lists these interactions as a sequence of steps. Each step contains an action on a device or web service and the related inputs to and outputs from that action. The flow defines the logical interactions and orders of execution between the devices and services.

For more information, see How a flow works.

Mapping

A mapping provides information that enables AWS IoT Things Graph to convert the output message of one device into the expected format for the next device in the flow. Mappings bridge differences between the devices and enable them to work together. Mappings enable you to build IoT applications that use a variety of devices from different manufacturers.

How AWS IoT Things Graph works

Follow these steps to create and deploy an AWS IoT Things Graph flow.

Step 1: Build a flow

Build your flow by dragging device and web service models from the model library into a flow designer.

(You can also find this page by choosing the menu icon at the upper left of the page, and then choosing Flows.)

The model library contains models that AWS IoT Things Graph has made publicly available (public models), and the models that you created (private models). Private models are visible only to you. Define interactions by connecting the model outputs with appropriate inputs of other models. Choose Publish to save your flow and publish it to the list of flows that can be deployed.

(8)

Step 2: Create the flow configuration

On the following pages that appear, you'll configure the deployment target (cloud or Greengrass) and map things in your registry to the devices in your flow.

Configure the target

When you create your flow configuration, do the following:

• For cloud deployments, specify the flow action ARN. This is the ARN of the IAM role that AWS IoT Things Graph will use when the flow executes in the cloud.

• For AWS IoT Greengrass deployments, specify the AWS IoT Greengrass group where the application will run. Also specify the Amazon Simple Storage Service (Amazon S3) bucket to store the application configuration so that AWS IoT Greengrass can retrieve it when it starts.

Cloud

(9)

AWS IoT Greengrass

Map things

When you create your flow configuration, select things from your registry that correspond with each device model in your flow.

(10)

Step 3: Deploy

After you configure your deployment, deploy the application to the cloud or to AWS IoT Greengrass- enabled devices.

AWS IoT Things Graph packages up the flow and its dependencies and pushes them either to the cloud or to the AWS IoT Greengrass-enabled device. AWS IoT Things Graph then manages interactions between locally connected devices.

How do I get started?

Explore existing devices and device models in the AWS IoT Things Graph console to see if the ones you want to use in your flows are available. If the ones you want aren't available, you can build your own models by using the built-in model editor in the AWS IoT Things Graph console.

You define flows by chaining together models and web services. Then you deploy the flow.

For more information about how a flow works, see How a flow works. For examples that demonstrate how this works, see Getting started with AWS IoT Things Graph.

(11)

How a flow works

When you deploy a flow configuration, the AWS IoT Things Graph runtime is deployed to the cloud or to an AWS IoT Greengrass core device. The AWS IoT Things Graph runtime identifies trigger devices and messages and handles communications between the devices and web services to ensure that the flow executes in the expected order. You can create model and flow definitions using either the AWS IoT Things Graph console or the AWS IoT Things Graph APIs.

The following diagram shows how an AWS IoT Things Graph flow works when device and flow definitions are deployed and a flow is ready to run. This is a hypothetical automated door entry workflow for a building's security system, and is an example of a business process represented as a graph.

In the diagram, the badge reader is defined by Model A, the validation web service by Model B, the turnstile by Model C, and the camera by Model D. When a valid badge is scanned, the badge reader triggers an event that causes the next step to execute. This step is a validation web service. The step calls the validation API in the service. In this way, AWS IoT Things Graph coordinates all of the steps in the graph.

The nodes in the graph represent things (devices or web services), and the edges represent connections between pairs of nodes.

Each thing is described by a model (a device definition). The models define each thing as a set of inputs, outputs, and attributes. Models also expose interfaces for the rest of the application to use. Each step (node) in a workflow (flow) represents an action for a device, service, or built-in control flow action to take. A connection between two nodes represents a logical interaction or an order of execution between two nodes. A flow is one or more steps chained together, and represents business processes.

How a flow configuration works

An AWS IoT Things Graph flow configuration implements a workflow (flow) for a specific location or deployment. A flow configuration consists of a flow, associated triggers, and all the corresponding physical things that interact with each other in the flows.

The following diagram shows the elements of a flow configuration and how they relate to each other.

(12)

Contents of a flow configuration

A flow configuration contains the following elements.

Flow

A flow (or workflow) consists of device models and services. Flows define how the devices and services interact with each other after a triggering event occurs. A flow lists these interactions as a sequence of steps. Each step contains an action on a device or web service and the related inputs to and outputs from that action. The flow defines the logical interactions and orders of execution between the devices and services.

For more information, see How a flow works.

Device and service models

Device and service models are representations of the agents that interact in a flow. Device and service models generically define the attributes, inputs, and outputs of the devices and services that interact with each other in flows. AWS IoT Things Graph enables you to define device and service interactions without considering the low-level implementations of devices produced by different manufacturers.

Triggers

Triggers are the events that start flows. Triggers define the conditions (such as an interval of time passing, a sensor detecting motion, or a change in temperature) that cause a flow to start. You define

(13)

triggers for each flow when you create a flow configuration, so different triggers can start a given flow in different deployments.

Things

Things are the physical devices used in the flows. When you create a flow configuration, you associate specific things with the device models used in the flows. For example, if your flow contains a thermostat device model, your flow configuration will contain a thermostat from your AWS IoT things registry that is associated with the thermostat device model.

How to create a flow configuration

You can create flow configurations by writing the GraphQL directly and using the AWS IoT Things Graph APIs. The AWS IoT Things Graph console provides an easy way to create, maintain, and deploy your flow configurations.

For detailed instructions on how to create and deploy flow configurations using both the AWS CLI and the AWS IoT Things Graph console, see Creating and deploying flows.

Namespaces

A namespace is the repository for entities (for example, models) created using the AWS IoT Things Graph Data Modeling (TDM) language. These entities are associated with a specific account. The namespace is part of the URN for each entity.

When you upload TDM entities for the first time, AWS IoT Things Graph creates a namespace for you.

The namespace consists of your AWS Region, your account ID, and a fixed suffix default. The pattern is REGION/ACCOUNT ID/default. For example, a TDM entity created in the us-west-2 region looks like this: us-west-2/012345678910/default.

You can extend the path under default to organize your entities. For example, you could place your device definitions under default/devices and your property definitions under default/

properties.

Currently AWS IoT Things Graph supports only one namespace per account. TDM entities that are stored in a namespace are Properties, States, Events, Actions, Capabilities, Mappings, Devices, and Services.

There are two kinds of namespaces: public and private. The namespace associated with your account is private. You create and upload your own entity models inside this namespace. The public namespace is maintained by AWS and contains the entity definitions that all accounts can access. Private namespaces track the public namespace, and you can synchronize your private namespace with a specific version of the public namespace.

For more information about namespaces, see:

• Versioning and entity modeling

• Namespace versioning and workflows

• Lifecycle management for AWS IoT Things Graph entities, flows, systems, and deployments

(14)

Getting started

This section contains example AWS IoT Things Graph entity models, workflows (flows), and deployment configurations to get you started with end-to-end development using AWS IoT Things Graph.

When you work with AWS IoT Things Graph, you must deploy the service and all associated AWS and AWS IoT services (such as AWS IoT Device Management, Amazon Simple Storage Service (Amazon S3) buckets, and AWS Lambda functions) in the same AWS Region.

Topics

• Getting started with AWS IoT Things Graph in the cloud (p. 9)

• Getting started with AWS IoT Things Graph in AWS IoT Greengrass (p. 20)

• Using the example mock devices (p. 52)

Getting started with AWS IoT Things Graph in the cloud

This section contains instructions and provides examples to get you started with end-to-end development using AWS IoT Things Graph in the cloud.

Topics

• Prepare for cloud deployments (p. 9)

• Cloud flow examples (p. 10)

Prepare for cloud deployments

This topic explains how to allow AWS IoT Things Graph to assume an IAM role with the appropriate permissions when it executes your flows in the cloud.

Create and configure an IAM role for cloud deployments

Cloud deployments require you to use an IAM role to allow AWS IoT Things Graph to execute the flows in the deployments on your behalf. A role that a service assumes to perform actions on your behalf is called a service role. For more information about this kind of role, see Creating a role to delegate permissions to an AWS service.

The role you create should have policies that allow AWS IoT Things Graph to perform all of the actions in your workflow. Workflows that contain devices or device models that publish and subscribe to MQTT messages need permission for Iot:Connect, Iot:DescribeEndpoint, and Iot:Publish. The getting started examples in this section also need permission for Lambda. If you are using any other web service in your workflows, add the appropriate policies. For sample AWS IoT policies that assign MQTT publish and subscribe permissions, see Publish/Subscribe policy examples.

When you deploy AWS IoT Things Graph flows to the cloud, you need to specify the IAM role that AWS IoT Things Graph assumes when it executes the flow in the cloud. If your flow uses other services, then your role must also have the appropriate permissions for those services.

(15)

For information about securing AWS resources, see IAM best practices. For information about best practices for attaching policies to IAM roles, see Grant least privilege and Get started using permissions with AWS managed policies.

This must have a trust relationship with AWS IoT Things Graph. The following instructions describe how to create this role.

1. In the IAM console (https://console.aws.amazon.com/iam/), choose Roles, and then choose Create Role.

2. On the Choose the service that will use this role page, choose IoT Things Graph, and then choose Next: Permissions.

3. On the Attach permissions policies page, choose policies that contain permissions that your flows require. All flows require read-write permissions to AWS IoT, and the example flows in this section require read permission to AWS Lambda. Choose Next: Tags.

4. On the Add tags (optional) page, add optional tags that help you categorize your role. Choose Next:

Review.

5. On the Create role page, enter a name for your role. Choose Create role.

After you create this role, copy the role ARN so that you can use it when you create cloud flow configurations.

Cloud flow examples

The examples in this section walk you through the steps to create and deploy AWS IoT Things Graph workflows (flows) to the cloud.

Topics

• Creating a flow in the cloud with devices (p. 10)

• Creating a flow with devices by using the AWS CLI (p. 18)

Creating a flow in the cloud with devices

This topic walks you through the steps to create and deploy a simple workflow (flow) that consists of three mock devices running in the cloud: a motion sensor, a camera, and a screen. The mock devices pretend to be devices running on a Raspberry Pi.

NoteThe flow that you create in this example is the cloud version of the flow in Creating a flow with devices in AWS IoT Greengrass flow examples. This cloud example currently shows how to run the flow only with mock devices.

The flow in this example is triggered when the motion sensor detects motion. The motion sensor sends a message to the camera, which takes a picture and sends it to the screen for display.

Find the code for the mock devices in the CloudMockDevices.zip or the CloudMockDevices-v2.zip file. The first file contains scripts that use the AWS IoT Device SDK for Python v1. The second file contains scripts that use the AWS IoT Device SDK for Python v2. You can run these scripts on any Linux environment, such as a Raspberry Pi or an Amazon EC2 instance, on which Python 2.7 is installed.

Prerequisites

To create this example, you need the following AWS resources:

• An AWS account

• An IAM role that is configured according to the instructions in Prepare for cloud deployments

(16)

Create things

Open the AWS IoT console and create three things: one thing for your motion sensor, and two things for the camera and screen that are attached to your Raspberry Pi.

For instructions on how to create things in the registry, see Register a device in the registry. Be sure to create and activate certificates for each thing.

For more information about AWS IoT concepts, see What is AWS IoT?

Set up your mock devices

To run the workflow (flow) with mock devices, you need to copy the Python scripts in the

CloudMockDevices.zip or the CloudMockDevices-v2.zip file to your Linux environment. These scripts mimic the actions of real devices.

1. Install the AWS IoT Device SDK for Python.

2. Download and extract the CloudMockDevices.zip or the CloudMockDevices-v2.zip file. The extracted directory contains three files named cloudms.py, cloudcamera.py, and cloudscreen.py.

3. Create folders named ms, camera, and screen.

4. Copy the cloudms.py file into the ms directory, the cloudcamera.py file into the camera directory, and the cloudscreen.py file into the screen directory.

5. Copy the certificate and private key for each of the three things that you created into the appropriate directory on your Linux environment. Also copy the root certificate authority (CA) for AWS IoT into each directory. For example, the motion sensor certificate and private key should be in the ms directory, with the root CA for AWS IoT and the cloudms.py file.

If you haven't created and activated certificates for your things, follow the steps in Register a device in the registry. Make sure to attach a policy to each certificate.

Create and publish the flow

To create this flow with the AWS CLI instead of the AWS IoT Things Graph console, follow the instructions in Creating a flow with devices by using the AWS CLI.

1. Open the AWS IoT Things Graph console, and then choose Create flow.

2. Create a flow.

In the Flow configuration pane that appears, name your flow (such as SecurityFlow). Choose Create flow.

3. Add the device models to the flow.

Search for the MotionSensor device model. Select the device model and drag it into the flow designer. Do the same for the Camera and Screen device models.

(17)

4. Connect the device models.

In the flow designer, select the edge of the MotionSensor device model and connect it to the Camera device model. Also connect the Camera device model to the Screen device model.

5. Update the motion sensor trigger.

In the trigger editor that appears in the right pane, for Condition, choose StateChanged. For Action, choose ThingsGraph.startFlow.

6. Update the camera device action.

a. In the flow designer, select the Camera device model.

b. In the action editor that appears in the right pane, choose No action configured.

c. For Action, choose capture.

d. Expand Output, and then enter cameraResult.

7. Update the screen device model action.

a. In the flow designer, select the Screen device model.

b. In the action editor that appears in the right pane, choose No action configured.

c. For Action, choose display.

d. Expand Inputs, and then choose Define Input.

e. For Inputs, enter ${cameraResult.lastClickedImage}.

8. Publish the flow.

Choose Publish at the upper right of the page. This creates the flow and adds it to the list of flows that can be deployed.

Associate things to device models

1. Select the menu icon at the upper left of the page. Choose Things.

(18)

On the Things page, choose the motion sensor thing that you created earlier. Then choose Associate with device.

2. On the Select device model page, choose HCSR501MotionSensor. Choose Associate. This step associates the HCSR501MotionSensor motion sensor thing in your registry with the motion sensor device model in your flow. The HCSR501MotionSensor device implements the capability of the motion sensor device model.

(19)

3. After you return to the Select device model page, refresh the page to verify that the motion sensor thing is associated with the HCSR501MotionSensor device. Repeat the previous two steps for the RaspberryPiCamera and RaspberryPiScreen devices.

Create and deploy the flow configuration

1. Create the flow configuration.

Select the menu icon at the upper left of the page, and then choose Flows to return to the Flows page. Select the box next to the flow that you just created, and then choose Create flow configuration.

2. Name the flow configuration.

A flow configuration contains the details that are specific to a single deployment. On the Describe flow configuration page, select your flow and enter a flow configuration name. The flow

configuration name can't contain spaces.

Choose Cloud, and then choose Next.

3. Configure the target.

On the Configure target page, enter the ARN of the role that you created in Prepare for cloud deployments. Choose Next.

(20)

4. Select things for your deployment.

The Map Things page provides an interface for selecting the specific things to include in your deployment. The menus under each device model in your deployment contain all of the things that you associated with the device model. Because you're getting started, the menus for each device on this page will include only one thing (the thing that you've associated with each device model).

On the Map Things page, from the menu under the motionSensor device model, select the motion sensor thing that you created earlier. Select the camera and screen things for the Camera and Screen device models. Choose Next.

5. View the trigger.

On the Set up triggers page, the GraphQL that defines the motion event trigger appears in the editor. This GraphQL specifies the event that triggers the flow. When the motion sensor detects a person moving, the ThingsGraph.startFlow function initiates the flow. You don't need to edit this code.

Choose Review.

(21)

6. Review and create.

On the Review and create page, review the information you entered for your flow configuration.

Then choose Create.

When the Flow configuration created message appears, choose Deploy now.

Refresh the Deployments page to verify that the flow has deployed. After a successful deployment, the Deployments page displays Deployed in target in the Status column.

Run the flow with mock devices

To run the Python scripts for each mock device, you need to know your AWS IoT custom endpoint. This enables you to connect to AWS IoT.

To find this endpoint, open the AWS IoT console (https://console.aws.amazon.com/iot/), and then choose Settings. You can also find the endpoint by using the aws iot describe-endpoint AWS CLI command.

(22)

If you're using an Amazon Trust Services (ATS) root CA, use the following AWS CLI command to find your custom endpoint. For more information about certificates and ATS endpoints, see X.509 certificates and AWS IoT.

aws iot describe-endpoint --endpoint-type iot:Data-ATS

Follow these steps to run all three Python scripts and observe the mock devices interacting in the flow.

1. Open three terminal sessions on your Linux environment. In one terminal, navigate to the ms directory. To run the ms.py script, run the following command.

python cloudms.py -e custom endpoint -r root CA file path -c certificate file path - k private key file path -n motion sensor thing name -id "cloudms"

After the script starts running, it displays the following output every 10 seconds. This indicates that the mock motion sensor has detected motion.

Published topic TG_MS/motion: {"isMotionDetected": true}

2. In the second terminal, navigate to the camera directory. Run the camera.py script by using the following command.

python cloudcamera.py -e custom endpoint -r root CA file path -c certificate file path -k private key file path -n camera thing name -id "cloudcamera"

After the script starts running, it displays the following output every 10 seconds. This indicates that the motion sensor trigger has prompted the mock camera to capture an image and publish it to the /capture/finished MQTT topic.

Received message on topic TG_Camera/capture: {}

2019-02-11 21:37:33,430 - AWSIoTPythonSDK.core.protocol.mqtt_core - INFO - Performing sync publish...

Published topic TG_Camera/capture/finished: {"lastClickedImage": "https://images- na.ssl-images-amazon.com/images/I/41+K4pC74XL._AC_US218_.jpg"}

3. In the third terminal, navigate to the screen directory. Run the screen.py script by using the following command.

python cloudscreen.py -e custom endpoint -r root CA file path -c certificate file path -k private key file path -n screen thing name -id "cloudscreen"

After the script starts running, it displays the following output every 10 seconds. This indicates that the mock screen has received the image from the mock camera.

Received message on topic TG_Screen/display: {"imageUri":"https://images-na.ssl-images- amazon.com/images/I/51rMLSWgwRL._AC_US218_.jpg"}

(23)

Delete the flow and flow configuration (optional)

For instructions on how to undeploy a flow configuration, and delete the flow configuration and flow that you've created, see Deleting flow configurations and Deleting systems, flows, and namespaces in Lifecycle management for AWS IoT Things Graph entities, flows, systems, and deployments.

Creating a flow with devices by using the AWS CLI

This topic contains the AWS CLI commands that create the flow in Creating a flow with devices. The setup instructions for this example are identical to the ones in that topic. Before starting with this example, follow all of the instructions in that topic up to Create and deploy the flow, and then return to this topic.

Install the CLI

To install the AWS CLI, follow the instructions in Installing the AWS CLI.

Create the flow by using the AWS CLI

The following steps describe how to create and deploy the flow by using the AWS CLI.

1. The following AWS IoT Things Graph Data Model (TDM) code contains the definition of the flow used in this example.

Copy this code to a file. Replace the REGION and ACCOUNT ID placeholders with your AWS Region and account ID.

{query SecurityFlow($camera: string!, $screen: string!) @workflowType(id:

\"urn:tdm:REGION/ACCOUNT ID/default:Workflow:SecurityFlow\") { variables {

cameraResult @property(id: \"urn:tdm:aws/examples:property:CameraStateProperty\") } steps {

step(name: \"Camera\", outEvent: [\"cameraStepDone\"]) {

DeviceActivity(deviceModel: \"urn:tdm:aws/examples:deviceModel:Camera\", out:

\"cameraResult\", deviceId: \"${camera}\") { capture

} }

step(name: \"Screen\", inEvent: [\"cameraStepDone\"]) {

DeviceActivity(deviceModel: \"urn:tdm:aws/examples:deviceModel:Screen\", deviceId: \"${screen}\") {

display(imageUrl: \"${cameraResult.lastClickedImage}\") }

} }} }

2. Enter the following command to create the flow. This command assumes that you're working in a Linux or Unix environment. For other environments, use the equivalent of the cat utility.

aws iotthingsgraph create-flow-template --definition language=GRAPHQL,text='"'"$(cat PATH TO TDM FILE)"'"'

(24)

3. The following TDM code contains the definition of the system used in this example. The console creates this system for you.

Copy this code to a file. Replace the REGION and ACCOUNT ID placeholders with your AWS Region and account ID.

{type SecurityFlow @systemType(id: \"urn:tdm:REGION/ACCOUNT ID/

default:System:SecurityFlow\", description: \"Home Security System\") {

motionSensor: Device @thing(id: \"urn:tdm:aws/examples:deviceModel:MotionSensor\") camera: Device @thing(id: \"urn:tdm:aws/examples:deviceModel:Camera\")

screen: Device @thing(id: \"urn:tdm:aws/examples:deviceModel:Screen\") SecurityFlow: Flow @workflow(id: \"urn:tdm:REGION/ACCOUNT ID/

default:Workflow:SecurityFlow\") }}

4. Enter the following command to create the system.

aws iotthingsgraph create-system-template --definition language=GRAPHQL,text='"'"$(cat PATH TO TDM FILE)"'"'

5. Enter the following commands to associate the things you created in your registry with the device models used in the flow.

Replace the MotionSensorName, CameraName, and ScreenName placeholders with the names of the things you created earlier.

aws iotthingsgraph associate-entity-to-thing --thing-name "MotionSensorName" --entity- id "urn:tdm:aws/examples:Device:HCSR501MotionSensor"

aws iotthingsgraph associate-entity-to-thing --thing-name "CameraName" --entity-id "urn:tdm:aws/examples:Device:RaspberryPiCamera"

aws iotthingsgraph associate-entity-to-thing --thing-name "ScreenName" --entity-id "urn:tdm:aws/examples:Device:RaspberryPiScreen"

6. The following TDM code contains the definition of the flow configuration used in this example.

The TDM definition is inside the definition object. For more information, see Creating flow configurations.

Copy this code to a file. Replace the REGION and ACCOUNT ID placeholders with your AWS Region and account ID. Replace the MotionSensorName, ScreenName, and CameraName placeholders with the names of the things you created earlier.

{query Room215 @deployment(id: \"urn:tdm:REGION/ACCOUNT ID/default:Deployment:Room215\", systemId: \"urn:tdm:REGION/ACCOUNT ID/default:System:SecurityFlow\") {

motionSensor(deviceId: \"MotionSensorName\") screen(deviceId: \"ScreenName\")

camera(deviceId: \"CameraName\")

triggers {MotionEventTrigger(description: \"a trigger\") { condition(expr: \"devices[name == 'motionSensor'].events[name ==

'StateChanged'].lastEvent\")

action(expr: \"ThingsGraph.startFlow('SecurityFlow', bindings[name ==

'camera'].deviceId, bindings[name == 'screen'].deviceId)\")

(25)

} } } }

7. Enter the following command to create the flow configuration.

Replace ROLE ARN with the IAM role ARN that you created in Prepare for cloud deployments.

aws iotthingsgraph create-system-instance --definition language=GRAPHQL,text='"'"$(cat PATH TO TDM FILE)"'"' \

--target CLOUD --flow-actions-role-arn ROLE ARN

When the operation completes, the AWS CLI returns the following deployment summary as a JSON object. Use the id value in the summary block as the TDM URN of the flow configuration.

{

"summary": {

"status": "PENDING_DEPLOYMENT", "greengrassGroupName": "", "target": "CLOUD",

"arn": "arn:aws:iotthingsgraph:REGION:ACCOUNT ID:default#Deployment#Room215", "updatedAt": 1555021747.176,

"id": "urn:tdm:REGION/ACCOUNT ID/default:Deployment:Room215", "createdAt": 1555021747.176

}

}

8. Enter the following command to deploy the flow configuration to your AWS IoT Greengrass group.

Use the TDM URN value returned in the previous step as the value of the id parameter.

aws iotthingsgraph deploy-system-instance --id SYSTEM INSTANCE URN

9. To verify the deployment, follow the steps in Run the Flow with Mock Devices (p. 16).

Delete the flow and flow configuration (optional)

For instructions on how to undeploy a flow configuration, and delete the flow configuration and flow that you've created, see Deleting flow configurations and Deleting systems, flows, and namespaces in Lifecycle management for AWS IoT Things Graph entities, flows, systems, and deployments.

Getting started with AWS IoT Things Graph in AWS IoT Greengrass

This section contains instructions and provides examples to get you started with end-to-end development using AWS IoT Greengrass deployments of AWS IoT Things Graph.

Topics

• Setting up your environment for AWS IoT Greengrass deployments (p. 21)

• AWS IoT Greengrass flow examples (p. 22)

(26)

Setting up your environment for AWS IoT Greengrass deployments

This topic describes the tasks you need to do to start working with AWS IoT Things Graph. You can't deploy and run a flow successfully until you perform the these tasks.

Before you get started, make sure that you have an AWS account.

Create an AWS IoT Greengrass group

NoteFor information about using AWS CloudFormation to create and manage AWS IoT Greengrass groups and resources, see AWS IoT Greengrass resource types reference.

To perform the tasks related to setting up your AWS IoT Greengrass core, you need a Mac, Windows, or Linux or Unix system. The setup instructions in Getting started with AWS IoT Greengrass recommend that you start with a Raspberry Pi.

1. Download and install the AWS IoT Greengrass core software.

Follow the instructions in Installing AWS IoT Greengrass core software.

2. Start the AWS IoT Greengrass software.

Follow the instructions in Deploy cloud configurations to an AWS IoT Greengrass core device to start AWS IoT Greengrass.

3. Create a directory named thingsgraph at the root directory of your AWS IoT Greengrass core device. AWS IoT Things Graph installs files in this location. This directory must have read, write, and execute permissions for ggc_user. If your AWS IoT Greengrass core is using a Unix-like operating system, set these permissions by entering the following commands at a command prompt.

sudo chown ggc_user: /thingsgraph sudo chmod 700 /thingsgraph

The AWS IoT Things Graph logs go into the /greengrass/ggc/var/log/user/us-east-1/

ThingsGraph/ directory. For information about how to configure AWS IoT Greengrass logs, see Monitoring with AWS IoT Greengrass logs.

4. Create an IAM role for AWS IoT Greengrass and attach the policies that your flows will need to interact with other AWS services when they're running.

For example, a flow that needs to read and write to an Amazon S3 bucket needs to have the AmazonS3FullAccess policy attached to it.

5. When AWS IoT Things Graph installs a flow to your AWS IoT Greengrass core, it first uploads a file that contains all of the flow's dependencies to an Amazon S3 bucket. It then installs the flow and its dependencies from the bucket. This means that the AWS IoT Greengrass service needs permission to access this bucket.

In the IAM console (https://console.aws.amazon.com/iam/), choose Roles. Select the role named Greengrass_ServiceRole, and attach the AmazonS3FullAccess policy to give it access to your S3 bucket.

Install Java

To run AWS IoT Things Graph, your AWS IoT Greengrass core device needs to have Java 8 installed.

(27)

If you're using a Linux environment, follow these steps to install the correct version of Java. See the Java website for instructions on installing Java 8 on Windows and Mac environments.

1. Run the following command to install Java 8.

sudo yum install java-1.8.0

2. Run the following command to uninstall Java 7.

sudo yum remove java-1.7.0-openjdk

3. Run the following command to create a symlink to the newly installed version of Java.

sudo ln /etc/alternatives/java /usr/bin/java8

AWS IoT Greengrass flow examples

The examples in this section walk you through the steps to create and deploy workflows (flows) to an AWS IoT Greengrass group.

Topics

• Creating a flow in an AWS IoT Greengrass group with devices (p. 22)

• Creating a flow with Lambda functions (p. 32)

• Creating a flow with devices and a service (p. 37)

• Creating a flow with devices by using the AWS CLI (p. 44)

• Creating a flow with Lambda functions by using the AWS CLI (p. 46)

• Creating a flow with devices and a service by using the CLI (p. 49)

Creating a flow in an AWS IoT Greengrass group with devices

This topic walks you through the steps to create and deploy a simple workflow (flow) that consists of a Raspberry Pi connected to three devices: an Aukru HC-SR501 motion sensor, a Raspberry Pi camera, and a Raspberry Pi screen.

The flow in this example is triggered when the motion sensor detects motion. The motion sensor sends a message to the camera, which takes a picture and sends it to the screen for display.

If you don't want to buy the devices used in this example, you can run three Python scripts that mimic the functions of the devices. This topic shows you how to run the flow with both the real and mock devices.

Find the code for the mock devices in the MockDevices.zip or the MockDevices-v2.zip file. The first file contains scripts that use the AWS IoT Device SDK for Python v1. The second file contains scripts that use the AWS IoT Device SDK for Python v2. You can run these scripts on any Linux environment, such as a Raspberry Pi or an Amazon EC2 instance, on which Python 2.7 is installed.

Prerequisites

To create this example, you need the following AWS resources:

• An AWS account

• An Amazon S3 bucket

To create this example with real devices, you need the following hardware resources:

• A Raspberry Pi running AWS IoT Greengrass version 1.7 or later

(28)

• An Aukru HC-SR501 motion sensor

• A Raspberry Pi 7" touch screen display

• A Raspberry Pi camera module v2-8 megapixel,1080p

Set up your Raspberry Pi

To run the workflow with real devices, you need to set up your Raspberry Pi with those devices. If you're creating this example with the mock devices, skip ahead to Create an AWS IoT Greengrass Group (p. 23).

• Attach your motion sensor to Raspberry Pi GPIO pin 1.

• Attach the camera by following the instructions in the Raspberry Pi camera board documentation.

• Attach the screen by following the instructions in the Raspberry Pi 7" touch screen assembly guide.

• Download and install the drivers included in the ThingsGraphPrototypeDevices.zip file. To install the drivers, follow the instructions in the README.

Now you've configured your Raspberry Pi to communicate with the motion sensor, camera, and screen.

Create an AWS IoT Greengrass group

NoteFor information about using AWS CloudFormation to create and manage AWS IoT Greengrass groups and resources, see AWS IoT Greengrass resource types reference.

If you're creating this example with real devices, install AWS IoT Greengrass on the same Raspberry Pi to which you attached your motion sensor, camera, and screen.

If you're using mock devices, install AWS IoT Greengrass on the same Linux environment where you run the Python scripts.

Perform the steps in Setting up your environment on the appropriate device or computer. Make sure that you've created an IAM role for AWS IoT Greengrass (step 4 in the Create an AWS IoT Greengrass Group procedure in that topic). Attach the AmazonS3FullAccess policy to give it access to your S3 bucket.

NoteThe AWS IoT Greengrass group and Amazon S3 bucket that you use in this example must be created in the same AWS Region. The AWS IoT Things Graph entities that you create must also be in the same Region as these resources.

Create things

Open the AWS IoT console and create three things: one thing for your motion sensor, and two things for the camera and screen that are attached to your Raspberry Pi.

For instructions on how to create things in the registry, see Register a device in the registry. Be sure to create and activate certificates for each thing.

In the AWS IoT console, on the Greengrass tab, select your group, choose Devices, and then add the three new things to your AWS IoT Greengrass group.

For more information about AWS IoT concepts, see What is AWS IoT?

Set up your mock devices

To run the workflow (flow) with mock devices, you need to install the AWS IoT Greengrass Core SDK, and then copy the Python scripts in the MockDevices.zip or the MockDevices-v2.zip file to your Linux environment.

(29)

If you're creating this example with real devices, skip ahead to Create and Deploy the Flow (p. 27).

1. Install the AWS IoT Device SDK for Python.

2. Download and extract the MockDevices.zip or the MockDevices-v2.zip file. The extracted directory contains three files named ms.py, camera.py, and screen.py.

3. Create folders named ms, camera, and screen.

4. Copy the ms.py file into the ms directory, the camera.py file into the camera directory, and the screen.py file into the screen directory.

5. Copy the certificate and private key for each of the three things that you created into the appropriate directory on your Linux environment. Also copy the root certificate authority (CA) for AWS IoT into each directory. For example, the motion sensor certificate and private key should be in the ms directory, with the root CA for AWS IoT and the ms.py file.

If you haven't created and activated certificates for your things, follow the steps in Register a device in the registry. Make sure to attach a policy to each certificate.

Create and publish the flow

To create this flow with the AWS CLI instead of the AWS IoT Things Graph console, follow the instructions in Creating a flow with devices by using the AWS CLI.

1. Open the AWS IoT Things Graph console, and then choose Create flow.

2. Create a flow.

In the Flow configuration pane that appears, name your flow (such as SecurityFlow). Choose Create flow.

3. Add the device models to the flow.

Search for the MotionSensor device mode. Select the device model and drag it into the flow designer. Do the same for the Camera and Screen device models.

4. Connect the device models.

In the flow designer, select the edge of the MotionSensor device model and connect it to the Camera device model. Also connect the Camera device model to the Screen device model.

(30)

5. Update the motion sensor trigger.

In the trigger editor that appears in the right pane, for Condition, choose StateChanged. For Action, choose ThingsGraph.startFlow.

6. Update the camera device model action.

a. In the flow designer, select the Camera device model.

b. In the action editor that appears in the right pane, choose No action configured.

c. For Action, choose capture.

d. Expand Output, and then enter cameraResult.

7. Update the screen device action.

a. In the flow designer, select the Screen device model.

b. In the action editor that appears in the right pane, choose No action configured.

c. For Action, choose display.

d. Expand Inputs, and then choose Define Input.

e. For Inputs, enter ${cameraResult.lastClickedImage}.

8. Publish the flow.

Choose Publish at the upper right of the page. This creates the flow and adds it to the list of flows that can be deployed.

Associate things to device models

1. Select the menu icon at the upper left of the page. Choose Things.

(31)

On the Things page, choose the motion sensor thing that you created earlier. Then choose Associate with device.

2. On the Select device model page, choose HCSR501MotionSensor. Choose Associate. This step associates the HCSR501MotionSensor motion sensor thing in your registry with the motion sensor device model in your flow. The HCSR501MotionSensor device implements the capability of the motion sensor device model.

(32)

3. After you return to the Select device model page, refresh the page to verify that the motion sensor thing is associate with the HCSR501MotionSensor device. Repeat the previous two steps for the RaspberryPiCamera and RaspberryPiScreen devices.

Create and deploy the flow configuration

1. Create the flow configuration.

Select the menu icon at the upper left of the page, and then choose Flows to return to the Flows page. Select the box next to the flow that you just created, and then choose Create flow configuration.

2. Name the flow configuration.

A flow configuration contains the details that are specific to a single deployment. On the Describe flow configuration page, select your flow and enter a flow configuration name. The flow

configuration name can't contain spaces.

Choose Greengrass, and then choose Next.

3. Configure the target.

On the Configure target page, enter the name of your Amazon S3 bucket and the AWS IoT Greengrass group to which your AWS IoT Greengrass core device belongs. Amazon S3 buckets are globally unique, so your bucket name will be different from the one in the following screen shot.

Choose Next.

(33)

4. Select things for your deployment.

The Map Things page provides an interface for selecting the specific things to include in your deployment. The menus under each device model in your deployment contain all of the things that you associated with the device model. Because you're getting started, the menus for each device model on this page will include only one thing (the thing that you've associated with each device model).

On the Map Things page, for motionSensor, select the motion sensor thing that you created earlier.

Select the screen and camera things for the Camera and Screen device models. Choose Next.

5. View the trigger.

On the Set up triggers page, the GraphQL that defines the motion event trigger appears in the editor. This GraphQL specifies the event that triggers the flow. When the motion sensor detects a person moving, the ThingsGraph.startFlow function initiates the flow. You don't need to edit this code.

Choose Review.

(34)

6. Review and create.

On the Review and create page, review the information you entered for your flow configuration.

Choose Create.

7. Deploy.

When the Flow configuration created message appears, choose Deploy now.

Refresh the Deployments page to verify that the flow has deployed. After a successful deployment, the Deployments page displays Deployed in target in the Status column.

Run the flow with real devices

If you created this example with mock devices, skip ahead to Run the Flow with Mock Devices (p. 30).

Turn on your Raspberry Pi, motion sensor, camera, and screen. Position the motion sensor and camera so that they are directly in front of you. Wave your hand over the motion sensor. The camera takes a picture of you and displays it on the screen.

(35)

Run the flow with mock devices

To run the Python scripts for each mock device, you need to know your AWS IoT custom endpoint. This enables you to connect to AWS IoT.

To find this endpoint, open the AWS IoT console (https://console.aws.amazon.com/iot/), and then choose Settings. You can also find the endpoint by using the aws iot describe-endpoint AWS CLI command.

If you're using an Amazon Trust Services (ATS) root CA, use the following AWS CLI command to find your custom endpoint. For more information about certificates and ATS endpoints, see X.509 certificates and AWS IoT.

aws iot describe-endpoint --endpoint-type iot:Data-ATS

(36)

Follow these steps to run all three Python scripts and observe the mock devices interacting in the flow.

NoteYou don't need to pass your custom endpoint as a parameter for the scripts that use the AWS IoT Device SDK for Python v2.

1. Open three terminal sessions on your Linux environment. In one terminal, navigate to the ms directory. To run the ms.py script, run the following command.

python ms.py -e custom endpoint -r root CA file path -c certificate file path - k private key file path -n motion sensor thing name

After the script starts running, it displays the following output every 10 seconds. This indicates that the mock motion sensor has detected motion.

Published topic motion sensor thing name/motion: {"isMotionDetected": true}

2. In the second terminal, navigate to the camera directory. Run the camera.py script by using the following command.

python camera.py -e custom endpoint -r root CA file path -c certificate file path - k private key file path -n camera thing name

After the script starts running, it displays the following output every 10 seconds. This indicates that the motion sensor trigger has prompted the mock camera to capture an image and publish it to the /capture/finished MQTT topic.

Received message on topic camera thing name/capture: {}

2019-02-11 21:37:33,430 - AWSIoTPythonSDK.core.protocol.mqtt_core - INFO - Performing sync publish...

Published topic camera thing name/capture/finished: {"lastClickedImage": "https://

images-na.ssl-images-amazon.com/images/I/41+K4pC74XL._AC_US218_.jpg"}

3. In the third terminal, navigate to the screen directory. Run the screen.py script by using the following command.

python screen.py -e custom endpoint -r root CA file path -c certificate file path - k private key file path -n screen thing name

After the script starts running, it displays the following output every 10 seconds. This indicates that the mock screen has received the image from the mock camera.

Received message on topic screen thing name/display: {"imageUri":"https://images- na.ssl-images-amazon.com/images/I/51rMLSWgwRL._AC_US218_.jpg"}

(37)

Delete the flow and flow configuration (optional)

For instructions on how to undeploy a flow configuration, and delete the flow configuration and flow that you've created, see Deleting flow configurations and Deleting systems, flows, and namespaces in Lifecycle management for AWS IoT Things Graph entities, flows, systems, and deployments.

Creating a flow with Lambda functions

This topic describes how to create a simple workflow (flow) that uses three AWS Lambda functions as service models in that flow.

The flow runs every 60 seconds and calls three service models: one that reads data from an Amazon Simple Storage Service (Amazon S3) bucket, one that analyzes the data, and one that saves the results of the analysis to the Amazon S3 bucket.

Prerequisites

To create this example, you need the following resources.

NoteYou must create the AWS IoT Greengrass group and Amazon S3 bucket in the same AWS Region.

The AWS IoT Things Graph entities that you create must also be in the same Region as these resources.

• An AWS account.

• An AWS IoT Greengrass core, version 1.7 or later.

• An AWS IoT Greengrass group.

• Node.js installed on your AWS IoT Greengrass core device.

• An Amazon S3 bucket that contains a file named HelloWorld.txt.

• An AWS IoT Greengrass IAM role that has access to your S3 bucket.

Add this role to your AWS IoT Greengrass group. For information about how to configure IAM roles for AWS IoT Greengrass, see Configure IAM roles.

• A Lambda IAM role that has access to your S3 bucket.

Create an AWS IoT Greengrass group

NoteFor information about using AWS CloudFormation to create and manage AWS IoT Greengrass groups and resources, see AWS IoT Greengrass resource types reference.

Perform the steps in Setting up your environment. Make sure that you've created an IAM role for AWS IoT Greengrass (step 4 in the Create an AWS IoT Greengrass Group procedure in that topic). Attach the AmazonS3FullAccess policy to give it access to your S3 bucket.

On the Settings page of your group, make sure that Greengrass container is selected under Lambda runtime environment.

Create and deploy the Lambda functions

1. Create the Lambda functions.

1. Follow the instructions in Create a simple Lambda function to create three Lambda functions named GetS3Object, WordCount, and SaveToS3.

NoteThe sample won't work if you use any other function names.

(38)

2. The code for these functions is in the Lambdas.zip file. Don't add any triggers. Choose the latest supported Node.js runtime. Use an IAM role that has read/write access to your Amazon S3 bucket.

In the SaveToS3 function, replace the value of bucket with the name of your S3 bucket.

Each Lambda function is a service model in the flow. Copy the Lambda Amazon Resource Names (ARNs) so that you can use them in your service model definitions.

3. After you copy and save the functions in the Lambda console, on the Actions menu, choose Publish new version. You must use version 1 for each Lambda function.

2. Deploy the Lambda functions to AWS IoT Greengrass.

To do this, follow the instructions in Configure the Lambda function for AWS IoT Greengrass.

Create and publish the flow

To create this flow with the AWS CLI instead of the AWS IoT Things Graph console, follow the instructions in Creating a flow with Lambda functions by using the AWS CLI.

1. Open the AWS IoT Things Graph console.

Choose Create flow.

2. Create a flow.

In the Flow configuration pane that appears, enter a name for your flow. Choose Create flow.

3. Add the service models to the flow.

On the Logic tab, choose Clock, and then drag it into the flow designer.

On the Service tab, search for the getS3Lambda service model. Choose the service model and drag it into the flow designer. Do the same for the wordCountLambda and saveResponseLambda service models.

4. Connect the service models.

In the flow designer, select the edge of the ClockTrigger service model and connect it to the getS3Lambda service model. Then connect the getS3Lambda, wordCountLambda, and saveResponseLambda service models in the same way.

(39)

5. Update the ClockTrigger.

In the trigger editor that appears in the right pane, for Frequency, enter 60, and then select seconds from the menu on the right. For Action, choose ThingsGraph.startFlow.

6. Add the getS3Lambda service model action.

a. In the flow designer, choose the getS3Lambda service model. In the action editor that appears in the right pane, select No action configured. In the list that appears, select getS3ObjectAsString.

b. Expand Inputs. Choose Define Input, and then enter the names of your Amazon S3 bucket and file as the values for bucket and key.

c. Expand Output, and then enter getS3LambdaResult.

7. Add the wordCountLambda service model action.

a. In the flow designer, select the wordCountLambda service model. In the action editor that appears in the right pane, choose No action configured. For Action box, choose wordCount. Expand Inputs, choose Define Input, and then for message, enter

${getS3LambdaResult.message}.

b. Expand Output, and then enter wordCountLambdaResult.

8. Add the saveResponseLambda service model action.

a. In the flow designer, select the saveResponseLambda service model.

b. In the action editor that appears in the right pane, choose No action configured.

c. For Action, choose save.

d. Expand Inputs, choose Define Input, and then for response, enter

${wordCountLambdaResult}.

9. Publish the flow.

Choose Publish at the upper right of the page. This creates the flow and adds it to the list of flows that can be deployed.

Create and deploy the flow configuration

1. On the Flows list page, select the box next to the flow that you just created, and then choose Create flow configuration.

(40)

2. Name the flow configuration.

On the Describe flow configuration page, select your flow and enter a flow configuration name. The flow configuration name can't contain spaces. Choose Greengrass, and then choose Next.

3. Configure the target.

On the Configure target page, enter the name of your Amazon S3 bucket and the AWS IoT Greengrass group to which your AWS IoT Greengrass core device belongs. Amazon S3 buckets are globally unique, so your bucket name will be different from the one in the following screen shot.

Choose Next.

4. Select things.

This example contains only service models, so you don't have to select any things to use in the flow.

Choose Next.

5. View the trigger.

(41)

On the Define trigger page, the following GraphQL appears in the editor. This GraphQL specifies the time intervals at which the flow runs. This flow runs every 60 seconds. You don't need to edit this code.

Choose Review.

6. Review and create.

On the Review and create page, review the information you entered for your flow configuration.

Choose Create.

7. Deploy.

When the Flow configuration created message appears, choose Deploy now.

Refresh the Deployments page to verify that the flow has deployed. After a successful deployment, the Deployments page displays Deployed in target in the Status column.

(42)

Run the flow

After a flow is deployed, it runs automatically every 60 seconds. You can verify that it's running by going to your Amazon S3 bucket. You should see a new file named word-count-response in the bucket.

Delete the flow and flow configuration (optional)

For instructions on how to undeploy a flow configuration, and delete the flow configuration and flow that you've created, see Deleting flow configurations and Deleting systems, flows, and namespaces in Lifecycle management for AWS IoT Things Graph entities, flows, systems, and deployments.

Creating a flow with devices and a service

This topic walks you through the steps to create and deploy a simple workflow (flow) that consists of a Raspberry Pi connected to three devices: an Aukru HC-SR501 motion sensor, a Raspberry Pi camera, and a Raspberry Pi screen. It also contains an AWS IoT Things Graph service model that exposes the face detection capability of Amazon Rekognition.

The flow is triggered when the motion detector detects a person moving. The motion detector sends a message to the camera, which takes a picture and sends it to the Amazon Rekognition service model. The service model sends the image to display to the screen. The service model doesn't process the results of the DetectFaces API or send anything other than the image to the screen.

You can modify this example by adding a service model between the Amazon Rekognition service and the screen. The additional service model can process the results (such as determining whether the image should be displayed on the screen) before sending the image to the screen.

Prerequisites

To create this example, you need the following resources:

• An AWS account

• A Raspberry Pi running AWS IoT Greengrass version 1.7 or later

• An Aukru HC-SR501 motion sensor

• A Raspberry Pi 7" touchscreen display

• A Raspberry Pi camera module v2-8 megapixel,1080p

• An Amazon S3 bucket

Set up your Raspberry Pi

To run the workflow (flow), you need to set up your Raspberry Pi.

• Attach your motion sensor to Raspberry Pi GPIO pin 1.

• Attach the camera by following the instructions in the Raspberry Pi camera board documentation.

Attach the screen by following the instructions in the Raspberry Pi 7" touch screen assembly guide.

• Download and install the drivers included in the ThingsGraphPrototypeDevices.zip file. Follow the instructions in the README to install the drivers.

Now you've configured your Raspberry Pi to communicate with the motion sensor, camera, and screen.

Create an AWS IoT Greengrass group

NoteFor information about using AWS CloudFormation to create and manage AWS IoT Greengrass groups and resources, see AWS IoT Greengrass resource types reference.

參考文獻

相關文件

• The  ArrayList class is an example of a  collection class. • Starting with version 5.0, Java has added a  new kind of for loop called a for each

• The memory storage unit holds instructions and data for a running program.. • A bus is a group of wires that transfer data from one part to another (data,

Various programming languages used to create computer programs A variety of Web development and multimedia development tools. Steps in the program development life cycle and tools

The/That new smartphone has a better camera and (a) thinner screen than the/that old

Once you get down to a purely business level, your influence is gone and the true light of your life isdimmed. You must work in the missionary spirit, with a breadth of charity

It is intended in this project to integrate the similar curricula in the Architecture and Construction Engineering departments to better yet simpler ones and to create also a new

We explicitly saw the dimensional reason for the occurrence of the magnetic catalysis on the basis of the scaling argument. However, the precise form of gap depends

• The memory storage unit holds instructions and data for a running program.. • A bus is a group of wires that transfer data from one part to another (data,