

# AWS IoT SiteWise tutorials
<a name="tutorials"></a>

Welcome to the AWS IoT SiteWise tutorials page. This growing collection of tutorials empowers you with the knowledge and skills needed to navigate the intricacies of AWS IoT SiteWise. These tutorials offer a diverse range of basic topics to cater to your needs. As you delve into the tutorials, uncover invaluable insights into various aspects of AWS IoT SiteWise.

Each tutorial uses a specific equipment example. These tutorials are intended for test environments, and they use fictitious company names, models, assets, properties, and so on. Their purpose is to provide general guidance. The tutorials are not intended for direct use in a production environment without careful review and adaptation to meet the unique needs of your organization.

**Topics**
+ [Calculate OEE in AWS IoT SiteWise](calculate-oee.md)
+ [Ingest data to AWS IoT SiteWise from AWS IoT things](ingest-data-from-iot-things.md)
+ [Integrate data into SiteWise Edge using an MQTT-enabled, V3 gateway](integrate_sitewise_edge_mqtt.md)
+ [Visualize and share data in Grafana](visualize-with-grafana.md)
+ [Visualize and share wind farm data in SiteWise Monitor](monitor-wind-farm.md)
+ [Publish property value updates to Amazon DynamoDB](publish-to-amazon-dynamodb.md)

# Calculate OEE in AWS IoT SiteWise
<a name="calculate-oee"></a>

This tutorial provides an example of how to calculate overall equipment effectiveness (OEE) for a manufacturing process. As a result, your OEE calculations or formulas might differ from those shown here. In general, OEE is defined as `Availability * Quality * Performance`. To learn more about calculating OEE, see [Overall equipment effectiveness](https://en.wikipedia.org/wiki/Overall_equipment_effectiveness) on *Wikipedia*.

## Prerequisites
<a name="oee-requirements"></a>

To complete this tutorial, you must configure data ingestion for a device that has the following three data streams:
+ `Equipment_State` – A numerical code that represents the state of the machine, such as idle, fault, planned stop, or normal operation.
+ `Good_Count` – A data stream where each data point contains the number of successful operations since the last data point.
+ `Bad_Count` – A data stream where each data point contains the number of unsuccessful operations since the last data point.

To configure data ingestion, see [Ingest data to AWS IoT SiteWise](industrial-data-ingestion.md). If you don't have an available industrial operation, you can write a script that generates and uploads sample data through the AWS IoT SiteWise API.

## How to calculate OEE
<a name="how-to-calculate-oee"></a>

In this tutorial, you create an asset model that calculates OEE from three data input streams: `Equipment_State`, `Good_Count`, and `Bad_Count`. In this example, consider a generic packaging machine, such as one that's used for packaging sugar, potato chips, or paint. In the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/), create an AWS IoT SiteWise asset model with the following measurements, transforms, and metrics. Then, you can create an asset to represent the packaging machine and observe how AWS IoT SiteWise calculates OEE.

Define the following [measurements](measurements.md) to represent the raw data streams from the packaging machine.

**Measurements**
+ `Equipment_State` – A data stream (or measurement) that provides the current state of the packaging machine in numerical codes: 
  + `1024` – The machine is idle. 
  + `1020` – A fault, such as an error or delay. 
  + `1000` – A planned stop.
  + `1111` – A normal operation.
+ `Good_Count` – A data stream where each data point contains the number of successful operations since the last data point.
+ `Bad_Count` – A data stream where each data point contains the number of unsuccessful operations since the last data point.

Using the `Equipment_State` measurement data stream and the codes it contains, define the following [transforms](transforms.md) (or derived measurements). Transforms have a one-to-one relationship with raw measurements.

**Transforms**
+ `Idle = eq(Equipment_State, 1024)` – A transformed data stream that contains the machine's idle state.
+ `Fault = eq(Equipment_State, 1020)` – A transformed data stream that contains the machine's fault state.
+ `Stop = eq(Equipment_State, 1000)` – A transformed data stream that contains the machine's planned stop state.
+ `Running = eq(Equipment_State, 1111)` – A transformed data stream that contains the machine's normal operational state.

Using the raw measurements and the transformed measurements, define the following [metrics](metrics.md) that aggregate machine data over specified time intervals. Choose the same time interval for each metric when you define the metrics in this section.

**Metrics**
+ `Successes = sum(Good_Count)` – The number of successfully filled packages over the specified time interval.
+ `Failures = sum(Bad_Count)` – The number of unsuccessfully filled packages over the specified time interval.
+ `Idle_Time = statetime(Idle)` – The machine's total idle time (in seconds) per specified time interval.
+ `Fault_Time = statetime(Fault)` – The machine's total fault time (in seconds) per specified time interval.
+ `Stop_Time = statetime(Stop)` – The machine's total planned stop time (in seconds) per specified time interval.
+ `Run_Time = statetime(Running)` – The machine's total time (in seconds) running without issue per specified time interval.
+ `Down_Time = Idle_Time + Fault_Time + Stop_Time` – The machine's total downtime (in seconds) over the specified time interval, calculated as the sum of the machine states other than `Run_Time`.
+ `Availability = Run_Time / (Run_Time + Down_Time)` – The machine's uptime or percentage of scheduled time that the machine is available to operate over the specified time interval.
+ `Quality = Successes / (Successes + Failures)` – The machine's percentage of successfully filled packages over the specified time intervals.
+ `Performance = ((Successes + Failures) / Run_Time) / Ideal_Run_Rate` – The machine's performance over the specified time interval as a percentage out of the ideal run rate (in seconds) for your process. 

  For example, your `Ideal_Run_Rate` might be 60 packages per minute (1 package per second). If your `Ideal_Run_Rate` is per minute or per hour, you need to divide it by the appropriate unit conversion factor because `Run_Time` is in seconds. 
+ `OEE = Availability * Quality * Performance` – The machine's overall equipment effectiveness over the specified time interval. This formula calculates OEE as a fraction out of 1.

**Note**  
 If OEE is defined as a transform, output values are computed for each of the input values. There is a potential to generate unexpected values as the transform evaluation considers the latest available values for all the contributing properties in the formula. For property updates with the same timestamp, output values may be overwritten by updates from other incoming properties. For example when Availability, Quality, and Performance are computed, the OEE is computed with the last available data points for the other two properties. These contributing values share timestamps, and cause incorrect output values of the OEE. The order is not guaranteed for transforms computation. 

# Ingest data to AWS IoT SiteWise from AWS IoT things
<a name="ingest-data-from-iot-things"></a>

Learn how to ingest data to AWS IoT SiteWise from a fleet of AWS IoT things by using device shadows in this tutorial. *Device shadows* are JSON objects that store current state information for an AWS IoT device. For more information, see [Device shadow service](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html) in the *AWS IoT Developer Guide*.

After you complete this tutorial, you can set up an operation in AWS IoT SiteWise based on AWS IoT things. By using AWS IoT things, you can integrate your operation with other useful features of AWS IoT. For example, you can configure AWS IoT features to do the following tasks:
+ Configure additional rules to stream data to [AWS IoT Events](https://docs.aws.amazon.com/iotevents/latest/developerguide/), [Amazon DynamoDB](https://docs.aws.amazon.com/dynamodb/), and other AWS services. For more information, see [Rules](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) in the *AWS IoT Developer Guide*.
+ Index, search, and aggregate your device data with the AWS IoT fleet indexing service. For more information, see [Fleet indexing service](https://docs.aws.amazon.com/iot/latest/developerguide/iot-indexing.html) in the *AWS IoT Developer Guide*.
+ Audit and secure your devices with AWS IoT Device Defender. For more information, see [AWS IoT Device Defender](https://docs.aws.amazon.com/iot-device-defender/latest/devguide/what-is-device-defender.html) in the *AWS IoT Developer Guide*.

In this tutorial, you learn how to ingest data from AWS IoT things' device shadows to assets in AWS IoT SiteWise. To do so, you create one or more AWS IoT things and run a script that updates each thing's device shadow with CPU and memory usage data. You use CPU and memory usage data in this tutorial to imitate realistic sensor data. Then, you create a rule with an AWS IoT SiteWise action that sends this data to an asset in AWS IoT SiteWise every time a thing's device shadow updates. For more information, see [Ingest data to AWS IoT SiteWise using AWS IoT Core rules](iot-rules.md).

**Topics**
+ [Prerequisites](#rule-ingestion-tutorial-prerequisites)
+ [Step 1: Create an AWS IoT policy](#ingestion-tutorial-create-iot-policy)
+ [Step 2: Create and configure an AWS IoT thing](#rule-tutorial-create-iot-thing)
+ [Step 3: Create a device asset model](#rule-tutorial-create-device-model)
+ [Step 4: Create a device fleet asset model](#rule-tutorial-create-fleet-model)
+ [Step 5: Create and configure a device asset](#rule-tutorial-create-device-assets)
+ [Step 6: Create and configure a device fleet asset](#rule-tutorial-create-fleet-asset)
+ [Step 7: Create a rule in AWS IoT Core to send data to device assets](#rule-tutorial-create-iot-rule)
+ [Step 8: Run the device client script](#rule-tutorial-run-script)
+ [Step 9: Clean up resources after the tutorial](#rule-tutorial-clean-up-resources)

## Prerequisites
<a name="rule-ingestion-tutorial-prerequisites"></a>

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, see [Set up an AWS account](getting-started.md#set-up-aws-account).
+ A development computer running Windows, macOS, Linux, or Unix to access the AWS Management Console. For more information, see [Getting Started with the AWS Management Console](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/getting-started.html).
+ An AWS Identity and Access Management (IAM) user with administrator permissions.
+ Python 3 installed on your development computer or installed on the device that you want to register as an AWS IoT thing.

## Step 1: Create an AWS IoT policy
<a name="ingestion-tutorial-create-iot-policy"></a>

In this procedure, create an AWS IoT policy that allows your AWS IoT things to access the resources used in this tutorial.

------
#### [ Console ]

Use the following procedure to create an AWS IoT policy using the AWS IoT Core console:

**To create an AWS IoT policy**

1. Sign in to the [AWS Management Console](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/what-is.html).

1. Review the [AWS Regions](https://docs.aws.amazon.com/general/latest/gr/iot-sitewise.html) where AWS IoT SiteWise is supported. Switch to one of these supported Regions, if necessary.

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/). If a **Connect device** button appears, choose it.

1. In the left navigation pane, choose **Security** and then choose **Policies**.

1. Choose **Create**.

1. Enter a name for the AWS IoT policy (for example, **SiteWiseTutorialDevicePolicy**).

1. Under **Policy document**, choose **JSON** to enter the following policy in JSON form. Replace *region* and *account-id* with your Region and account ID, such as **us-east-1** and **123456789012**.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Action": "iot:Connect",
         "Resource": "arn:aws:iot:us-east-1:123456789012:client/SiteWiseTutorialDevice*"
       },
       {
         "Effect": "Allow",
         "Action": "iot:Publish",
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get"
         ]
       },
       {
         "Effect": "Allow",
         "Action": "iot:Receive",
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/accepted",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/accepted",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/accepted",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/rejected",
           "arn:aws:iot:us-east-1:123456789012:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/rejected"
         ]
       },
       {
         "Effect": "Allow",
         "Action": "iot:Subscribe",
         "Resource": [
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/accepted",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/accepted",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/get/accepted",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/update/rejected",
           "arn:aws:iot:us-east-1:123456789012:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/delete/rejected"
         ]
       },
       {
         "Effect": "Allow",
         "Action": [
           "iot:GetThingShadow",
           "iot:UpdateThingShadow",
           "iot:DeleteThingShadow"
         ],
         "Resource": "arn:aws:iot:us-east-1:123456789012:thing/SiteWiseTutorialDevice*"
   
       }
     ]
   }
   ```

------

1. Choose **Create**.

------
#### [ AWS CLI ]

**Important**  
This policy uses wildcards to stay within AWS IoT SiteWise CLI size limits. For more restrictive permissions with explicit topic paths, create the policy through the AWS IoT SiteWise console instead. For more information, see the IoT policy example provided on the tab.

Use the following AWS CLI command to create an IoT policy:

```
aws iot create-policy \
  --policy-name "SiteWiseTutorialDevicePolicy" \
  --policy-document '{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": "iot:Connect",
        "Resource": "arn:aws:iot:region:account-id:client/SiteWiseTutorialDevice*"
      },
      {
        "Effect": "Allow",
        "Action": ["iot:Publish", "iot:Receive"],
        "Resource": [
          "arn:aws:iot:region:account-id:topic/$aws/things/${iot:Connection.Thing.ThingName}/shadow/*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": "iot:Subscribe",
        "Resource": [
          "arn:aws:iot:region:account-id:topicfilter/$aws/things/${iot:Connection.Thing.ThingName}/shadow/*"
        ]
      },
      {
        "Effect": "Allow",
        "Action": [
          "iot:GetThingShadow",
          "iot:UpdateThingShadow",
          "iot:DeleteThingShadow"
        ],
        "Resource": "arn:aws:iot:region:account-id:thing/SiteWiseTutorialDevice*"
      }
    ]
  }'
```

To verify that your policy was created successfully, use the following command:

```
aws iot get-policy --policy-name "SiteWiseTutorialDevicePolicy"
```

------

This policy enables your AWS IoT devices to establish connections and communicate with device shadows using MQTT messages. For more information about MQTT messages, see [What is MQTT?](https://aws.amazon.com/what-is/mqtt/). To interact with device shadows, your AWS IoT things publish and receive MQTT messages on topics that start with `$aws/things/thing-name/shadow/`. This policy incorporates a thing policy variable known as `${iot:Connection.Thing.ThingName}`. This variable substitutes the connected thing's name in each topic. The `iot:Connect` statement sets limitations on which devices can establish connections, ensuring that the thing policy variable can only substitute names starting with `SiteWiseTutorialDevice`.

For more information, see [Thing policy variables](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policy-variables.html) in the *AWS IoT Developer Guide*.

**Note**  
This policy applies to things whose names start with `SiteWiseTutorialDevice`. To use a different name for your things, you must update the policy accordingly.

## Step 2: Create and configure an AWS IoT thing
<a name="rule-tutorial-create-iot-thing"></a>

In this procedure, you create and configure an AWS IoT thing. You can designate your development computer as an AWS IoT thing. As you progress, remember that the principles you're learning here can be applied to actual projects. You have the flexibility to make and set up AWS IoT things on any device capable of running an AWS IoT SDK, including AWS IoT Greengrass and FreeRTOS. For more information, see [AWS IoT SDKs](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html) in the *AWS IoT Developer Guide*.

------
#### [ Console ]

**To create and configure an AWS IoT thing**

1. Open a command line and run the following command to create a directory for this tutorial.

   ```
   mkdir iot-sitewise-rule-tutorial
   cd iot-sitewise-rule-tutorial
   ```

1. Run the following command to create a directory for your thing's certificates.

   ```
   mkdir device1
   ```

   If you're creating additional things, increment the number in the directory name accordingly to keep track of which certificates belong to which thing.

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **All devices** in the **Manage** section. Then choose **Things**.

1. If a **You don't have any things yet** dialog box appears, choose **Create a thing**. Otherwise, choose **Create things**.

1. On the **Creating things** page, choose **Create a single thing** and then choose **Next**.

1. On the **Specify thing properties** page, enter a name for your AWS IoT thing (for example, **SiteWiseTutorialDevice1**) and then choose **Next**. If you're creating additional things, increment the number in the thing name accordingly.
**Important**  
The thing name must match the name used in the policy that you created in *Step 1: Creating an AWS IoT policy*. Otherwise, your device can't connect to AWS IoT.

1. On the **Configure device certificate - *optional*** page, choose **Auto-generate a new certificate (recommended)**, then choose **Next**. Certificates enable AWS IoT to securely identify your devices.

1. On the **Attach policies to certificate - *optional*** page, select the policy you created in *Step 1: Creating an AWS IoT policy* and choose **Create thing**.

1. On the **Download certificates and keys** dialog box, do the following:

   1. Choose the **Download** links to download your thing's certificate, public key, and private key. Save all three files to the directory that you created for your thing's certificates (for example, **iot-sitewise-rule-tutorial/device1**).
**Important**  
This is the only time that you can download your thing's certificate and keys, which you need for your device to successfully connect to AWS IoT.

   1. Choose the **Download** link to download a root CA certificate. Save the root CA certificate to the **iot-sitewise-rule-tutorial**. We recommend downloading Amazon Root CA 1.

1. Choose **Done**.

------
#### [ AWS CLI ]

Follow these steps to create and configure an AWS IoT thing using the AWS CLI:

1. Open a command line and run the following command to create a directory for this tutorial:

   ```
   mkdir iot-sitewise-rule-tutorial
   ```

1. Navigate to the tutorial directory:

   ```
   cd iot-sitewise-rule-tutorial
   ```

1. Run the following command to create a directory for your thing's certificates:

   ```
   mkdir device1
   ```

   If you're creating additional things, increment the number in the directory name accordingly to keep track of which certificates belong to which thing.

1. Create an AWS IoT thing:

   ```
   aws iot create-thing --thing-name "SiteWiseTutorialDevice1"
   ```
**Important**  
The thing name must match the name pattern used in the policy that you created in Step 1. Otherwise, your device can't connect to AWS IoT.

1. Create a certificate and save the files. Note the certificate ARN from the output - you'll need it in the next steps:

   ```
   aws iot create-keys-and-certificate \
       --set-as-active \
       --certificate-pem-outfile "device1/device.pem.crt" \
       --public-key-outfile "device1/public.pem.key" \
       --private-key-outfile "device1/private.pem.key"
   ```

1. Attach the policy you created in Step 1 to the certificate:

   ```
   aws iot attach-policy \
       --policy-name "SiteWiseTutorialDevicePolicy" \
       --target "certificate-arn"
   ```

1. Attach the certificate to the thing:

   ```
   aws iot attach-thing-principal \
       --thing-name "SiteWiseTutorialDevice1" \
       --principal "certificate-arn"
   ```

1. Download the Amazon root CA certificate:

   ```
   curl https://www.amazontrust.com/repository/AmazonRootCA1.pem > AmazonRootCA1.pem
   ```

   This certificate is required for your device to successfully connect to AWS IoT.

**Important**  
Store your certificates and keys securely. You cannot download these credentials again after creating them.

------

You have now registered an AWS IoT thing on your computer. Take one of the following next steps:
+ Continue to *Step 3: Creating a device asset model* without creating additional AWS IoT things. You can complete this tutorial with only one thing.
+ Repeat the steps in this section on another computer or device to create more AWS IoT things. For this tutorial, we recommend that you follow this option so that you can ingest unique CPU and memory usage data from multiple devices.
+ Repeat the steps in this section on the same device (your computer) to create more AWS IoT things. Each AWS IoT thing receives similar CPU and memory usage data from your computer, so use this approach to demonstrate ingesting non-unique data from multiple devices.

## Step 3: Create a device asset model
<a name="rule-tutorial-create-device-model"></a>

In this procedure, you create an asset model in AWS IoT SiteWise to represent your devices that stream CPU and memory usage data. To process data in assets that represent groups of devices, asset models enforce consistent information across multiple assets of the same type. For more information, see [Model industrial assets](industrial-asset-models.md).

**To create an asset model that represents a device**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Models**.

1. Choose **Create asset model**.

1. Under **Model details**, enter a name for your model. For example, **SiteWise Tutorial Device Model**.

1. Under **Measurement definitions**, do the following:

   1. In **Name**, enter **CPU Usage**.

   1. In **Unit**, enter **%**.

   1. Leave the **Data type** as **Double**.

   Measurement properties represent a device's raw data streams. For more information, see [Define data streams from equipment (measurements)](measurements.md).

1. Choose **Add new measurement** to add a second measurement property.

1. In the second row under **Measurement definitions**, do the following:

   1. In **Name**, enter **Memory Usage**.

   1. In **Unit**, enter **%**.

   1. Leave the **Data type** as **Double**.

1. Under **Metric definitions**, do the following:

   1. In **Name**, enter **Average CPU Usage**.

   1. In **Formula**, enter **avg(CPU Usage)**. Choose **CPU Usage** from the autocomplete list when it appears.

   1. In **Time interval**, enter **5 minutes**.

   Metric properties define aggregation calculations that process all input data points over an interval and output a single data point per interval. This metric property calculates each device's average CPU usage every 5 minutes. For more information, see [Aggregate data from properties and other assets (metrics)](metrics.md).

1. Choose **Add new metric** to add a second metric property.

1. In the second row under **Metric definitions**, do the following:

   1. In **Name**, enter **Average Memory Usage**.

   1. In **Formula**, enter **avg(Memory Usage)**. Choose **Memory Usage** from the autocomplete list when it appears.

   1. In **Time interval**, enter **5 minutes**.

   This metric property calculates each device's average memory usage every 5 minutes.

1. (Optional) Add other additional metrics that you're interested in calculating per device. Some interesting functions include `min` and `max`. For more information, see [Use formula expressions](formula-expressions.md). In *Step 4: Creating a device fleet asset model*, you create a parent asset that can calculate metrics using data from your entire fleet of devices.

1. Choose **Create model**.

## Step 4: Create a device fleet asset model
<a name="rule-tutorial-create-fleet-model"></a>

In this procedure, you craft an asset model in AWS IoT SiteWise to symbolize your collection of devices. Within this asset model, you establish a structure that allows you to link numerous device assets to one overarching fleet asset. Following that, you outline metrics in the fleet asset model to consolidate data from all connected device assets. This approach provides you with comprehensive insights into the collective performance of your entire fleet.

**To create an asset model that represents a device fleet**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Models**.

1. Choose **Create asset model**.

1. Under **Model details**, enter a name for your model. For example, **SiteWise Tutorial Device Fleet Model**.

1. Under **Hierarchy definitions**, do the following:

   1. In **Hierarchy name**, enter **Device**.

   1. In **Hierarchy model**, choose your device asset model (**SiteWise Tutorial Device Model**).

   A hierarchy defines a relationship between a parent (fleet) asset model and a child (device) asset model. Parent assets can access child assets' property data. When you create assets later, you need to associate child assets to parent assets according to a hierarchy definition in the parent asset model. For more information, see [Asset hierarchies represent equipment relationships](industrial-asset-models.md#asset-hierarchies).

1. Under **Metric definitions**, do the following:

   1. In **Name**, enter **Average CPU Usage**.

   1. In **Formula**, enter **avg(Device \$1 Average CPU Usage)**. When the autocomplete list appears, choose **Device** to choose a hierarchy, then choose **Average CPU Usage** to choose the metric from the device asset that you created earlier.

   1. In **Time interval**, enter **5 minutes**.

   This metric property calculates the average CPU usage of all device assets associated to a fleet asset through the **Device** hierarchy.

1. Choose **Add new metric** to add a second metric property.

1. In the second row under **Metric definitions**, do the following:

   1. In **Name**, enter **Average Memory Usage**.

   1. In **Formula**, enter **avg(Device \$1 Average Memory Usage)**. When the autocomplete list appears, choose **Device** to choose a hierarchy, then choose **Average Memory Usage** to choose the metric from the device asset that you created earlier.

   1. In **Time interval**, enter **5 minutes**.

   This metric property calculates the average memory usage of all device assets associated to a fleet asset through the **Device** hierarchy.

1. (Optional) Add other additional metrics that you're interested in calculating across your fleet of devices.

1. Choose **Create model**.

## Step 5: Create and configure a device asset
<a name="rule-tutorial-create-device-assets"></a>

In this procedure, you generate a device asset that's based on your device asset model. Then, you define property aliases for each measurement property. A *property alias* is a unique string that identifies an asset property. Later, you can identify a property for data upload by using the aliases instead of the asset ID and property ID. For more information, see [Manage data streams for AWS IoT SiteWise](manage-data-streams.md). 

**To create a device asset and define property aliases**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Assets**.

1. Choose **Create asset**.

1. Under **Model information**, choose your device asset model, **SiteWise Tutorial Device Model**.

1. Under **Asset information**, enter a name for your asset. For example, **SiteWise Tutorial Device 1**.

1. Choose **Create asset**.

1. For your new device asset, choose **Edit**.

1. Under **Measurements**:

   1. Under **CPU Usage**, enter **/tutorial/device/SiteWiseTutorialDevice1/cpu** as the property alias. You include the AWS IoT thing's name in the property alias, so that you can ingest data from all of your devices using a single AWS IoT rule.

   1. Under **Memory Usage**, enter **/tutorial/device/SiteWiseTutorialDevice1/memory** as the property alias.

1. Choose **Save**.

If you created multiple AWS IoT things earlier, repeat steps 3 through 10 for each device, and increment the number in the asset name and property aliases accordingly. For example, the second device asset's name should be **SiteWise Tutorial Device 2**, and its property aliases should be **/tutorial/device/SiteWiseTutorialDevice2/cpu**, and **/tutorial/device/SiteWiseTutorialDevice2/memory**.

## Step 6: Create and configure a device fleet asset
<a name="rule-tutorial-create-fleet-asset"></a>

In this procedure, you form a device fleet asset derived from your device fleet asset model. Then, you link your individual device assets to the fleet asset. This association enables the metric properties of the fleet asset to compile and analyze data from multiple devices. This data provides you with a consolidated view of the collective performance of the entire fleet.

**To create a device fleet asset and associate device assets**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Assets**.

1. Choose **Create asset**.

1. Under **Model information**, choose your device fleet asset model, **SiteWise Tutorial Device Fleet Model**.

1. Under **Asset information**, enter a name for your asset. For example, **SiteWise Tutorial Device Fleet 1**.

1. Choose **Create asset**.

1. For your new device fleet asset, choose **Edit**.

1. Under **Assets associated to this asset**, choose **Add associated asset** and do the following:

   1. Under **Hierarchy**, choose **Device**. This hierarchy identifies the hierarchical relationship between device and device fleet assets. You defined this hierarchy in the device fleet asset model earlier in this tutorial.

   1. Under **Asset**, choose your device asset, **SiteWise Tutorial Device 1**.

1. (Optional) If you created multiple device assets earlier, repeat steps 8 through 10 for each device asset that you created.

1. Choose **Save**.

   You should now see your device assets organized as a hierarchy.

## Step 7: Create a rule in AWS IoT Core to send data to device assets
<a name="rule-tutorial-create-iot-rule"></a>

In this procedure, you establish a rule in AWS IoT Core. The rule is designed to interpret notification messages from device shadows and transmit the data to your device assets in AWS IoT SiteWise. Each time your device's shadow updates, AWS IoT sends an MQTT message. You can create a rule that takes action when device shadows change based on the MQTT message. In this case, the aim is to handle the update message, extract the property values, and transmit them to your device assets in AWS IoT SiteWise. 

**To create a rule with an AWS IoT SiteWise action**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Message routing** and then choose **Rules**.

1. Choose **Create rule**.

1. Enter a name and description for your rule and the choose **Next**.

1. Enter the following SQL statement and the choose **Next**.

   ```
   SELECT
     *
   FROM
     '$aws/things/+/shadow/update/accepted'
   WHERE
     startsWith(topic(3), "SiteWiseTutorialDevice")
   ```

   This rule query statement works because the device shadow service publishes shadow updates to `$aws/things/thingName/shadow/update/accepted`. For more information about device shadows, see [Device shadow service](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html) in the *AWS IoT Developer Guide*.

   In the `WHERE` clause, this rule query statement uses the `topic(3)` function to get the thing name from the third segment of the topic. Then, the statement filters out devices that have names that don't match those of the tutorial devices. For more information about AWS IoT SQL, see [AWS IoT SQL reference](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-reference.html) in the *AWS IoT Developer Guide*.

1. Under **Rule actions**, choose **Send message data to asset properties in AWS IoT SiteWise** and do the following:

   1. Choose **By property alias**.

   1. In **Property alias**, enter **/tutorial/device/\$1\$1topic(3)\$1/cpu**.

      The `${...}` syntax is a substitution template. AWS IoT evaluates the contents within the braces. This substitution template pulls the thing name from the topic to create an alias unique to each thing. For more information, see [Substitution templates](https://docs.aws.amazon.com/iot/latest/developerguide/iot-substitution-templates.html) in the *AWS IoT Developer Guide*.
**Note**  <a name="substitution-template-limitations"></a>
Because an expression in a substitution template is evaluated separately from the `SELECT` statement, you can't use a substitution template to reference an alias created using an `AS` clause. You can reference only information present in the original payload, in addition to supported functions and operators.

   1. In **Entry ID - *optional***, enter **\$1\$1concat(topic(3), "-cpu-", floor(state.reported.timestamp))\$1**.

      Entry IDs uniquely identify each value entry attempt. If an entry returns an error, you can find the entry ID in the error output to troubleshoot the issue. The substitution template in this entry ID combines the thing name and the device's reported timestamp. For example, the resulting entry ID might look like `SiteWiseTutorialDevice1-cpu-1579808494`.

   1. In **Time in seconds**, enter **\$1\$1floor(state.reported.timestamp)\$1**.

      This substitution template calculates the time in seconds from the device's reported timestamp. In this tutorial, devices report timestamp in seconds in Unix epoch time as a floating point number.

   1. In **Offset in nanos - *optional***, enter **\$1\$1floor((state.reported.timestamp % 1) \$1 1E9)\$1**.

      This substitution template calculates the nanosecond offset from the time in seconds by converting the decimal portion of the device's reported timestamp.
**Note**  
AWS IoT SiteWise requires that your data has a current timestamp in Unix epoch time. If your devices don't report time accurately, you can get the current time from the AWS IoT rules engine with [timestamp()](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-function-timestamp). This function reports time in milliseconds, so you must update your rule action's time parameters to the following values:  
In **Time in seconds**, enter **\$1\$1floor(timestamp() / 1E3)\$1**.
In **Offset in nanos**, enter **\$1\$1(timestamp() % 1E3) \$1 1E6\$1**.

   1. In **Data type**, choose **Double**.

      This data type must match the data type of the asset property you defined in the asset model.

   1. In **Value**, enter **\$1\$1state.reported.cpu\$1**. In substitution templates, you use the `.` operator to retrieve a value from within a JSON structure.

   1. Choose **Add entry** to add a new entry for the memory usage property, and complete the following steps again for that property:

      1. Choose **By property alias**.

      1. In **Property alias**, enter **/tutorial/device/\$1\$1topic(3)\$1/memory**.

      1. In **Entry ID - *optional***, enter **\$1\$1concat(topic(3), "-memory-", floor(state.reported.timestamp))\$1**.

      1. In **Time in seconds**, enter **\$1\$1floor(state.reported.timestamp)\$1**.

      1. In **Offset in nanos - *optional***, enter **\$1\$1floor((state.reported.timestamp % 1) \$1 1E9)\$1**.

      1. In **Data type**, choose **Double**.

      1. In **Value**, enter **\$1\$1state.reported.memory\$1**.

   1. Under **IAM Role**, choose **Create new role** to create an IAM role for this rule action. This role allows AWS IoT to push data to properties in your device fleet asset and its asset hierarchy.

   1. Enter a role name and choose **Create**.

1. (Optional) Configure an error action that you can use to troubleshoot your rule. For more information, see [Troubleshoot a rule (AWS IoT SiteWise)](troubleshoot-rule.md#rule-tutorial-troubleshoot-rule).

1. Choose **Next**.

1. Review the settings and choose **Create** to create the rule.

## Step 8: Run the device client script
<a name="rule-tutorial-run-script"></a>

For this tutorial, you aren't using an actual device to report data. Instead, you run a script to update your AWS IoT thing's device shadow with CPU and memory usage to imitate real sensor data. To run the script, you must first install required Python packages. In this procedure, you install the required Python packages and then run the device client script.

**To configure and run the device client script**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. At the bottom of the left navigation pane, choose **Settings**.

1. Save your custom endpoint for use with the device client script. You use this endpoint to interact with your thing's shadows. This endpoint is unique to your account in the current Region.

   Your custom endpoint should look like the following example.

   ```
   identifier.iot.region.amazonaws.com
   ```

1. Open a command line and run the following command to navigate to the tutorial directory you created earlier.

   ```
   cd iot-sitewise-rule-tutorial
   ```

1. Run the following command to install the AWS IoT Device SDK for Python.

   ```
   pip3 install AWSIoTPythonSDK
   ```

   For more information, see [AWS IoT Device SDK for Python](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html#iot-python-sdk) in the *AWS IoT Developer Guide*

1. Run the following command to install psutil, a cross-platform process and system utilities library.

   ```
   pip3 install psutil
   ```

   For more information, see [psutil](https://pypi.org/project/psutil/) in the *Python Package Index*.

1. Create a file called `thing_performance.py` in the `iot-sitewise-rule-tutorial` directory and then copy the following Python code into the file.

   ```
   import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT
   
   import json
   import psutil
   import argparse
   import logging
   import time
   
   
   # Configures the argument parser for this program.
   def configureParser():
       parser = argparse.ArgumentParser()
       parser.add_argument(
           "-e",
           "--endpoint",
           action="store",
           required=True,
           dest="host",
           help="Your AWS IoT custom endpoint",
       )
       parser.add_argument(
           "-r",
           "--rootCA",
           action="store",
           required=True,
           dest="rootCAPath",
           help="Root CA file path",
       )
       parser.add_argument(
           "-c",
           "--cert",
           action="store",
           required=True,
           dest="certificatePath",
           help="Certificate file path",
       )
       parser.add_argument(
           "-k",
           "--key",
           action="store",
           required=True,
           dest="privateKeyPath",
           help="Private key file path",
       )
       parser.add_argument(
           "-p",
           "--port",
           action="store",
           dest="port",
           type=int,
           default=8883,
           help="Port number override",
       )
       parser.add_argument(
           "-n",
           "--thingName",
           action="store",
           required=True,
           dest="thingName",
           help="Targeted thing name",
       )
       parser.add_argument(
           "-d",
           "--requestDelay",
           action="store",
           dest="requestDelay",
           type=float,
           default=1,
           help="Time between requests (in seconds)",
       )
       parser.add_argument(
           "-v",
           "--enableLogging",
           action="store_true",
           dest="enableLogging",
           help="Enable logging for the AWS IoT Device SDK for Python",
       )
       return parser
   
   
   # An MQTT shadow client that uploads device performance data to AWS IoT at a regular interval.
   class PerformanceShadowClient:
       def __init__(
           self,
           thingName,
           host,
           port,
           rootCAPath,
           privateKeyPath,
           certificatePath,
           requestDelay,
       ):
           self.thingName = thingName
           self.host = host
           self.port = port
           self.rootCAPath = rootCAPath
           self.privateKeyPath = privateKeyPath
           self.certificatePath = certificatePath
           self.requestDelay = requestDelay
   
       # Updates this thing's shadow with system performance data at a regular interval.
       def run(self):
           print("Connecting MQTT client for {}...".format(self.thingName))
           mqttClient = self.configureMQTTClient()
           mqttClient.connect()
           print("MQTT client for {} connected".format(self.thingName))
           deviceShadowHandler = mqttClient.createShadowHandlerWithName(
               self.thingName, True
           )
   
           print("Running performance shadow client for {}...\n".format(self.thingName))
           while True:
               performance = self.readPerformance()
               print("[{}]".format(self.thingName))
               print("CPU:\t{}%".format(performance["cpu"]))
               print("Memory:\t{}%\n".format(performance["memory"]))
               payload = {"state": {"reported": performance}}
               deviceShadowHandler.shadowUpdate(
                   json.dumps(payload), self.shadowUpdateCallback, 5
               )
               time.sleep(args.requestDelay)
   
       # Configures the MQTT shadow client for this thing.
       def configureMQTTClient(self):
           mqttClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient(self.thingName)
           mqttClient.configureEndpoint(self.host, self.port)
           mqttClient.configureCredentials(
               self.rootCAPath, self.privateKeyPath, self.certificatePath
           )
           mqttClient.configureAutoReconnectBackoffTime(1, 32, 20)
           mqttClient.configureConnectDisconnectTimeout(10)
           mqttClient.configureMQTTOperationTimeout(5)
           return mqttClient
   
       # Returns the local device's CPU usage, memory usage, and timestamp.
       def readPerformance(self):
           cpu = psutil.cpu_percent()
           memory = psutil.virtual_memory().percent
           timestamp = time.time()
           return {"cpu": cpu, "memory": memory, "timestamp": timestamp}
   
       # Prints the result of a shadow update call.
       def shadowUpdateCallback(self, payload, responseStatus, token):
           print("[{}]".format(self.thingName))
           print("Update request {} {}\n".format(token, responseStatus))
   
   
   # Configures debug logging for the AWS IoT Device SDK for Python.
   def configureLogging():
       logger = logging.getLogger("AWSIoTPythonSDK.core")
       logger.setLevel(logging.DEBUG)
       streamHandler = logging.StreamHandler()
       formatter = logging.Formatter(
           "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
       )
       streamHandler.setFormatter(formatter)
       logger.addHandler(streamHandler)
   
   
   # Runs the performance shadow client with user arguments.
   if __name__ == "__main__":
       parser = configureParser()
       args = parser.parse_args()
       if args.enableLogging:
           configureLogging()
       thingClient = PerformanceShadowClient(
           args.thingName,
           args.host,
           args.port,
           args.rootCAPath,
           args.privateKeyPath,
           args.certificatePath,
           args.requestDelay,
       )
       thingClient.run()
   ```

1. Run **thing\$1performance.py** from the command line with the following parameters:
   + `-n`, `--thingName` – Your thing name, such as **SiteWiseTutorialDevice1**.
   + `-e`, `--endpoint` – Your custom AWS IoT endpoint that you saved earlier in this procedure.
   + `-r`, `--rootCA` – The path to your AWS IoT root CA certificate.
   + `-c`, `--cert` – The path to your AWS IoT thing certificate.
   + `-k`, `--key` – The path to your AWS IoT thing certificate private key.
   + `-d`, `--requestDelay` – (Optional) The time in seconds to wait between each device shadow update. Defaults to 1 second.
   + `-v`, `--enableLogging` – (Optional) If this parameter is present, the script prints debug messages from the AWS IoT Device SDK for Python.

   Your command should look similar to the following example.

   ```
   python3 thing_performance.py \
     --thingName SiteWiseTutorialDevice1 \
     --endpoint identifier.iot.region.amazonaws.com \
     --rootCA AmazonRootCA1.pem \
     --cert device1/thing-id-certificate.pem.crt \
     --key device1/thing-id-private.pem.key
   ```

   If you're running the script for additional AWS IoT things, update the thing name and certificate directory accordingly.

1. Try opening and closing programs on your device to see how the CPU and memory usages change. The script prints each CPU and memory usage reading. If the script uploads data to the device shadow service successfully, the script's output should look like the following example.

   ```
   [SiteWiseTutorialDevice1]
   CPU:    24.6%
   Memory: 85.2%
   
   [SiteWiseTutorialDevice1]
   Update request e6686e44-fca0-44db-aa48-3ca81726f3e3 accepted
   ```

1. Follow these steps to verify that the script is updating the device shadow:

   1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

   1. In the left navigation pane, choose **All devices** and then choose **Things**.

   1. Choose your thing, **SiteWiseTutorialDevice**.

   1. Choose the **Device Shadows** tab, choose **Classic Shadow**, and verify that the **Shadow state** looks like the following example.

      ```
      {
        "reported": {
          "cpu": 24.6,
          "memory": 85.2,
          "timestamp": 1579567542.2835066
        }
      }
      ```

      If your thing's shadow state is empty or doesn't look like the previous example, check that the script is running and successfully connected to AWS IoT. If the script continues to time out when connecting to AWS IoT, check that your [thing policy](#ingestion-tutorial-create-iot-policy) is configured according to this tutorial.

1. Follow these steps to verify that the rule action is sending data to AWS IoT SiteWise:

   1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

   1. In the left navigation pane, choose **Assets**.

   1. Choose the arrow next to your device fleet asset (**SiteWise Tutorial Device Fleet 1**) to expand its asset hierarchy, and then choose your device asset (**SiteWise Tutorial Device 1**).

   1. Choose **Measurements**.

   1. Verify that the **Latest value** cells have values for the **CPU Usage** and **Memory Usage** properties.  
![\[Screenshot with "Measurements" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/rule-ingestion/sitewise-view-measurement-values-console.png)

   1. If the **CPU Usage** and **Memory Usage** properties don't have the latest values, refresh the page. If values don't appear after a few minutes, see [Troubleshoot a rule (AWS IoT SiteWise)](troubleshoot-rule.md#rule-tutorial-troubleshoot-rule).

You have completed this tutorial. If you want to explore live visualizations of your data, you can configure a portal in AWS IoT SiteWise Monitor. For more information, see [Monitor data with AWS IoT SiteWise Monitor](monitor-data.md). Otherwise, you can press **CTRL\$1C** in your command prompt to stop the device client script. It's unlikely the Python program will send enough messages to incur charges, but it's a best practice to stop the program when you're done.

## Step 9: Clean up resources after the tutorial
<a name="rule-tutorial-clean-up-resources"></a>

**Note**  
The resources created in this tutorial are required for the [Integrate data into SiteWise Edge](integrate_sitewise_edge_mqtt.md) tutorial. Do not clean up the resources in this step if you plan on completing it.

After you complete the tutorial about ingesting data from AWS IoT things, clean up your resources to avoid incurring additional charges.<a name="rule-tutorial-delete-assets"></a>

**To delete hierarchical assets in AWS IoT SiteWise**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/)

1. In the left navigation pane, choose **Assets**.

1. When you delete assets in AWS IoT SiteWise, you must first disassociate them.

   Complete the following steps to disassociate your device assets from your device fleet asset:

   1. Choose your device fleet asset (**SiteWise Tutorial Device Fleet 1**).

   1. Choose **Edit**.

   1. Under **Assets associated to this asset**, choose **Disassociate** for each device asset associated to this device fleet asset.

   1. Choose **Save**.

      You should now see your device assets no longer organized as a hierarchy.

1. Choose your device asset (**SiteWise Tutorial Device 1**).

1. Choose **Delete**.

1. In the confirmation dialog, enter **Delete** and then choose **Delete**.

1. Repeat steps 4 through 6 for each device asset and the device fleet asset (**SiteWise Tutorial Device Fleet 1**).

**To delete hierarchical asset models in AWS IoT SiteWise**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. If you haven't already, delete your device and device fleet assets. For more information, see [the previous procedure](#rule-tutorial-delete-assets). You can't delete a model if you have assets that were created from that model.

1. In the left navigation pane, choose **Models**.

1. Choose your device fleet asset model (**SiteWise Tutorial Device Fleet Model**).

   When deleting hierarchical asset models, start by deleting the parent asset model first.

1. Choose **Delete**.

1. In the confirmation dialog, enter **Delete** and then choose **Delete**.

1. Repeat steps 4 through 6 for your device asset model (**SiteWise Tutorial Device Model**).

**To disable or delete a rule in AWS IoT Core**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Message routing** and then choose **Rules**.

1. Select your rule and choose **Delete**.

1. In the confirmation dialog, enter the name of the rule and then choose **Delete**.

# Integrate data into SiteWise Edge using an MQTT-enabled, V3 gateway
<a name="integrate_sitewise_edge_mqtt"></a>

This tutorial guides you through integrating third-party devices and sensors that use MQTT messaging protocol with the AWS IoT SiteWise MQTT-enabled, V3 gateway. You will learn how to set up an AWS IoT SiteWise edge gateway to collect and monitor data from your MQTT-enabled devices. AWS IoT SiteWise enables you to collect, process, and monitor industrial equipment data. Use SiteWise Edge capabilities to optimize industrial IoT operations, and transform raw data into actionable insights.

In this tutorial, we use data from a wind farm demonstration to illustrate key concepts. After you become familiar with the process, you can repeat the tutorial with your own data.

 After you complete this tutorial, you can do the following items:
+ Set up and configure an MQTT-enabled, V3 gateway to receive data from industrial devices
+ Process and validate incoming MQTT messages from your equipment at the edge
+ View device data in AWS IoT SiteWise using a third-party visualization platform
+ Send processed data from your edge gateway to the AWS Cloud to enable centralized storage and further analysis

Additionally, you can leverage your edge gateway capabilities by connecting to other AWS IoT services to perform the following tasks:
+ Configure AWS IoT rules to route data to services like [Amazon S3](https://aws.amazon.com/s3/), [Amazon Timestream](https://aws.amazon.com/timestream/), and [AWS Lambda](https://aws.amazon.com/lambda/).
+ Use [AWS IoT Device Defender](https://aws.amazon.com/iot-device-defender/) to remotely manage and update your gateway configurations.
+ Implement secure device authentication and authorization using AWS IoT security features. For more information, see [AWS IoT security](https://docs.aws.amazon.com/iot/latest/developerguide/iot-security.html) in the *AWS IoT Developer Guide*.
+ Create automated alerts and notifications based on equipment data. For more information, see [Rules for AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) in the *AWS IoT Developer Guide*.

**Note**  
This tutorial references third-party services, tools, and documentation. AWS isn't a vendor or supplier for any third-party products or services, and can't guarantee the accuracy of information from external providers. Evaluate and validate all third-party tools before deployment.

**Topics**
+ [Prerequisites](#gateway-tutorial-prerequisites)
+ [Step 1: Create an AWS IoT policy](#gateway-tutorial-create-iot-policy)
+ [Step 2: Create and configure an AWS IoT thing](#gateway-tutorial-create-and-configure-aws-iot-thing)
+ [Step 3: Configure your SiteWise Edge MQTT-enabled, V3 gateway](#gateway-tutorial-configure-your-edge-gateway)
+ [Step 4: Install SiteWise Edge gateway software](#install-gateway-software)
+ [Step 5: Configure the EMQX broker to connect to external applications](#configure-emqx-broker-external-applications)
+ [Step 6: Publish data with Mosquitto](#add-mqtt-data-source)
+ [Step 7: Specify destinations](#specify-destinations)
+ [Step 8: Specify path filters](#specify-path-filters)
+ [Step 9: Configure your AWS IoT resources](#configure-iot-resources)
+ [Step 10: Visualize your data](#visualize-your-data)
+ [Step 11: Clean up resources after the tutorial](#tutorial-clean-up-resources)
+ [Additional resources](#additional-resources)

## Prerequisites
<a name="gateway-tutorial-prerequisites"></a>

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, see [Set up an AWS account](getting-started.md#set-up-aws-account).
+ An AWS Identity and Access Management (IAM) user with administrator permissions. For more information, see [Identity and access management for AWS IoT SiteWise](security-iam.md).
+ The latest version of Python installed on your device.

**Important**  
This tutorial requires the use of resources created in the [Ingest data](ingest-data-from-iot-things.md) tutorial. You must complete it before proceeding with this tutorial.

## Step 1: Create an AWS IoT policy
<a name="gateway-tutorial-create-iot-policy"></a>

This tutorial uses the AWS IoT policy you created in the [Ingest data](ingest-data-from-iot-things.md) tutorial. This policy sets the security rules for your devices and creates a digital representation of your external devices and sensors in AWS IoT. The policy allows your third-party devices to send data to AWS IoT Core using MQTT (Message Queuing Telemetry Transport). For more information about MQTT messages, see [What is MQTT?](https://aws.amazon.com/what-is/mqtt/).

------
#### [ Console ]

Ensure completion of an AWS IoT policy. For detailed instructions, see [Step 1](ingest-data-from-iot-things.md#ingestion-tutorial-create-iot-policy) in the [Ingest data](ingest-data-from-iot-things.md) tutorial.

**To verify you have an active AWS IoT policy**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Securities**, then **Policies**.

1. Choose the policy you created. For example, **SiteWiseTutorialDevicePolicy**.

1. Confirm that the policy's status is listed as Active.

------
#### [ AWS CLI ]

Ensure completion of an AWS IoT policy. For detailed instruction, see [Step 1](ingest-data-from-iot-things.md#ingestion-tutorial-create-iot-policy) in the [Ingest data](ingest-data-from-iot-things.md) tutorial.

Use the following AWS CLI [get-policy](https://docs.aws.amazon.com/cli/latest/reference/iot/get-policy.html) command in the *AWS CLI Command Reference* to verify you have an active AWS IoT policy:

```
aws iot get-policy --policy-name "SiteWiseTutorialDevicePolicy"
```

------

This policy enables your AWS IoT devices to establish connections and to communicate with device shadows using MQTT messages. To interact with device shadows, your AWS IoT things publish and receive MQTT messages on topics that start with `$aws/things/thing-name/shadow/`. This policy incorporates a thing policy variable known as `${iot:Connection.Thing.ThingName}`. This variable substitutes the connected thing's name in each topic. The `iot:Connect` statement sets limitations on which devices can establish connections, ensuring that the thing policy variable can only substitute names starting with `SiteWiseTutorialDevice`.

For more information, see [Thing policy variables](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policy-variables.html) in the *AWS IoT Developer Guide*.

**Note**  
This policy applies to things whose names start with `SiteWiseTutorialDevice`. To use a different name for your things, you must update the policy accordingly.

## Step 2: Create and configure an AWS IoT thing
<a name="gateway-tutorial-create-and-configure-aws-iot-thing"></a>

In this step, register your edge device as an AWS IoT thing and generate your thing’s certificates and keys needed for secure communication with AWS IoT SiteWise Edge. This process establishes the foundation for your device to send third-party data through your MQTT-enabled, V3 gateway. 

------
#### [ Console ]

Ensure completion of the creation and configuration steps for an AWS IoT thing. For detailed instructions, see [Step 2](ingest-data-from-iot-things.md#rule-tutorial-create-iot-thing) in the [Ingest data](ingest-data-from-iot-things.md) tutorial.

**To verify you have an active AWS IoT thing**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **All devices**, then **Things**.

1. Choose the thing you created. For example, **SiteWiseTutorialDevice1**.

1. Under **Certificates**, confirm that the status is listed as active.

------
#### [ AWS CLI ]

Ensure completion of the creation and configuration steps for an AWS IoT thing. For detailed instructions, see [Step 2](ingest-data-from-iot-things.md#rule-tutorial-create-iot-thing) in the [Ingest data](ingest-data-from-iot-things.md) tutorial.

Use the following AWS CLI command to verify you have an active AWS IoT policy:

```
 aws iot describe-thing --thing-name "SiteWiseTutorialDevice1"
```

------

After completing these steps, you can securely connect your device to AWS IoT SiteWise Edge. You created a local directory to store your certificates and keys you generated for MQTT authentication. Your device is registered as an AWS IoT thing in the [AWS IoT console](https://console.aws.amazon.com/iot/), and your device is prepared to integrate data with SiteWise Edge. You can connect your industrial equipment or other devices to the AWS IoT platform and start ingesting data into SiteWise Edge. 

## Step 3: Configure your SiteWise Edge MQTT-enabled, V3 gateway
<a name="gateway-tutorial-configure-your-edge-gateway"></a>

In this step, create your AWS IoT SiteWise Edge MQTT-enabled, V3 gateway and configure it to receive data from the EMQX broker. The gateway acts as a bridge between your devices and AWS IoT. This allows you to process data locally at the edge before sending it to the AWS Cloud. This configuration reduces bandwidth and decreases cloud processing delays.

------
#### [ Console ]

**To create your AWS IoT SiteWise MQTT-enabled, V3 gateway**

1. Sign in to the [AWS Management Console](https://console.aws.amazon.com/) and open the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/). 

1. In the left navigation pane, choose **Edge gateways**, then choose **Create gateway**.

1. Under **Deployment target**, choose **Self-hosted gateway**.

1. Under Self-hosted gateway options, choose **MQTT-enabled, V3 gateway - *recommended***.

1. Under **Gateway configuration**:

   1. In **Gateway name**, enter a name for your gateway. For example, **SiteWise Tutorial Device Gateway**.

   1. In **Greengrass device OS**, select the appropriate option for your device.

1. Under **Advanced configuration**:

   1. Choose **Default setup**.

   1. Enter a name for the Greengrass core device or use the name generated by AWS IoT SiteWise. 

1. Choose **Create gateway**.

1. In the confirmation dialog, choose **Generate and download** to generate an installer for your SiteWise Edge gateway. For more information, see [Create a self-hosted SiteWise Edge gateway](create-gateway-ggv2.md#configure-gateway-console).

**Warning**  
Store the installer file in a secure location. This file can't be regenerated, and is needed to complete the gateway setup in later steps.

------
#### [ AWS CLI ]

Use AWS CLI to create a self-hosted gateway. You need to provide a name for the gateway, specify the platform and gateway version. For more information, see [CreateGateway](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_CreateGateway.html) in the *AWS IoT SiteWise API Reference*.

To use this example, replace the user input placeholders with your own information.

```
aws iotsitewise create-gateway \
    --gateway-name SiteWise Tutorial Device Gateway \
    --gateway-platform greengrassV2={coreDeviceThingName=your-core-device-thing-name, coreDeviceOperatingSystem=LINUX_AMD64} \                        
    --gateway-version 3 \
    [--cli-input-json your-configuration]
```
+ `gateway-name` – A unique name for the gateway, for example, `SiteWise Tutorial Device Gateway`.
+ `gateway-platform` – Enter `greengrassV2`. For more information, see [CreateGateway](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_CreateGateway.html) in the *AWS IoT SiteWise API Reference*.
  + `coreDeviceThingName` – The name of the AWS IoT thing for your AWS IoT Greengrass V2 core device. For example, `SiteWiseTutorialDevice1`.
  + `coreDeviceOperatingSystem` – The operating system of the core device in AWS IoT Greengrass V2. Specifying the operating system is required for gateway-version 3. Options include: `LINUX_AARCH64`, `LINUX_AMD64`, and `WINDOWS_AMD64`.
+ `gateway-version` – The version of the gateway.
  + Use `3` for the gateway version to create an MQTT-enabled, V3 gateway.
+ `cli-input-json` – A JSON file containing request parameters.

 Use the following AWS CLI command to verify that your gateway was created successfully:

```
aws iotsitewise describe-gateway --gateway-id your-gateway-id
```

------

## Step 4: Install SiteWise Edge gateway software
<a name="install-gateway-software"></a>

To install the gateway software, use the installer package that you downloaded in the previous step. The installation process configures the necessary components, starts the Greengrass core service, and registers your device with AWS IoT Greengrass. After installation is complete, verify that your gateway appears in the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/) under **Edge gateways** and that the Greengrass service is running properly on your device.

For detailed instructions, see [Install the AWS IoT SiteWise Edge gateway software on your local device](install-gateway-software-on-local-device.md).

## Step 5: Configure the EMQX broker to connect to external applications
<a name="configure-emqx-broker-external-applications"></a>

**Note**  
 You must have deployed your SiteWise Edge MQTT-enabled, V3 gateway before proceeding. The gateway provides the necessary infrastructure and security settings required for configuring the EMQX broker. The broker configuration will fail without an active gateway deployment. 

Configure the EMQX broker to enable secure communication between your IoT devices and external applications. The EMQX broker functions as a central messaging hub that routes data between your IoT devices, gateway, and applications. The EMQX broker ensures reliable message delivery on your gateway and connected applications at the edge. For more information, see [Connect external applications to the EMQX broker](connect-external-applications-emqx.md).

**To configure the EMQX broker**

1. Set up the EMQX broker. For detailed configuration instructions, follow Steps 1-14 in [Update the EMQX deployment configuration for authentication](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/configure-emqx-broker.html#update-emqx-broker-authentication).

1. Set up MQTT topics for wind farm monitoring. For more information on MQTT requirements, see [MQTT topic requirements](connect-broker-payload-format.md#connect-broker-mqtt-requirements).

   1. CPU Usage: `SiteWiseTutorialDevice/cpu`

   1. Memory Usage: `SiteWiseTutorialDevice/memory`

   1. Timestamp: `SiteWiseTutorialDevice/timestamp`

1. Review your configuration and complete the deployment.

   1. Choose **Confirm** to save your settings.

   1. Choose **Next** until you reach the **Review** step.

   1. On the **Review** page, choose **Deploy**.

   1. Wait for the deployment to complete successfully before proceeding.

1. Prepare messages using the payload format to send to the EMQX broker. For more information about structuring payloads, see [Update the EMQX deployment configuration for authentication](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/configure-emqx-broker.html#update-emqx-broker-authentication).

1. Implement the following security measures:

   1. Use Transport Layer Security (TLS) encryption (port 8833) to protect data in transit. For more information, see [Configure TLS for secure connections to the EMQX broker on AWS IoT SiteWise Edge](connect-app-to-broker.md#configure-tls-emqx-broker).

   1. Set up username and password authentication to verify device identities. This security measure helps protect your data, and ensures only authorized devices can connect to your system. For more information, see [Enable username and password authentication](configure-emqx-broker.md#emqx-broker-username-password-auth).

EMQX allows you to create authorization rules based on identifiers such as username, IP address, or client ID. This is useful for controlling access to your data. For more information, see [Set up authorization rules for AWS IoT SiteWise Edge in EMQX](authorization-rules-emqx-broker.md).

After successful deployment, your EMQX broker is configured and ready to securely connect with external applications.

**Note**  
The payload format must follow a specific structure for AWS IoT SiteWise Edge to properly process and ingest your data. For more information about the required structure, see [JSON payload structure](connect-broker-payload-format.md#connect-broker-json-payload).

**Example: Add CPU, memory, and timestamp JSON payloads**

**CPU JSON payload**

```
{
  "propertyAlias": "SiteWiseTutorialDevice/cpu",
  "propertyValues": [
    {
      "quality": "GOOD",
      "timestamp": {
        "offsetInNanos": 0,
        "timeInSeconds": 1753206441
      },
      "value": {
        "integerValue": 45.2
      }
    }
  ]
}
```

**Memory JSON payload**

```
{
  "propertyAlias": "SiteWiseTutorialDevice/memory",
  "propertyValues": [
    {
      "quality": "GOOD",
      "timestamp": {
        "offsetInNanos": 0,
        "timeInSeconds": 1753206441
      },
      "value": {
        "integerValue": 67.8
      }
    }
  ]
}
```

**Timestamp JSON payload**

```
{
  "propertyAlias": "SiteWiseTutorialDevice/timestamp",
  "propertyValues": [
    {
      "quality": "GOOD",
      "timestamp": {
        "offsetInNanos": 0,
        "timeInSeconds": 1753206441
      },
      "value": {
        "integerValue": 23.5
      }
    }
  ]
}
```

**Note**  
Each JSON payload must be published separately as an individual message. Don't combine multiple property values into a single message. Send each CPU, memory, and timestamp payload as its own distinct MQTT publication.

The payload defines the required JSON structure that your IoT devices must use to send device data through the EMQX broker to SiteWise Edge. This format ensures that AWS IoT SiteWise can identify your devices and process the sensor readings. After you implement these configurations and payload structures, your wind farm monitoring system is ready to collect and process data. 

## Step 6: Publish data with Mosquitto
<a name="add-mqtt-data-source"></a>

After creating your MQTT-enabled, V3 gateway, configure Eclipse Mosquitto to send test data to SiteWise Edge. Mosquitto is an open-source MQTT message broker that uses the MQTT protocol for lightweight messaging between devices. The Mosquitto client allows you to publish messages to MQTT topics, simulating data from wind farm sensors. Using Mosquitto, simulate device data without requiring any third-party services or additional equipment. For more information, see [documentation](https://mosquitto.org) on the official Eclipse Mosquitto website. In this tutorial, local data from the [Ingest data](ingest-data-from-iot-things.md) tutorial and fictitious data are being used for demonstration purposes. 

**Use Mosquitto CLI client to test the SiteWise Edge EMQX broker **

1. Install Mosquitto on your local device. For detailed instructions, see [Download Mosquitto](https://mosquitto.org/download/) on the official Eclipse Mosquitto website.

1. For more information about connecting external applications to transfer industrial data, see [Connect external applications to the EMQX broker](connect-external-applications-emqx.md).

**Important**  
Ensure that the MQTT connection settings you configure here match the settings used in Mosquitto publish command. The host must be the IP address or hostname of your SiteWise Edge gateway. The port is typically 1883 (or 8883 if using SSL/TLS).

Use Mosquitto to publish test data. Open a command line and run the following commands:

**Example: CPU property **

```
mosquitto_pub -h localhost -p 1883 -t "SiteWiseTutorialDevice/cpu" -m '{
  "propertyAlias": "SiteWiseTutorialDevice/cpu",
  "propertyValues": [
    {
      "quality": "GOOD",
      "timestamp": {
        "timeInSeconds": 1753206441,
        "offsetInNanos": 0
      },
      "value": {
        "integerValue": 45.2
      }
    }
  ]
}'
```

**Example: Memory property**

```
mosquitto_pub -h localhost -p 1883 -t "SiteWiseTutorialDevice/memory" -m '{
  "propertyAlias": "SiteWiseTutorialDevice/memory",
  "propertyValues": [
    {
      "quality": "GOOD",
      "timestamp": {
        "timeInSeconds": 1753206441,
        "offsetInNanos": 0
      },
      "value": {
        "integerValue": 72.1
      }
    }
  ]
}'
```

**Example: Timestamp property**

```
mosquitto_pub -h localhost -p 1883 -t "SiteWiseTutorialDevice/timestamp" -m '{
  "propertyAlias": "SiteWiseTutorialDevice/timestamp",
  "propertyValues": [
    {
      "quality": "GOOD",
      "timestamp": {
        "timeInSeconds": 1753206441,
        "offsetInNanos": 0
      },
      "value": {
        "integerValue": 1683000000
      }
    }
  ]
}'
```

**Note**  
The use of `localhost` as the EMQX broker address is for demonstration purposes only. In production environments or when connecting from external devices, you must use the appropriate EMQX broker address for your specific deployment configuration. For detailed connection instructions, see [Connect an application to the EMQX broker on AWS IoT SiteWise Edge](connect-app-to-broker.md).

## Step 7: Specify destinations
<a name="specify-destinations"></a>

In this step, specify destinations to determine where to direct your source data. Use AWS IoT SiteWise with Amazon S3 buffering as your destination. This option provides a scalable way to store and process your IoT data. 

------
#### [ Console ]

**To add destinations**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/) and select **Edge gateways**.

1. Under **SiteWise Tutorial Device Gateway**, choose **Add destinations**.

1. Under **Destination details**, choose **AWS IoT SiteWise buffered using Amazon S3**. To learn more about destination types, see [AWS IoT SiteWise gateway destinations](gw-destinations.md#source-destination).

1. Under **Destination name**, enter a name for your destination, for example, `SiteWise Tutorial S3 Destination`.

1. Under **S3 upload settings**, enter your S3 bucket location. For example, `s3://sitewise-tutorial-mqtt-data-[your-account-id]`. To learn more about Amazon S3, see [Creating, configuring, and working with Amazon S3 buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-buckets-s3.html) in the *Amazon Simple Storage Service User Guide*.

1. Under **Data upload frequency**, enter a value between 1 minute and 30 days. For example, `1 minute`.

1. Under **Data storage settings**:

   1. Deselect **Copy data to storage**. While this setting is recommended for production environments, you don't need it for this tutorial. When you deselect this option, the **Delete data from S3** option is automatically deselected.

1. Choose **Add destination**.

**Note**  
This tutorial uses a 1-minute interval for testing. After you complete the tutorial, you can adjust this interval to match your production needs or delete it to avoid additional charges.

------
#### [ AWS CLI ]

**Example: Create a new AWS IoT SiteWise destination buffered using Amazon S3 **

Use the [update-gateway-capability-configuration](https://docs.aws.amazon.com/cli/latest/reference/iotsitewise/update-gateway-capability-configuration.html) in the *AWS CLI Command Reference* to configure the publisher. Set the `capabilityNamespace` parameter to `iotsitewise:publisher:3`.

```
{
    "sources": [
      {
        "type": "MQTT"
      }
    ],
    "destinations": [
      {
        "type": "SITEWISE_BUFFERED",
        "name": "your-s3-destination-name",
        "config": {
          "targetBucketArn": "arn:aws:s3:::amzn-s3-demo-bucket/Optional/SomeFolder",
          "publishPolicy": {
            "publishFrequency": "1m",
            "localSizeLimitGB": 10
          },
          "siteWiseImportPolicy": {
            "enableSiteWiseStorageImport": true,
            "enableDeleteAfterImport": true,
            "bulkImportJobRoleArn": "arn:aws:iam::123456789012:role/your-role-name"
          }
        },
        "filters": [
          {
            "type": "PATH",
            "config": {
              "paths": [
                "#"
              ]
            }
          }
        ]
      }
    ]
  }
```

For more information about destinations, see [Add an AWS IoT SiteWise buffered destination using Amazon S3](destinations-buffered.md).

------

## Step 8: Specify path filters
<a name="specify-path-filters"></a>

In this step, configure path filters to specify which MQTT topics to monitor for your wind farm device data.

Path filters follow the MQTT topic wildcard specification, which supports two special characters:
+ `+` – This symbol represents a single-level wildcard, which matches any string at a single level.
+ `#` – This symbol represents a multi-level wildcard, which matches any number of levels in the topic hierarchy.

**Note**  
For more information about other path filters, see [Special characters in path filter names](gw-destinations.md#path-filters-special-characters).

------
#### [ Console ]

**To configure your path filters**

Under **Path filters**:

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/) and select **Edge gateways**.

1. Under **SiteWise Tutorial Device Gateway**, choose **Add destinations**.

1. Choose **Add path filters** to enter the following path filters manually:
   + `SiteWiseTutorialDevice/#`
   + `windfarm/+/turbine/+/performance/#`
   + `cpu/+/idle-time`
   + `cpu/+/interruption-count/+`
   + `+/memory/consumption`
   + `timestamp/+/measurement`
   + `device/+/status/+`
   + `system/+/performance-log`

1. Choose **Add destination**.

For more information about best practices for path filters, see [Best practices for path filters](gw-destinations.md#create-effective-path-filters).

------
#### [ AWS CLI ]

Use the following AWS CLI commands to configure your path filters:

**Example 1: Device data using wildcard**

```
{
 "destinations": [
   {
     "name": "All Device Data Destination"
   }
 ],
 "filters": [
   {
     "type": "PATH",
     "config": {
       "paths": [
         "SiteWiseTutorialDevice/#",
         "windfarm/+/turbine/+/performance/#"
       ]
     }
   }
 ]
}
```

This path filter configuration uses multi-level wildcards (\$1) to capture all data from the SiteWiseTutorialDevice and all performance data from any turbine in the wind farm.

**Example 2: CPU and memory performance**

```
{
 "destinations": [
   {
     "name": "Performance Metrics Destination"
   }
 ],
 "filters": [
   {
     "type": "PATH",
     "config": {
       "paths": [
         "cpu/+/idle-time",
         "+/memory/consumption",
         "cpu/+/interruption-count/+"
       ]
     }
   }
 ]
}
```

This example captures various CPU metrics (idle time and interruption count) and memory consumption data across devices.

**Example 3: Device diagnostics**

```
{
 "destinations": [
   {
     "name": "Device Diagnostics Destination"
   }
 ],
 "filters": [
   {
     "type": "PATH",
     "config": {
       "paths": [
        "device/+/status/+",
        "system/+/performance-log"
       ]
     }
   }
 ]
}
```

This configuration uses the `+` wildcard to capture diagnostic data from multiple devices, specifically system performance logs and device status updates.

These three path filters match the MQTT topics that you use to publish test data with Mosquitto. The filters ensure your SiteWise Edge gateway captures and processes the relevant MQTT messages. For more information on how to add path filters, see [Add path filters to AWS IoT SiteWise Edge destinations](destinations-add-path-filters.md).

------

## Step 9: Configure your AWS IoT resources
<a name="configure-iot-resources"></a>

In this step, create the necessary AWS IoT SiteWise asset models and assets to represent your simulated third-party devices and enable data ingestion through your edge gateway.

Before starting this step, you should have completed steps 3 to 8 in the [Ingest data](ingest-data-from-iot-things.md) tutorial. These steps establish the foundational components to integrate your third-party data through the MQTT-enabled V3 gateway. You also set up rules that define how your sensor data flows into AWS IoT SiteWise, and run a device client script that simulates industrial wind farm data.

**To validate your AWS IoT resource configuration**

1. Use the following AWS CLI command to verify you created and properly configured your SiteWise Tutorial Device Model and SiteWise Tutorial Device Fleet Model:

   ```
   aws iotsitewise describe-asset-model --asset-model-id your-device-model-id
   ```

   Use the following AWS CLI command to retrieve your asset models' ID:

   ```
   aws iotsitewise list-asset-models
   ```

1. Use the following AWS CLI command to verify you created and properly configured your SiteWise Tutorial Device 1 asset and SiteWise Tutorial Device Fleet 1 asset:

   ```
   aws iotsitewise describe-asset --asset-id your-asset-id
   ```

   Use the following AWS CLI command to retrieve your assets' ID:

   ```
   aws iotsitewise list-assets
   ```

## Step 10: Visualize your data
<a name="visualize-your-data"></a>

Set up the open-source version of Grafana to visualize your wind farm device data. Grafana is a visualization platform that displays your real-time operational data. These dashboards help you track operational efficiency and identify maintenance needs across your infrastructure. For more information about integration, see [Integrate AWS IoT SiteWise with Grafana](grafana-integration.md).

**To setup Grafana**

1. For instructions to download and install the latest version of Grafana, see [Install Grafana](https://grafana.com/docs/grafana/latest/setup-grafana/installation/#install-grafana) on the official Grafana website.

1. For detailed configuration instructions specific to your operating system, see [Configure Grafana](https://grafana.com/docs/grafana/latest/setup-grafana/configure-grafana/#configure-grafana) on the official Grafana website.

1. Configure the AWS IoT SiteWise data source. This allows you to set up the AWS IoT SiteWise plugin on your Grafana server. For detailed instructions about how to use the plugin, see [Connect to an AWS IoT SiteWise data source](https://docs.aws.amazon.com/grafana/latest/userguide/using-iotsitewise-in-AMG.html) in the *Amazon Managed Grafana User Guide*.

**Important**  
Ensure you have the latest version of Grafana for compatibility with the AWS IoT SiteWise data source.

After completing these steps, you can build and customize Grafana dashboards to display your wind farm's operational metrics. This enables you to track and analyze your wind farm performance at the edge in real time.

**Note**  
While this tutorial uses the open-source version of Grafana, AWS also offers Amazon Managed Grafana for production environments. Amazon Managed Grafana is a fully managed service that eliminates the need to set up, configure, and maintain your own Grafana servers.  
Consider upgrading to Amazon Managed Grafana when you're ready to scale your solution. For detailed instructions on how to connect your SiteWise data to Grafana, see the [Visualize and share data in Grafana](visualize-with-grafana.md) tutorial.

You have completed the tutorial. In this procedure, you configured AWS IoT SiteWise Edge to integrate third-party device data using an MQTT-enabled, V3 gateway. This setup allows you to collect, process, and visualize industrial equipment data at the edge, reducing latency and operational costs. By using the wind farm demo, you collected and processed operational metrics like CPU and memory usage data through your MQTT-enabled, V3 gateway.

To enhance your IoT solution, consider exploring advanced features like anomaly detection by leveraging [Detect anomalies with Lookout for Equipment](anomaly-detection.md), or integrating with other AWS services like [Amazon Quick](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) in the *Amazon Quick User Guide* for advanced analytics.

## Step 11: Clean up resources after the tutorial
<a name="tutorial-clean-up-resources"></a>

After you complete this tutorial about integrating data into AWS IoT SiteWise Edge, clean up your resources to avoid incurring additional charges.

**To delete hierarchical assets in AWS IoT SiteWise**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Assets**.

1. When you delete assets in AWS IoT SiteWise, you must first disassociate them.

   Complete the following steps to disassociate your device assets from your device fleet asset:

   1. Choose your device fleet asset (**SiteWise Tutorial Device Fleet 1**).

   1. Choose **Edit**.

   1. Under **Assets associated to this asset**, choose **Disassociate** for each device asset associated to this device fleet asset.

   1. Choose **Save**.
**Note**  
 The device assets are no longer organized as a hierarchy now.

1. Choose your device asset (**SiteWise Tutorial Device 1**).

1. Choose **Delete**.

1. In the confirmation dialog, enter **Delete**, and then choose **Delete**.

1. Repeat steps 4 through 6 for each device asset and the device fleet asset (**SiteWise Tutorial Device Fleet 1**).

**To delete hierarchical asset models in AWS IoT SiteWise**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. Delete your device and device fleet assets.

1. In the left navigation pane, choose **Models**.

1. Choose your device fleet asset model (**SiteWise Tutorial Device Fleet Model**). You can't delete a model if you have assets that were created from that model.

   When deleting hierarchical asset models, start by deleting the parent asset model first.

1. Choose **Delete**.

1. In the confirmation dialog, enter **Delete**, and then choose **Delete**.

1. Repeat steps 4 through 6 for your device asset model (**SiteWise Tutorial Device Model**).

**To disable or delete a rule in AWS IoT Core**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Message routing**, and then choose **Rules**.

1. Select your rule and choose **Delete**.

1. In the confirmation dialog, enter the name of the rule and then choose **Delete**.

**To delete an Amazon S3 bucket**

1. Navigate to the [Amazon S3 console](https://console.aws.amazon.com/s3/).

1. In the left navigation pane, choose **General purpose bucket**.

1. In the buckets list, select the option button next to the bucket you created, and then choose **Empty** at the top of the page.

1. In the confirmation dialog, confirm the deletion, and then choose **Empty**.

1. After the bucket is empty, choose **Delete** to delete the bucket.

1. In the confirmation dialog, enter the name of your bucket to confirm deletion.

1. Choose **Delete bucket**.

**To delete a SiteWise Edge gateway**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Edge gateways**.

1. Under Gateways, choose the gateway you created for this tutorial. For example, `SiteWise Tutorial Device Gateway`.

1. Choose **Delete**.

1. To confirm you want to delete the gateway, type **Delete** in the confirmation dialog, and then choose **Delete** in the window that appears.

**To delete your IoT thing**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Manage**, then choose **Things**.

1. Select the IoT thing you created for this tutorial. For example, `SiteWiseTutorialDevice1`.

1. Choose **Delete**.

1. In the confirmation dialog, enter the name of the thing, and then choose **Delete**.

**To uninstall AWS IoT Greengrass Core**

Uninstall the AWS IoT Greengrass Core software from your local device. For detailed instructions, see [Uninstall the AWS IoT Greengrass Core software](https://docs.aws.amazon.com/greengrass/v2/developerguide/uninstall-greengrass-core-v2.html) in the *AWS IoT Greengrass Developer Guide, Version 2*.

**Important**  
Uninstalling Greengrass removes all local configurations and data. Ensure you've backed up any important information before proceeding.

**(Optional) To delete third-party resources**

After completing this tutorial, consider shutting down any external resources you created. This helps to prevent incurring charges from third-party providers.

## Additional resources
<a name="additional-resources"></a>

Refer to the following resources for more information:
+ [Interact with other AWS services](interact-with-other-services.md)
+ [Use AWS IoT SiteWise Edge gateways](gateways.md)
+ [Troubleshooting a SiteWise Edge gateway](troubleshooting-gateway.md)
+ [Security best practices for AWS IoT SiteWise](security-best-practices.md)
+ [AWS IoT pricing](https://aws.amazon.com/iot-sitewise/pricing/)
+ [Ingest data to AWS IoT SiteWise](industrial-data-ingestion.md)
+ [Use tags in AWS IoT SiteWise](tag-basics.md)

# Visualize and share data in Grafana
<a name="visualize-with-grafana"></a>

This tutorial guides you through configuring the AWS IoT SiteWise data source plugin with Grafana, a data visualization platform. With Grafana, you can create dashboards that visualize and monitor your industrial data. In this tutorial, a sample dataset from a wind farm demonstration is used to illustrate key concepts. After you become familiar with the process, you can repeat the tutorial with your own data.

 After you complete this tutorial, you can do the following:
+ Collect, query, and analyze data from industrial equipment
+ Create interactive Grafana dashboards to visualize asset performance metrics
+ Monitor operational data through a unified interface
+ Share insights with your team using Grafana's collaboration features
+ Combine AWS IoT SiteWise data with other AWS data sources such as [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/) or [Amazon Timestream](https://aws.amazon.com/timestream/)

**Topics**
+ [Prerequisites](#grafana-tutorial-prerequisites)
+ [Step 1: Configure your Amazon Managed Grafana workspace](#configure-workspace)
+ [Step 2: Add AWS IoT SiteWise as a data source](#add-iot-data-source)
+ [Step 3: Create a dashboard to explore and visualize your data](#explore-your-data)
+ [(optional) Step 4: Set up alerts to monitor performance](#set-up-alerts)
+ [Step 5: Clean up resources after the tutorial](#clean_up_resources)
+ [Additional resources](#additional-resources)

## Prerequisites
<a name="grafana-tutorial-prerequisites"></a>

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, see [Set up an AWS account](getting-started.md#set-up-aws-account).
+ An AWS Identity and Access Management (IAM) user with administrator permissions. For detailed instructions, see [How AWS IoT SiteWise works with IAM](security_iam_service-with-iam.md).
+ A running AWS IoT SiteWise demo.
**Note**  
This tutorial requires the use of resources created in the [Use the AWS IoT SiteWise demo](getting-started-demo.md). You must complete it before proceeding with this tutorial. 

  The demo typically takes around 3 minutes to create. If the demo fails to create, it might indicate insufficient permissions in your AWS account. In this case, switch to an account with administrative access. For more information about required permissions, see [How AWS IoT SiteWise works with IAM](security_iam_service-with-iam.md).
**Important**  
Keep all demo resources until you complete this tutorial. Deleting any components might disrupt the demo's functionality and affect your ability to display data in Grafana.

## Step 1: Configure your Amazon Managed Grafana workspace
<a name="configure-workspace"></a>

In this procedure, create and configure an Amazon Managed Grafana workspace to visualize your wind farm data.

1. Sign in to the [Amazon Managed Grafana console](https://console.aws.amazon.com/grafana/).

1. Choose **Create workspace**.

1. Under **Workspace details**, enter a name for your workspace, such as **SiteWiseTutorialDemo**.

1. Under **Grafana version**, choose the latest version. Choose this version for the most up-to-date features and capabilities. For more information about different version sets, see [Differences between Grafana versions](https://docs.aws.amazon.com/grafana/latest/userguide/version-differences.html) in the *Amazon Managed Grafana User Guide*.

1. Choose **Next**.

1. Under **Authentication access**, choose **AWS IAM Identity Center**.
   + If AWS IAM Identity Center in your account isn't enabled, you will be prompted to set it up first. For detailed instruction about how to set up user access, see [Identity-based policy examples for Amazon Managed Grafana](https://docs.aws.amazon.com/grafana/latest/userguide/security_iam_id-based-policy-examples.html#security_iam_id-based-policy-examples-create-workspace-standalone) in the *Amazon Managed Grafana User Guide*.

1. Under **Permission type**, choose **Service managed**. Amazon Managed Grafana automatically creates and configures the necessary IAM roles and permissions for any AWS data sources you choose to use in this workspace. For organizational member accounts, the Service managed option is only available if the account is designated as a delegated administrator. For information about setting up delegated administrator accounts, see [Register a delegated administrator member account](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html) in the *CloudFormation User Guide*.

1. Under **Workspace configuration options**, take the following actions:

   1. Select **Turn Grafana alerting on**. With this setting, you can create and manage alerts through a centralized interface in your workspace. For more information, see [Working with Grafana alerting](https://docs.aws.amazon.com/grafana/latest/userguide/alerts-overview.html) in the *Amazon Managed Grafana User Guide*.

   1. Select **Turn plugin management on**. This allows you to install, update, and uninstall plugins in your workspace. For more information, see [Extend your workspace with plugins](https://docs.aws.amazon.com/grafana/latest/userguide/grafana-plugins.html) in the *Amazon Managed Grafana User Guide*.
**Important**  
Be sure to enable plugin management. If you don't select this option, you cannot add AWS IoT SiteWise as a data source in the following step.

1. Under **Network access control**, choose **Open access**. You use demo data in this tutorial, so you can make the workspace publically available.
   + **Open access** – Allows your workspace to be publicly accessible.
   + **Restricted access** – Limits access to specific IP ranges or VPC endpoints. For more information, see [How VPC connectivity works](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-configure-vpc.html#AMG-VPC-how-it-works) in the *Amazon Managed Grafana User Guide*.

1. Choose **Next**.

1. Under the **Service managed permission settings** page, choose **Current account** to have Amazon Managed Grafana automatically create policies and permissions for accessing AWS data within your account.

1. Under **Data sources**, select **AWS IoT SiteWise**. For more information, see [Connect to an AWS IoT SiteWise data source](https://docs.aws.amazon.com/grafana/latest/userguide/using-iotsitewise-in-AMG.html) in the *Amazon Managed Grafana User Guide*.

1. (Optional) Under **Notification channels**, select **Amazon SNS** to enable Grafana alerts to be sent through Amazon SNS, This creates an IAM policy that allows publishing to Amazon SNS topics with names starting with Grafana. You need to complete the notification channel setup later in your Grafana console within the workspace.

1. Confirm the workspace details, and choose **Create workspace**. This process takes a couple of minutes.

1. On the **Authentication** tab, under **AWS IAM Identity Center**. assign users or groups to your workspace by doing the following:

   1. To assign the user who will manage AWS IoT SiteWise data, choose **Assign new user or group**. Then choose **Make admin** from the **Actions** dropdown list to grant them administrative privileges.
**Important**  
To manage the Grafana workspace, you must assign the `Admin` role to at least one user. This user will have full access to the Grafana workspace console.

You have now set up and configured your Grafana workspace. In the next step, you can add AWS IoT SiteWise as a data source and begin creating visualizations for your wind farm data. From your workspace, you can query, visualize, and analyze your industrial data in real time. For more information about Amazon Managed Grafana workspaces, see [Use your Grafana workspace](https://docs.aws.amazon.com/grafana/latest/userguide/using-grafana-workspace.html) in the *Amazon Managed Grafana User Guide*.

## Step 2: Add AWS IoT SiteWise as a data source
<a name="add-iot-data-source"></a>

To help you visualize your data, Amazon Managed Grafana includes the AWS Data Sources plugin, which simplifies the process of connecting to AWS services. This plugin comes pre-installed in your workspace and provides a unified interface for discovering and configuring AWS resources as data sources. For your wind farm visualization, you'll use this plugin to connect to AWS IoT SiteWise. For more information, see [Connect to an AWS IoT SiteWise data source](https://docs.aws.amazon.com/grafana/latest/userguide/using-iotsitewise-in-AMG.html) in the *Amazon Managed Grafana User Guide*.

Before you can start querying your wind farm data, the AWS Data Sources plugin needs the appropriate permissions to access your AWS IoT SiteWise resources. These permissions were automatically configured when you selected AWS IoT SiteWise as a data source in the previous step. For more information about plugin permissions, see [Required permissions](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-configure-permissions.html) in the *Amazon Managed Grafana User Guide*.

**To connect AWS IoT SiteWise to your Grafana workspace**

1. Open the [Amazon Managed Grafana console](https://console.aws.amazon.com/grafana/). In your workspace details page, choose the URL displayed under **Grafana workspace URL**. The workspace URL opens the Grafana workspace console login page.

1. Choose **Sign in with AWS IAM Identity Center** and enter your credentials. These credentials only work if you responded to the email from Amazon Managed Grafana that prompted you to create a password for IAM Identity Center.

1. In the left navigation pane, choose **Apps**, then **AWS Data Sources**, and then select the **AWS services** tab.

1. Under **AWS IoT SiteWise**, choose **Install now** to install the latest version of the AWS IoT SiteWise plugin.

1. Navigate to the **Data sources** tab, and select **IoT SiteWise** as the service.

1. Under **Default region**, select the Region where you want to retrieve data from, for example, **US East (N. Virginia)**.

1. After specifying the parameters for the plugin, select **Add data source**.

1. Select **Go to settings**.

1. Under **Connection details**, select **Save and test** to verify that the service is working.

## Step 3: Create a dashboard to explore and visualize your data
<a name="explore-your-data"></a>

In this step, create a Grafana dashboard to visualize the demo wind farm data that you created earlier. Dashboards help you monitor your data by displaying multiple visualizations in a single view. You can use dashboards to track metrics, analyze patterns, and gain insights from your industrial data. For more information, see [Create your first dashboard](https://docs.aws.amazon.com/grafana/latest/userguide/getting-started-grafanaui.html) in the *Amazon Managed Grafana User Guide*.

**To create your first dashboard in Grafana**

1. In the left navigation pane, select **Dashboards** and then choose **Create Dashboard** to start building your first dashboard.

1. Select **Add visualization**. This opens the panel editor where you can configure data sources, queries, and visualization settings.

1. Under the **Query** tab, select the AWS IoT SiteWise data source from the dropdown menu.

1. Under **Query type**, select **Get property value aggregates** from the dropdown menu to retrieve aggregated values for asset properties over time.

1. Select **Explore** to view available assets in your hierarchy. From the **Hierarchy** tab, select **Demo Wind Farm Asset**, and then select **Demo Turbine Asset 1**.

1. Under **Property**, select **Average Power** from the available properties. Select **Run queries** to run the query so you can preview the output. The visualization will update to show the average power data for `Demo Turbine Asset 1`.

1. In the right navigation pane, give the new panel a title, such as **Turbine Demo 1 (Average Power)**. Choose **Apply** to save your changes.
**Warning**  
Whenever you make any changes to the dashboard, save the dashboard before refreshing the page or navigating away. Otherwise, you will lose your progress.

1. In the top-right corner, select **Save dashboard**. You will be prompted to enter a name for your dashboard, for example, **SiteWise Wind Farm Demo Dashboard**.

1. Choose **Save**.

For information about sharing dashboards, see [Sharing dashboards and panels](https://docs.aws.amazon.com/grafana/latest/userguide/v10-dash-sharing.html) in the *Amazon Managed Grafana User Guide*.

**To add another panel to visualize the wind speed**

1. Select **Add visualization** to open a blank panel.

1. Under the **Query** tab, select the AWS IoT SiteWise data source from the dropdown menu.

1. Under **Query type**, select **Get property value** from the dropdown menu and under **Asset**, select `Demo Wind Farm Asset`, then `Demo Turbine Asset 1`.

1. Under **Property**, select **Wind Speed ** from the available properties. Select **Run queries** to update the changes.

1. Under **Visualization**, select **Gauge**. Gauges work best for displaying single, real-time metrics like wind speed.

1. In the right navigation pane, give the new panel a title, such as **Turbine Demo 1 (Wind Speed)**.

1. Under **Standard options** from the Panel options, select **Unit**. Choose **Velocity**, and then choose **meters/second (m/s)**.

1. Choose **Apply** to save your changes.

   The following image displays what your Grafana dashboards might look like when you complete this step.  
![\[Sample dashboards created with the wind farm demo data.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/updated-grafana.png)

## (optional) Step 4: Set up alerts to monitor performance
<a name="set-up-alerts"></a>

Alerts indicate state changes after they occur to identify performance issues with your industrial equipment. For more information, see [Amazon Managed Grafana alerting](https://docs.aws.amazon.com/grafana/latest/userguide/alerts-overview.html) in the *Amazon Managed Grafana User Guide*.

**To set up alerts in Grafana**

1. Under the **Rule** tab in the `Turbine Demo 1 (Average Power)`, set **Evaluate every **to `5m` and **For** to `15m`. This configuration evaluates the average power every 5 minutes and triggers an alert if the condition persists for longer than 15 minutes.

1. Under **Conditions**, select **IS BELOW** and enter **7,020** watts. This setting will notify you if average turbine conditions fall below 7,020 watts for longer than 5 minutes. For more information about creating alerts, see [Alert rule fields](https://docs.aws.amazon.com/grafana/latest/userguide/old-create-alerts.html#old-alert-rule-fields) in the *Amazon Managed Grafana User Guide*.

You have completed the tutorial. In this procedure, you created a Grafana workspace and configured it to visualize wind farm data from AWS IoT SiteWise. You built an interactive dashboard with multiple widget types, including a time-series graph for average power and a gauge for wind speed. You also set up alerts to monitor turbine performance, enabling you to identify potential issues before they disrupt production. You can continue to enhance your dashboard by adding more visualizations, creating additional alerts, or connecting other AWS data sources to gain deeper insights into your industrial operations.

## Step 5: Clean up resources after the tutorial
<a name="clean_up_resources"></a>

After you complete this tutorial about visualizing data with Grafana, clean up your resources to avoid incurring additional charges.

**To delete the AWS IoT SiteWise demo**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the upper-right corner of the page, choose **Delete demo**.

1. In the confirmation dialog, enter **DELETE** and then choose **Delete**.

For more information, see [Delete the AWS IoT SiteWise demo](getting-started-demo.md#delete-getting-started-demo).

If you delete an Amazon Managed Grafana, all the configuration data for that workspace is also deleted. This includes dashboards, data source configuration, alerts, and snapshots.

**To delete an Amazon Managed Grafana workspace**

1.  Open the [Amazon Managed Grafana console](https://console.aws.amazon.com/grafana/).

1. In the left navigation pane, choose the menu icon.

1. Choose **All workspaces**.

1. Choose the name of the workspace that you want to delete.

1. Choose **Delete**.

1. To confirm the deletion, enter the name of the workspace and choose **Delete**.
**Note**  
This procedure deletes a workspace. Other resources may not be deleted. For example, IAM roles that were in use by the workspace are not deleted (but may be unlocked if they are no longer in use).

For more information, see [Delete an Amazon Managed Grafana workspace](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-edit-delete-workspace.html) in the *Amazon Managed Grafana User Guide*.

## Additional resources
<a name="additional-resources"></a>

For more information about visualizing data, see the following resources:
+ [Troubleshooting Amazon Managed Grafana identity and access](https://docs.aws.amazon.com/grafana/latest/userguide/security_iam_troubleshoot.html) in the *Amazon Managed Grafana User Guide*
+ [Security best practices](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-Security-Best-Practices.html) in the *Amazon Managed Grafana User Guide*
+ [Integrate AWS IoT SiteWise with Grafana](grafana-integration.md)
+ [Process and visualize data with SiteWise Edge and open-source toolsProcess and visualize data at the Edge](open-source-edge-integrations.md)
+ [Users, teams, and permissions](https://docs.aws.amazon.com/grafana/latest/userguide/Grafana-administration-authorization.html) in the *Amazon Managed Grafana User Guide*
+ [Amazon Managed Grafana permissions and policies for AWS data sources](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html) in the *Amazon Managed Grafana User Guide*

# Visualize and share wind farm data in SiteWise Monitor
<a name="monitor-wind-farm"></a>

This tutorial explains how to use AWS IoT SiteWise Monitor to visualize and share industrial data through managed web applications, known as portals. Each *portal* encompasses projects, providing you with the flexibility to choose which data is accessible within each project. Then, specify people in your organization that can access each portal. Your users sign in to portals using AWS IAM Identity Center accounts, so you can use your existing identity store or a store managed by AWS.

You, and your users with sufficient permissions, can create dashboards in each project to visualize your industrial data in meaningful ways. Then, your users can view these dashboards to quickly gain insights into your data and monitor your operation. You can configure administrative or read-only permissions to each project for every user in your company. For more information, see [Monitor data with AWS IoT SiteWise Monitor](monitor-data.md).

Throughout the tutorial, you enhance the AWS IoT SiteWise demo, providing a sample dataset for a wind farm. You configure a portal in SiteWise Monitor, create a project, and dashboards to visualize the wind farm data. The tutorial also covers the creation of additional users, along with the assignment of permissions to own or view the project and its associated dashboards.

**Note**  
When you use SiteWise Monitor, you're charged per user that signs in to a portal (per month). In this tutorial, you create three users, but you only need to sign in with one user. After you complete this tutorial, you incur charges for one user. For more information, see [AWS IoT SiteWise Pricing](https://aws.amazon.com/iot-sitewise/pricing/).

**Topics**
+ [Prerequisites](#monitor-tutorial-prerequisites)
+ [Step 1: Create a portal in SiteWise Monitor](#monitor-tutorial-create-portal)
+ [Step 2: Sign in to a portal](#monitor-tutorial-sign-in-portal)
+ [Step 3: Create a wind farm project](#monitor-tutorial-create-project)
+ [Step 4: Create a dashboard to visualize wind farm data](#monitor-tutorial-create-dashboard)
+ [Step 5: Explore the portal](#monitor-tutorial-explore-portal)
+ [Step 6: Clean up resources after the tutorial](#monitor-tutorial-clean-up-resources)

## Prerequisites
<a name="monitor-tutorial-prerequisites"></a>

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, see [Set up an AWS account](getting-started.md#set-up-aws-account).
+ A development computer running Windows, macOS, Linux, or Unix to access the AWS Management Console. For more information, see [What is the AWS Management Console?](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/what-is.html).
+ An AWS Identity and Access Management (IAM) user with administrator permissions.
+ A running AWS IoT SiteWise wind farm demo. When you set up the demo, it defines models and assets in AWS IoT SiteWise and streams data to them to represent a wind farm. For more information, see [Use the AWS IoT SiteWise demo](getting-started-demo.md).
+ If you enabled IAM Identity Center in your account, sign in to your AWS Organizations management account. For more information, see [AWS Organizations terminology and concepts](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html). If you haven't enabled IAM Identity Center, you will enable it in this tutorial and set your account as the management account.

  If you can't sign in to your AWS Organizations management account, you can partially complete the tutorial as long as you have an IAM Identity Center user in your organization. In this case, you can create the portal and dashboards, but you can't create new IAM Identity Center users to assign to projects.

## Step 1: Create a portal in SiteWise Monitor
<a name="monitor-tutorial-create-portal"></a>

In this procedure, you create a portal in AWS IoT SiteWise Monitor. Each *portal* is a managed web application that you and your users can sign in to with AWS IAM Identity Center accounts. With IAM Identity Center, you can use your company's existing identity store or create one managed by AWS. Your company's employees can sign in without creating separate AWS accounts.

**To create a portal**

1. Sign in to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. Review the [AWS IoT SiteWise endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/iot-sitewise.html) where AWS IoT SiteWise is supported and switch Regions, if needed. You must run the AWS IoT SiteWise demo in the same Region.

1. In the left navigation pane, choose **Portals**.

1. Choose **Create portal**.

1. If you already enabled IAM Identity Center, skip to step 6. Otherwise, complete the following steps to enable IAM Identity Center:

   1. On the **Enable AWS IAM Identity Center (SSO)** page, enter your **Email address**, **First name**, and **Last name** to create an IAM Identity Center user for yourself to be the portal administrator. Use an email address you can access so that you can receive an email to set a password for your new IAM Identity Center user.

      In a portal, the portal administrator creates projects and assigns users to projects. You can create more users later.  
![\[The "Enable AWS IAM Identity Center (SSO)" page of the "Create portal" process.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/sitewise-enable-sso-console.png)

   1. Choose **Create user**.

1. On the **Portal configuration** page, complete the following steps:

   1. Enter a name for your portal, such as **WindFarmPortal**.

   1. (Optional) Enter a description for your portal. If you have multiple portals, use meaningful descriptions to keep track of what each portal contains.

   1. (Optional) Upload an image to display in the portal.

   1. Enter an email address that portal users can contact when they have an issue with the portal and need help from your company's AWS administrator to resolve it.

   1. Choose **Create portal**.

1. On the **Invite administrators** page, you can assign IAM Identity Center users to the portal as administrators. Portal administrators manage permissions and projects within a portal. On this page, do the following:

   1. Select a user to be the portal administrator. If you enabled IAM Identity Center earlier in this tutorial, select the user that you created.  
![\[The "Invite administrators" page of the "Create portal" process.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/sitewise-invite-portal-administrators-console.png)

   1. (Optional) Choose **Send invite to selected users**. Your email client opens, and an invitation appears in the message body. You can customize the email before you send it to your portal administrators. You can also send the email to your portal administrators later. If you're trying SiteWise Monitor for the first time and will be the portal administrator, you don't need to email yourself.

   1. Choose **Next**.

1. On the **Assign users** page, you can assign IAM Identity Center users to the portal. Portal administrators can later assign these users as project owners or viewers. Project owners can create dashboards in projects. Project viewers have read-only access to the projects that they're assigned. On this page, you can create IAM Identity Center users to add to the portal.
**Note**  
If you aren't signed in to your AWS Organizations management account, you can't create IAM Identity Center users. Choose **Assign users** to create the portal without portal users, and then skip this step.

   On this page, do the following:

   1. Complete the following steps twice to create two IAM Identity Center users:

      1. Choose **Create user** to open a dialog box where you enter details for the new user.

      1. Enter an **Email address**, **First name**, and **Last name** for the new user. IAM Identity Center sends the user an email for them to set their password. If you want to sign in to the portal as these users, choose an email address that you can access. Each email address must be unique. Your users sign in to the portal using their email address as their usernames.  
![\[The "Portal details" page with "Assign users" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/sso-widget-create-user-console.png)

      1. Choose **Create user**.

   1. Select the two IAM Identity Center users that you created in the previous step.  
![\[The "Assign users" page with the new IAM Identity Center users highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/sitewise-choose-users-to-assign-console.png)

   1. Choose **Assign users** to add these users to the portal.

   The portals page opens with your new portal listed.

## Step 2: Sign in to a portal
<a name="monitor-tutorial-sign-in-portal"></a>

In this procedure, you sign in to your new portal using the AWS IAM Identity Center user that you added to the portal.

**To sign in to a portal**

1. On the **Portals** page, choose your new portal's **Link** to open your portal in a new tab.  
![\[The "Portals" page with the wind farm portal's link highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/sitewise-choose-portal-link-console.png)

1. If you created your first IAM Identity Center user earlier in the tutorial, use the following steps to create a password for your user:

   1. Check your email for the subject line **Invitation to join AWS IAM Identity Center**.

   1. Open that invitation email and choose **Accept invitation**.

   1. In the new window, set a password for your IAM Identity Center user.

   If you want to sign in later to the portal as the second and third IAM Identity Center users that you created earlier, you can also complete these steps to set passwords for those users.
**Note**  
If you didn't receive an email, you can generate a password for your user in the IAM Identity Center console. For more information, see [Reset the IAM Identiy Center user password for an end user](https://docs.aws.amazon.com/singlesignon/latest/userguide/reset-password-for-user.html) in the *AWS IAM Identity Center User Guide*.

1. Enter your IAM Identity Center **Username** and **Password**. If you created your IAM Identity Center user earlier in this tutorial, your **Username** is the email address of the portal administrator user that you created.

   All portal users, including the portal administrator, must sign in with their IAM Identity Center user credentials. These credentials are typically not the same credentials that you use to sign in to the AWS Management Console.  
![\[The portal sign-in page.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/portal-sign-in-console.png)

1. Choose **Sign in**.

   Your portal opens.

## Step 3: Create a wind farm project
<a name="monitor-tutorial-create-project"></a>

In this procedure, you create a project in your portal. *Projects* are resources that define a set of permissions, assets, and dashboards, which you can configure to visualize asset data in that project. With projects, you define who has access to which subsets of your operation and how those subsets' data is visualized. You can assign portal users as owners or viewers of each project. Project owners can create dashboards to visualize data and share the project with other users. Project viewers can view dashboards but not edit them. For more information about roles in SiteWise Monitor, see [SiteWise Monitor roles](monitor-data.md#monitor-roles).

**To create a wind farm project**

1. In the left navigation pane in your portal, choose the **Assets** tab. On the **Assets** page, you can explore all assets available in the portal and add assets to projects.

1. In the asset browser, choose **Demo Wind Farm Asset**. When you choose an asset, you can explore that asset's live and historical data. You can also press Shift to select multiple assets and compare their data side-by-side.

1. Choose **Add asset to project** in the upper left. Projects contain dashboards that your portal users can view to explore your data. Each project has access to a subset of your assets in AWS IoT SiteWise. When you add an asset to a project, all users with access to that project can also access data for that asset and its children.  
![\[The "Assets" page with the demo wind farm asset and "Add asset to project" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/portal-add-asset-project-console.png)

1. In the **Add asset to project** dialog box, choose **Create new project**, and then choose **Next**.  
![\[The "Add asset to project" dialog box with "Create new project" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/portal-choose-new-project-console.png)

1. In the **Create new project** dialog box, enter a **Project name** and **Project description** for your project, and then choose **Add asset to project**.  
![\[The "Create new project" dialog box.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/portal-create-new-project-console.png)

   Your new project's page opens.

1. On the project's page, you can add portal users as owners or viewers of this project.
**Note**  
If you aren't signed in to your AWS Organizations management account, you might not have portal users to assign to this project, so you can skip this step.

   On this page, do the following:

   1. Under **Project owners**, choose **Add owners** or **Edit users**.  
![\[The "Project details" page with "Assign users" and "Edit users" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/project-add-owners-console.png)

   1. Choose the user to add as a project owner (for example, **Mary Major**), and then choose the **>>** icon.  
![\[The "Project owners" dialog box with a user highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/project-choose-owner-console.png)

   1. Choose **Save**.

      Your IAM Identity Center user **Mary Major** can sign in to this portal to edit the dashboards in this project and share this project with other users in this portal.

   1. Under **Project viewers**, choose **Add viewers** or **Edit users**.

   1. Choose the user to add as a project viewer (for example, **Mateo Jackson**), and then choose the **>>** icon.

   1. Choose **Save**.

      Your IAM Identity Center user **Mateo Jackson** can sign in to this portal to view, but not edit, the dashboards in the wind farm project.

## Step 4: Create a dashboard to visualize wind farm data
<a name="monitor-tutorial-create-dashboard"></a>

In this procedure, you create dashboards to visualize the demo wind farm data. Dashboards contain customizable visualizations of your project's asset data. Each visualization can have a different type, such as a line chart, bar chart, or key performance indicator (KPI) display. You can choose the visualization type that works best for your data. Project owners can edit dashboards, whereas project viewers can only view dashboards to gain insights.

**To create a dashboard with visualizations**

1. On your new project's page, choose **Create dashboard** to create a dashboard and open its edit page.

   In a dashboard's edit page, you can drag asset properties from the asset hierarchy to the dashboard to create visualizations. Then, you can edit each visualization's title, legend titles, type, size, and location in the dashboard.

1. Enter a name your dashboard.  
![\[The "Dashboard" edit page with the dashboard name highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/dashboard-edit-console.png)

1. Drag **Total Average Power** from the **Demo Wind Farm Asset** to the dashboard to create a visualization.  
![\[The "Dashboard" edit page with the "Average Total Power" property dragging an asset property to the dashboard.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/dashboard-add-total-power-console.png)

1. Choose **Demo Turbine Asset 1** to show properties for that asset, and then drag **Wind Speed** to the dashboard to create a visualization for wind speed.  
![\[The "Dashboard" edit page with a wind turbine's "Wind Speed" property highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/dashboard-add-wind-speed-console.png)

1. Add **Wind Speed** to the new wind speed visualization for each **Demo Turbine Asset 2**, **3**, and **4** (in that order).

   Your **Wind Speed** visualization should look similar to the following screenshot.  
![\[A "Wind Speed" visualization that contains four demo wind turbine assets' wind speeds.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/dashboard-add-all-wind-speeds-console.png)

1. Repeat steps 4 and 5 for the wind turbines' **Torque (KiloNewton Meter)** properties to create a visualization for wind turbine torque.

1. Choose the visualization type icon for the **Torque (KiloNewton Meter)** visualization, and then choose the bar chart icon.  
![\[A "Torque (KiloNewton Meter)" visualization with visualization type and bar chart icons.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/dashboard-change-torque-visualization-type-console.png)

1. Repeat steps 4 and 5 for the wind turbines' **Wind Direction** properties to create a visualization for wind direction.

1. Choose the visualization type icon for the **Wind Direction** visualization, and then choose the KPI chart icon (**30%**).  
![\[A "Wind Direction" visualization with the visualization type and KPI chart icons highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/dashboard-change-wind-direction-visualization-type-console.png)

1. (Optional) Make other changes to each visualization's title, legend titles, type, size, and location as needed.

1. Choose **Save dashboard** in the upper right to save your dashboard.

   Your dashboard should look similar to the following screenshot.  
![\[A complete wind farm dashboard.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/wind-farm-dashboard-console.png)

1. (Optional) Create an additional dashboard for each wind turbine asset.

   As a best practice, we recommend that you create a dashboard for each asset so that your project viewers can investigate any issues with each individual asset. You can only add up to 5 assets to each visualization, so you must create multiple dashboards for your hierarchical assets in many scenarios.

   A dashboard for a demo wind turbine might look similar to the following screenshot.  
![\[A complete wind turbine dashboard.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/wind-turbine-dashboard-console.png)

1. (Optional) Change the timeline or select data points on a visualization to explore the data in your dashboard. For more information, see [Viewing dashboards](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/view-dashboards.html) in the *AWS IoT SiteWise Monitor Application Guide*.

## Step 5: Explore the portal
<a name="monitor-tutorial-explore-portal"></a>

In this procedure, you can explore the portal as a user with fewer permissions than an AWS IoT SiteWise portal administrator.

**To explore the portal and finish the tutorial**
+ (Optional) If you added other users to the project as owners or viewers, you can sign in to the portal as these users. This lets you explore the portal as a user with fewer permissions than a portal administrator.
**Important**  
You're charged for each user that signs in to a portal. For more information, see [AWS IoT SiteWise Pricing](https://aws.amazon.com/iot-sitewise/pricing/).

  To explore the portal as other users, do the following:

  1. Choose **Log out** in the bottom left of the portal to exit the web application.

  1. Choose **Sign out** in the upper right of the IAM Identity Center application portal to sign out of your IAM Identity Center user.

  1. Sign in to the portal as the IAM Identity Center user that you assigned as a project owner or project viewer. For more information, see [Step 2: Sign in to a portal](#monitor-tutorial-sign-in-portal).

 You've completed the tutorial. When you finish exploring your demo wind farm in SiteWise Monitor, follow the next procedure to clean up your resources. 

## Step 6: Clean up resources after the tutorial
<a name="monitor-tutorial-clean-up-resources"></a>

After you complete the tutorial, you can clean up your resources. You aren't charged for AWS IoT SiteWise if users don't sign in to your portal, but you can delete your portal and AWS IAM Identity Center directory users. Your demo wind farm assets are deleted at the end of the duration that you chose when you created the demo, or you can delete the demo manually. For more information, see [Delete the AWS IoT SiteWise demo](getting-started-demo.md#delete-getting-started-demo).

Use the following procedures to delete your portal and IAM Identity Center users.

**To delete a portal**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Portals**.

1. Choose your portal, **WindFarmPortal**, and then choose **Delete**.

   When you delete a portal or project, the assets associated to deleted projects aren't affected.  
![\[The "Portals" page with the wind farm portal and "Delete" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/sitewise-choose-delete-portal-console.png)

1. In the **Delete portal** dialog box, choose **Remove administrators and users**.  
![\[The "Delete portal" dialog box with "Remove administrators and users" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/sitewise-delete-portal-remove-users-console.png)

1. Enter **delete** to confirm deletion, and then choose **Delete**.  
![\[The "Delete portal" dialog box with "Delete" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/sitewise-delete-portal-confirm-delete-console.png)

**To delete IAM Identity Center users**

1. Navigate to the [IAM Identity Center console](https://console.aws.amazon.com/singlesignon).

1. In the left navigation pane, choose **Users**.

1. Select the check box for each user to delete, and then choose **Delete users**.  
![\[IAM Identity Center "Users" page with "Delete users" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/sso-choose-delete-users-console.png)

1. In the **Delete users** dialog box, enter **DELETE**, and then choose **Delete users**.  
![\[IAM Identity Center "Delete users" dialog box.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/monitor-wind-farm/sso-delete-users-console.png)

# Publish property value updates to Amazon DynamoDB
<a name="publish-to-amazon-dynamodb"></a>

This tutorial introduces a convenient way to store your data by using [Amazon DynamoDB](https://aws.amazon.com/dynamodb/), making it easier to access historical asset data without repeatedly querying the AWS IoT SiteWise API. After you complete this tutorial, you can create custom software that consumes your asset data, such as a live map of wind speed and direction over an entire wind farm. If you want to monitor and visualize your data without implementing a custom software solution, see [Monitor data with AWS IoT SiteWise Monitor](monitor-data.md).

In this tutorial, you build on the AWS IoT SiteWise demo that provides a sample set of data for a wind farm. You configure property value updates from the wind farm demo to send data, through AWS IoT Core rules, to a DynamoDB table that you create. When you enable property value updates, AWS IoT SiteWise sends your data to AWS IoT Core in MQTT messages. Then, define AWS IoT Core rules that perform actions, such as the DynamoDB action, depending on the contents of those messages. For more information, see [Interact with other AWS services](interact-with-other-services.md).

**Topics**
+ [Prerequisites](#dynamodb-tutorial-prerequisites)
+ [Step 1: Configure AWS IoT SiteWise to publish property value updates](#dynamodb-tutorial-enable-value-notifications)
+ [Step 2: Create a rule in AWS IoT Core](#dynamodb-tutorial-create-iot-rule)
+ [Step 3: Configure the DynamoDB rule action](#dynamodb-tutorial-configure-rule-action)
+ [Step 4: Explore data in DynamoDB](#dynamodb-tutorial-explore-dynamodb-data)
+ [Clean up resources](#dynamodb-tutorial-clean-up-resources)
+ [Additional resources](#dynamodb-tutorial-additional-resources)

## Prerequisites
<a name="dynamodb-tutorial-prerequisites"></a>

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, see [Set up an AWS account](getting-started.md#set-up-aws-account).
+ A development computer running Windows, macOS, Linux, or Unix to access the AWS Management Console. For more information, see [What is the AWS Management Console?](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/what-is.html)
+ An AWS Identity and Access Management (IAM) user with administrator permissions. For detailed instructions, see [How AWS IoT SiteWise works with IAM](security_iam_service-with-iam.md).
+ A running AWS IoT SiteWise demo. For more information, see [Use the AWS IoT SiteWise demo](getting-started-demo.md).

**Note**  
This tutorial requires the use of resources created in the [Use the AWS IoT SiteWise demo](getting-started-demo.md). You must complete it before proceeding with this tutorial.

**Important**  
Keep all demo resources until you complete this tutorial. Deleting any components might disrupt the demo's functionality and affect your ability to complete the tutorial.

## Step 1: Configure AWS IoT SiteWise to publish property value updates
<a name="dynamodb-tutorial-enable-value-notifications"></a>

In this procedure, you enable property value notifications on your demo turbine assets' **Wind Speed** properties. After you enable property value notifications, AWS IoT SiteWise publishes each value update in an MQTT message to AWS IoT Core.

**To enable property value update notifications on asset properties**

1. Sign in to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. Review the [AWS IoT SiteWise endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/iot-sitewise.html) where AWS IoT SiteWise is supported and switch AWS Regions, if necessary. Switch to a Region where you're running the AWS IoT SiteWise demo.

1. In the left navigation pane, choose **Assets**.

1. Choose the arrow next to **Demo Wind Farm Asset** to expand the wind farm asset's hierarchy.

1. Choose a demo turbine and choose **Edit**.

1. Choose **Measurements**.

1. Update the **Wind Speed** property's **MQTT Notification status** to **ACTIVE**.

1. Choose **Save** at the bottom of the page.

1. Repeat steps 5 through 7 for each demo turbine asset.

1. Choose a demo turbine (for example, **Demo Turbine Asset 1**).

1. Choose **Measurements**.

1. Choose the copy icon next to the **Wind Speed** property to copy the notification topic to your clipboard. Save the notification topic to use later in this tutorial. You only need to record the notification topic from one turbine.

   The notification topic should look like the following example.

   ```
   $aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE/assets/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE/properties/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
   ```

## Step 2: Create a rule in AWS IoT Core
<a name="dynamodb-tutorial-create-iot-rule"></a>

In this step, create a rule in AWS IoT Core that parses the property value notification messages and inserts data into an Amazon DynamoDB table. AWS IoT Core rules parse MQTT messages and perform actions based on the contents and topic of each message. Then, you create a rule with a DynamoDB action to insert data to a DynamoDB table that you create as part of this tutorial.

**To create a rule with a DynamoDB action**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Message routing**, and then choose **Rules**.

1. Choose **Create rule**.

1. Under **Specify rule properties**, enter a name and description for the rule.

1. Find the notification topic that you saved earlier in this tutorial.

   ```
   $aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE/assets/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE/properties/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
   ```

   Replace the asset ID (the ID after `assets/`) in the topic with a `+`. This selects the wind speed property for all demo wind turbine assets. The `+` topic filter accepts all nodes from a single level in a topic. Your topic should look like the following example.

   ```
   $aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE/assets/+/properties/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
   ```

1. Enter the following rule query statement. Replace the topic in the `FROM` section with your notification topic.

   ```
   SELECT
     payload.assetId AS asset,
     (SELECT VALUE (value.doubleValue) FROM payload.values) AS windspeed,
     timestamp() AS timestamp
   FROM
     '$aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE/assets/+/properties/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE' 
   WHERE
     type = 'PropertyValueUpdate'
   ```

1. Under **Rule actions**, navigate to **Action 1**.

1. On the **Select an action** page, choose **DynamoDBv2**. This splits the message into multiple columns of a DynamoDB table

1. Under **Table name**, choose **Create new table**. You create an Amazon DynamoDB table to receive wind speed data from the rule action.

1. Under **Table name** in the [DynamoDB console](https://console.aws.amazon.com/dynamodb/) enter a name for your table.

1. For **Partition key**, do the following:

   1. Enter **timestamp** as the partition key.

   1. Choose the **Number** type.

   1. Select the **Add sort key** check box.

   1. Enter **asset** as the sort key, and leave the default sort key type of **String**.

1. Choose **Create table**.

1. Return to the tab with the **Configure action** page.

1. On the **Attach rule action** page, refresh the **Table name** list, and choose your new DynamoDB table you created in the previous step.

## Step 3: Configure the DynamoDB rule action
<a name="dynamodb-tutorial-configure-rule-action"></a>

In this step, configure the Amazon DynamoDB rule action to insert data from property value updates to your new DynamoDB table.

**To configure the DynamoDB rule action**

1. Choose **Create role** to create an IAM role that grants AWS IoT Core access to perform the rule action.

1. Enter a role name, for example, `WindSpeedDataRole`. Choose **Create role**.

1. Choose **Next**.

1. Choose **Create** at the bottom of the page to finish creating the rule.

   Your demo asset data should start appearing in your DynamoDB table.

## Step 4: Explore data in DynamoDB
<a name="dynamodb-tutorial-explore-dynamodb-data"></a>

In this step, explore the demo assets' wind speed data in your new Amazon DynamoDB table.

**To explore asset data in DynamoDB**

1. Return to the tab with the DynamoDB table open.

1. In the table you created earlier, choose the **Explore table items** tab to view the data in the table. Refresh the page if you don't see rows in the table. If rows don't appear after a few minutes, see [Troubleshoot a rule (DynamoDB)](troubleshoot-rule.md#dynamodb-tutorial-troubleshoot-rule).

1. In a row in the table, choose the edit icon to expand the data.

1. Choose the arrow next to the **windspeed** structure to expand the list of wind speed data points. Each list reflects a batch of wind speed data points sent to AWS IoT SiteWise by the wind farm demo. You might want a different data format if you set up a rule action for your own use. For more information, see [Query asset property notifications in AWS IoT SiteWise](query-notification-messages.md).

Now that you have completed the tutorial, you can disable or delete the rule and delete your DynamoDB table to avoid incurring additional charges. To clean up your resources, see [Clean up resources](#dynamodb-tutorial-clean-up-resources).

You can also learn how to create custom applications to consume and visualize this data. For a guided tutorial on visualizing AWS IoT SiteWise data, see [Visualize and share data in Grafana](visualize-with-grafana.md).

## Clean up resources
<a name="dynamodb-tutorial-clean-up-resources"></a>

After you complete the tutorial, clean up your resources to avoid incurring additional charges.

**To delete the AWS IoT SiteWise demo**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the upper-right corner of the page, choose **Delete demo**.

1. In the confirmation dialog, enter **DELETE** and then choose **Delete**.

For more information, see [Delete the AWS IoT SiteWise demo](getting-started-demo.md#delete-getting-started-demo).

Use the following procedures to disable property value update notifications (if you didn't delete the demo), disable or delete your AWS IoT rule, and delete your DynamoDB table.

**To disable property value update notifications on asset properties**

1. Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the left navigation pane, choose **Assets**.

1. Choose the arrow next to **Demo Wind Farm Asset** to expand the wind farm asset's hierarchy.

1. Choose a demo turbine and choose **Edit**.

1. Update the **Wind Speed** property's **Notification status** to **INACTIVE**.

1. Choose **Save asset** at the bottom of the page.

1. Repeat steps 4 through 6 for each demo turbine asset.

**To disable or delete a rule in AWS IoT Core**

1. Navigate to the [AWS IoT console](https://console.aws.amazon.com/iot/).

1. In the left navigation pane, choose **Message routing** and then choose **Rules**.

1. Select your rule and choose **Delete**.

1. In the confirmation dialog, enter the name of the rule and then choose Delete.

**To delete a DynamoDB table**

1. Navigate to the [DynamoDB console](https://console.aws.amazon.com/dynamodb/).

1. In the left navigation pane, choose **Tables**.

1. Choose the table you created earlier, for example, `WindSpeedData`.

1. Choose **Delete**.

1. In the confirmation dialog, enter **confirm** to delete the table.

## Additional resources
<a name="dynamodb-tutorial-additional-resources"></a>

For more information about working with DynamoDB and monitoring your data, see the following resources:
+ [Monitoring metrics in with CloudWatch ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Monitoring-metrics-with-Amazon-CloudWatch.html) in the *DynamoDB Developer Guide*
+ [Best practices for designing and using partition keys effectively in ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html) in the *DynamoDB Developer Guide*
+ [Rules for AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) in the *AWS IoT Developer Guide*
+ [Visualize and share data in Grafana](visualize-with-grafana.md)