

# Interact with other AWS services
Interact with other services

AWS IoT SiteWise can publish asset data to the AWS IoT MQTT publish-subscribe message broker, so that you can interact with your asset data from other AWS services. AWS IoT SiteWise assigns each asset property a unique MQTT topic that you can use to route your asset data to other AWS services using AWS IoT Core rules. For example, you can configure AWS IoT Core rules to do the following tasks:
+ Identify equipment failure and notify appropriate personnel by sending data to [AWS IoT Events](https://docs.aws.amazon.com/iotevents/latest/developerguide/).
+ Historize select asset data for use in external software solutions by sending data to [Amazon DynamoDB](https://docs.aws.amazon.com/dynamodb/).
+ Generate weekly reports by triggering an [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/) function.

You can follow a tutorial that walks through the steps required to set up a rule that stores property values in DynamoDB. For more information, see [Publish property value updates to Amazon DynamoDB](publish-to-amazon-dynamodb.md).

For more information about how to configure a rule, see [Rules](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) in the *AWS IoT Developer Guide*.

You can also consume data from other AWS services back into AWS IoT SiteWise. To ingest data through the AWS IoT SiteWise rule action, see [Ingest data to AWS IoT SiteWise using AWS IoT Core rules](iot-rules.md).

**Topics**
+ [

# Understand asset properties in MQTT topics
](mqtt-topics.md)
+ [

# Turn on asset property notifications in AWS IoT SiteWise
](property-notifications.md)
+ [

# Query asset property notifications in AWS IoT SiteWise
](query-notification-messages.md)
+ [

# Export data to Amazon S3 with asset property notifications
](export-to-s3.md)
+ [

# Integrate AWS IoT SiteWise with Grafana
](grafana-integration.md)
+ [

# Integrate AWS IoT SiteWise and AWS IoT TwinMaker
](integrate-tm.md)
+ [

# Detect anomalies with Lookout for Equipment
](anomaly-detection.md)

# Understand asset properties in MQTT topics


Every asset property has a unique MQTT topic path in the following format.

```
$aws/sitewise/asset-models/assetModelId/assets/assetId/properties/propertyId
```

**Note**  
AWS IoT SiteWise doesn't support the `#` (multi-level) topic filter wildcard in the AWS IoT Core rules engine. You can use the `+` (single-level) wildcard. For example, you can use the following topic filter to match all updates for a particular asset model.  

```
$aws/sitewise/asset-models/assetModelId/assets/+/properties/+
```
To learn more about topic filter wildcards, see [Topics](https://docs.aws.amazon.com/iot/latest/developerguide/topics.html) in the *AWS IoT Core Developer Guide*.

# Turn on asset property notifications in AWS IoT SiteWise
Work with notifications

You can enable property notifications to publish asset data updates to AWS IoT Core, and then run queries on your data. With asset property notifications, AWS IoT SiteWise provides an CloudFormation template that you can use to export AWS IoT SiteWise data to Amazon S3.

**Note**  
Asset data is sent to AWS IoT Core every time it's received by AWS IoT SiteWise, regardless of if the value has changed.

**Topics**
+ [

## Turn on asset property notifications (console)
](#enable-property-notifications-console)
+ [

## Turn on asset property notifications (AWS CLI)
](#enable-property-notifications-cli)

## Turn on asset property notifications (console)


By default, AWS IoT SiteWise doesn't publish property value updates. You can use the AWS IoT SiteWise console to enable notifications for an asset property.

**To enable or disable notifications for an asset property (console)**

1. <a name="sitewise-open-console"></a>Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. <a name="sitewise-choose-assets"></a>In the navigation pane, choose **Assets**.

1. Choose the asset to enable a property's notifications.
**Tip**  <a name="sitewise-expand-asset-hierarchy"></a>
You can choose the arrow icon to expand an asset hierarchy to find your asset.

1. Choose **Edit**.

1. For the asset property's **Notification status**, choose **ENABLED**.  
![\[AWS IoT SiteWise "Edit asset" page screenshot with "Notification status" highlighted.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/sitewise-enable-property-notifications-console.png)

   You can also choose **DISABLED** to disable notifications for the asset property.

1. Choose **Save**.

## Turn on asset property notifications (AWS CLI)


By default, AWS IoT SiteWise doesn't publish property value updates. You can use the AWS Command Line Interface (AWS CLI) to enable or disable notifications for an asset property.

You must know your asset's `assetId` and property's `propertyId` to complete this procedure. You can also use the external ID. If you created an asset and don't know its `assetId`, use the [ListAssets](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_ListAssets.html) API to list all the assets for a specific model. Use the [DescribeAsset](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_DescribeAsset.html) operation to view your asset's properties including property IDs.

Use the [UpdateAssetProperty](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_UpdateAssetProperty.html) operation to enable or disable notifications for an asset property. Specify the following parameters:
+ `assetId` – The asset's ID.
+ `propertyId` – The asset property's ID.
+ `propertyNotificationState` – The property value notification state: `ENABLED` or `DISABLED`.
+ `propertyAlias` – The alias of the property. Specify the property's existing alias when you update the notification state. If you omit this parameter, the property's existing alias is removed.

**To enable or disable notifications for an asset property (CLI)**

1. Run the following command to retrieve the asset property's alias. Replace *asset-id* with the ID of the asset and *property-id* with the ID of the property.

   ```
   aws iotsitewise describe-asset-property \
     --asset-id asset-id \
     --property-id property-id
   ```

   The operation returns a response that contains the asset property's details in the following format. The property alias is in `assetProperty.alias` in the JSON object.

   ```
   {
     "assetId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
     "assetName": "Wind Turbine 7",
     "assetModelId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
     "assetProperty": {
       "id": "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
       "name": "Wind Speed",
       "alias": "/company/windfarm/3/turbine/7/windspeed",
       "notification": {
         "topic": "$aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE/assets/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE/properties/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
         "state": "DISABLED"
       },
       "dataType": "DOUBLE",
       "unit": "m/s",
       "type": {
         "measurement": {}
       }
     }
   }
   ```

1. Run the following command to enable notifications for the asset property. Replace *property-alias* with the property alias from the previous command's response, or omit `--property-alias` to update the property without an alias.

   ```
   aws iotsitewise update-asset-property \
     --asset-id asset-id \
     --property-id property-id \
     --property-notification-state ENABLED \
     --property-alias property-alias
   ```

   You can also pass `--property-notification-state DISABLED` to disable notifications for the asset property.

# Query asset property notifications in AWS IoT SiteWise
Query notifications

To query asset property notifications, create AWS IoT Core rules made up of SQL statements.

AWS IoT SiteWise publishes asset property data updates to AWS IoT Core in the following format.

```
{
  "type": "PropertyValueUpdate",
  "payload": {
    "assetId": "String",
    "propertyId": "String",
    "values": [
      {
        "timestamp": {
          "timeInSeconds": Number,
          "offsetInNanos": Number
        },
        "quality": "String",
        "value": {
          "booleanValue": Boolean,
          "doubleValue": Number,
          "integerValue": Number,
          "stringValue": "String",
          "nullValue": {
            "valueType": "String
            }           
        }
      }
    ]
  }
}
```

Each structure in the `values` list is a timestamp-quality-value (TQV) structure.
+ The `timestamp` contains the current Unix epoch time in seconds with nanosecond offset.
+ The `quality` contains one of the following strings that indicate the quality of the data point:
  + `GOOD` – The data isn't affected by any issues.
  + `BAD` – The data is affected by an issue such as sensor failure.
  + `UNCERTAIN` – The data is affected by an issue such as sensor inaccuracy.
+ The `value` contains one of the following fields, depending on the type of the property:
  + `booleanValue`
  + `doubleValue`
  + `integerValue`
  + `stringValue`
  + `nullValue`

`nullValue` – A structure with the following field denoting the type of the property value with value Null and quality of `BAD` or `UNCERTAIN`.
+ `valueType` – Enum of \$1"B", "D", "S", "I"\$1

To parse values out of the `values` array, you need to use complex nested object queries in your rules' SQL statements. For more information, see [Nested object queries](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-nested-queries.html) in the *AWS IoT Developer Guide*, or see the [Publish property value updates to Amazon DynamoDB](publish-to-amazon-dynamodb.md) tutorial for a specific example of parsing asset property notification messages.

**Example query to extract the array of values**  
The following statement demonstrates how to query the array of updated property values for a specific double-type property on all assets with that property.  

```
SELECT
  (SELECT VALUE (value.doubleValue) FROM payload.values) AS windspeed
FROM
  '$aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE/assets/+/properties/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE' 
WHERE
  type = 'PropertyValueUpdate'
```
The previous rule query statement outputs data in the following format.  

```
{
  "windspeed": [
    26.32020195042838,
    26.282584572975477,
    26.352566977372508,
    26.283084346171442,
    26.571883739599322,
    26.60684140743005,
    26.628738636715045,
    26.273486932802125,
    26.436379105473964,
    26.600590095377303
  ]
}
```

**Example query to extract a single value**  
The following statement demonstrates how to query the first value from the array of property values for a specific double-type property on all assets with that property.  

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

The previous rule query statement outputs data in the following format.

```
{
  "windspeed": 26.32020195042838
}
```

**Important**  
This rule query statement ignores value updates other than the first in each batch. Each batch can contain up to 10 values. If you need to include the remaining values, you must set up a more complex solution to output asset property values to other services. For example, you can set up a rule with an AWS Lambda action to republish each value in the array to another topic, and set up another rule to query that topic and publish each value to the desired rule action.

# Export data to Amazon S3 with asset property notifications
Export data to Amazon S3

You can export incoming data from AWS IoT SiteWise to an Amazon S3 bucket in your account. You can back up your data in a format that you can use to create historical reports or to analyze your data with complex methods. 

 To export time series data from AWS IoT SiteWise, enable the cold tier feature to have the data stored in an Amazon S3 bucket. See [Manage data storage in AWS IoT SiteWise](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-data-storage.html) for details. 

 To export asset model and asset metadata from AWS IoT SiteWise, use the bulk operations feature to export metadata to an Amazon S3 bucket. See [Bulk operations with assets and models](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/bulk-operations-assets-and-models.html) for details. 

# Integrate AWS IoT SiteWise with Grafana
Integrate Grafana

Grafana is a data visualization platform used to visualize and monitor data in dashboards. In Grafana version 10.4.0 and later, use the AWS IoT SiteWise plugin to visualize your AWS IoT SiteWise asset data in Grafana dashboards. Users can visualize data from multiple AWS sources (such as AWS IoT SiteWise, Amazon Timestream, and Amazon CloudWatch) and other data sources with a single Grafana dashboard.

You have two options to use the AWS IoT SiteWise plugin:
+ **Local Grafana servers**

  You can set up the AWS IoT SiteWise plugin on a Grafana server that you manage. For more information about how to add and use the plugin, see the [AWS IoT SiteWise Datasource README](https://github.com/grafana/iot-sitewise-datasource/blob/main/src/README.md) file on the GitHub website.
+ **AWS Managed Service for Grafana**

  You can use the AWS IoT SiteWise plugin in the AWS Managed Service for Grafana (AMG). AMG manages Grafana servers for you so that you can visualize your data without having to build, package, or deploy any hardware or any other Grafana infrastructure. For more information, see the following topics in the *AWS Managed Service for Grafana User Guide*:
  + [What is Amazon Managed Service for Grafana (AMG)?](https://docs.aws.amazon.com/grafana/latest/userguide/what-is-Amazon-Managed-Service-Grafana.html)
  + [Using the AWS IoT SiteWise data source](https://docs.aws.amazon.com/grafana/latest/userguide/using-iotsitewise-in-AMG.html)

**Example Grafana dashboard**  
The following Grafana dashboard visualizes the [demo wind farm](getting-started-demo.md). You can access this demo dashboard on the [Grafana Play](https://play.grafana.org/d/avzwehmz/demo-wind-farm?orgId=1) website.  

![\[An example Grafana dashboard that visualizes the AWS IoT SiteWise demo wind farm.\]](http://docs.aws.amazon.com/iot-sitewise/latest/userguide/images/grafana-dashboard-example.png)


# Integrate AWS IoT SiteWise and AWS IoT TwinMaker
Integrate with AWS IoT TwinMaker

Integrating with AWS IoT TwinMaker grants access to robust functionality in AWS IoT SiteWise, such as AWS IoT SiteWise data retrieval `ExecuteQuery` API and advanced asset search in the AWS IoT SiteWise console. To integrate the services and use these features, you must first enable the integration.

**Topics**
+ [

## Enabling the integration
](#it-enable)
+ [

## Integrating AWS IoT SiteWise and AWS IoT TwinMaker
](#it-integrate)

## Enabling the integration


Administrators can use AWS JSON policies to specify who has access to what. That is, which *principal* can perform *actions* on what *resources*, and under what *conditions*. The `Action` element of a JSON policy describes the actions that you can use to allow or deny access in a policy. For more information about AWS IoT SiteWise supported actions, see [Actions defined by AWS IoT SiteWise](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotsitewise.html#awsiotsitewise-actions-as-permissions) in the *Service Authorization Reference*.

For more information about AWS IoT TwinMaker service-linked role, see [Service-linked roles for AWS IoT TwinMaker](https://docs.aws.amazon.com/iot-twinmaker/latest/guide/security_iam_service-with-iam.html#security_iam_service-with-iam-roles-service-linked) in the *AWS IoT TwinMaker User Guide*.

Before you can integrate AWS IoT SiteWise and AWS IoT TwinMaker, you must grant the following permissions that allow AWS IoT SiteWise to integrate with an AWS IoT TwinMaker linked workspace:
+ `iotsitewise:EnableSiteWiseIntegration` – Allows AWS IoT SiteWise to integrate with a linked AWS IoT TwinMaker workspace. This integration allows AWS IoT TwinMaker to read all your modeling information in AWS IoT SiteWise through an AWS IoT TwinMaker service-linked role. To enable this permission, add the following policy to your IAM role:

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

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
          "iotsitewise:EnableSiteWiseIntegration"
        ],
        "Resource": "*"
      }
    ]
  }
  ```

------

## Integrating AWS IoT SiteWise and AWS IoT TwinMaker


To integrate AWS IoT SiteWise and AWS IoT TwinMaker, you must have the following:
+ AWS IoT SiteWise service-linked role set up in your account
+ AWS IoT TwinMaker service-linked role set up in your account
+ AWS IoT TwinMaker workspace with ID `IoTSiteWiseDefaultWorkspace` in your account in the Region.

### To integrate by using the AWS IoT SiteWise console


When you see the **Integration with AWS IoT TwinMaker** banner in the console, choose **Grant permission**. The prerequisites are created in your account.

### To integrate by using the AWS CLI


To integrate AWS IoT SiteWise and AWS IoT TwinMaker by using the AWS CLI, enter the following commands:

1. Call `CreateServiceLinkedRole` with an `AWSServiceName` of `iotsitewise.amazonaws.com`.

   ```
   aws iam create-service-linked-role --aws-service-name iotsitewise.amazonaws.com
   ```

1. Call `CreateServiceLinkedRole` with an `AWSServiceName` of ` iottwinmaker.amazonaws.com`.

   ```
   aws iam create-service-linked-role --aws-service-name iottwinmaker.amazonaws.com
   ```

1. Call `CreateWorkspace` with an `ID` of `IoTSiteWiseDefaultWorkspace`.

   ```
    aws iottwinmaker create-workspace --workspace-id IoTSiteWiseDefaultWorkspace
   ```

# Detect anomalies with Lookout for Equipment
Detect equipment anomalies

**Note**  
Anomaly detection is only available in the Regions where Amazon Lookout for Equipment is available.

You can integrate AWS IoT SiteWise with Amazon Lookout for Equipment to gain insights about your industrial equipment through anomaly detection and predictive maintenance of industrial equipment. Lookout for Equipment is a machine learning (ML) service for monitoring industrial equipment that detects abnormal equipment behavior and identifies potential failures. With Lookout for Equipment, you can implement predictive maintenance programs and identify suboptimal equipment processes. For more information about Lookout for Equipment, see [What is Amazon Lookout for Equipment?](https://docs.aws.amazon.com/lookout-for-equipment/latest/ug/what-is.html) in the* Amazon Lookout for Equipment User Guide*.

When you create a prediction to train an ML model to detect anomalous equipment behavior, AWS IoT SiteWise sends asset property values to Lookout for Equipment to train an ML model to detect anomalous equipment behavior. To define a prediction definition on an asset model, you specify the IAM roles needed for Lookout for Equipment to access your data and the properties to send to Lookout for Equipment and send processed data to Amazon S3. For more information, see [Create asset models in AWS IoT SiteWise](create-asset-models.md).

To integrate AWS IoT SiteWise and Lookout for Equipment, you'll perform the following high-level steps:
+ Add a prediction definition on an asset model that outlines what properties you want to track. The prediction definition is a reusable collection of measurements, transforms, and metrics that is used to create predictions on the assets that are based on that asset model.
+ Train the prediction based on historical data that you provide.
+ Schedule inference, which tells AWS IoT SiteWise how often to run a specific prediction.

Once inference is scheduled, the Lookout for Equipment model monitors the data it receives from your equipment and looks for anomalies in equipment behavior. You can view and analyze the results in SiteWise Monitor, using the AWS IoT SiteWise GET API operations, or the Lookout for Equipment console. You can also create alarms using alarm detectors from the asset model to alert you about abnormal equipment behavior.

**Topics**
+ [

## Add a prediction definition (console)
](#ad-add-prediction-definition-console)
+ [

## Train a prediction (console)
](#ad-train-prediction-console)
+ [

## Start or stop inference on a prediction (console)
](#ad-start-stop-inference-console)
+ [

## Add a prediction definition (CLI)
](#ad-add-prediction-definition-cli)
+ [

## Train a prediction and starting inference (CLI)
](#ad-train-inference-prediction-cli)
+ [

## Train a prediction (CLI)
](#ad-train-prediction-cli)
+ [

## Start or stop inference on a prediction (CLI)
](#ad-start-stop-inference-cli)

## Add a prediction definition (console)


To begin sending data collected by AWS IoT SiteWise to Lookout for Equipment, you must add an AWS IoT SiteWise prediction definition to an asset model.

**To add a prediction definition to an AWS IoT SiteWise asset model**

1. <a name="sitewise-open-console"></a>Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the navigation pane, choose **Models** and select the asset model to which you want to add the prediction definition.

1. Choose **Predictions**.

1. Choose **Add prediction definition**.

1. Define details about the prediction definition.

   1. Enter a unique **Name** and a **Description** for your prediction definition. Choose the name thoughtfully because after you create the prediction definition, you can't change its name.

   1. Create or select an **IAM permissions role** that allows AWS IoT SiteWise to share your asset data with Amazon Lookout for Equipment. The role should have the following IAM and trust policies. For help creating the role, see [Creating a role using custom trust policies (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-custom.html).

      **IAM policy**

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Sid": "L4EPermissions",
                  "Effect": "Allow",
                  "Action": [
                      "lookoutequipment:CreateDataset",
                      "lookoutequipment:CreateModel",
                      "lookoutequipment:CreateInferenceScheduler",
                      "lookoutequipment:DescribeDataset",
                      "lookoutequipment:DescribeModel",
                      "lookoutequipment:DescribeInferenceScheduler",
                      "lookoutequipment:ListInferenceExecutions",
                      "lookoutequipment:StartDataIngestionJob",
                      "lookoutequipment:StartInferenceScheduler",
                      "lookoutequipment:UpdateInferenceScheduler",
                      "lookoutequipment:StopInferenceScheduler"
                  ],
                  "Resource": [
                      "arn:aws:lookoutequipment:us-east-1:123456789012:inference-scheduler/IoTSiteWise_*",
                      "arn:aws:lookoutequipment:us-east-1:123456789012:model/IoTSiteWise_*",
                      "arn:aws:lookoutequipment:us-east-1:123456789012:dataset/IoTSiteWise_*"
                  ]
              },
              {
                  "Sid": "L4EPermissions2",
                  "Effect": "Allow",
                  "Action": [
                      "lookoutequipment:DescribeDataIngestionJob"
                  ],
                  "Resource": "*"
              },
              {
                  "Sid": "S3Permissions",
                  "Effect": "Allow",
                  "Action": [
                      "s3:CreateBucket",
                      "s3:ListBucket",
                      "s3:PutObject",
                      "s3:GetObject"
                  ],
                  "Resource": [
                      "arn:aws:s3:::iotsitewise-*"
                  ]
              },
              {
                  "Sid": "IAMPermissions",
                  "Effect": "Allow",
                  "Action": [
                      "iam:GetRole",
                      "iam:PassRole"
                  ],
                  "Resource": "arn:aws:iam::111122223333:role/Role_name"
              }
          ]
      }
      ```

------

      **Trust policy**

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Principal": {
                      "Service": "iotsitewise.amazonaws.com"
                  },
                  "Action": "sts:AssumeRole",
                  "Condition": {
                      "StringEquals": {
                          "aws:SourceAccount": "123456789012"
                      },
                      "ArnEquals": {
                          "aws:SourceArn": "arn:aws:iotsitewise:us-east-1:123456789012:asset/*"
                      }
                  }
              },
              {
                  "Effect": "Allow",
                  "Principal": {
                      "Service": "lookoutequipment.amazonaws.com"
                  },
                  "Action": "sts:AssumeRole",
                  "Condition": {
                      "StringEquals": {
                          "aws:SourceAccount": "123456789012"
                      },
                      "ArnEquals": {
                          "aws:SourceArn": "arn:aws:lookoutequipment:us-east-1:123456789012:*"
                      }
                  }
              }
          ]
      }
      ```

------

   1. Choose **Next**.

1. Select data attributes (measurements, transforms, and metrics) that you want to send to Lookout for Equipment.

   1. (Optional) Select measurements.

   1. (Optional) Select transforms.

   1. (Optional) Select metrics.

   1. Choose **Next**.

1. Review your selections. To add the prediction definition to the asset model, on the summary page, choose **Add prediction definition**.

You can also **Edit** or **Delete** an existing prediction definition that has active predictions attached.

## Train a prediction (console)


After you've added a prediction definition to an asset model, you can train the predictions that are on your assets.

**To train a prediction in AWS IoT SiteWise**

1. <a name="sitewise-open-console"></a>Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the navigation pane, choose **Assets**, and select the asset you want to monitor.

1. Choose **Predictions**.

1. Select the predictions that you want to train.

1. Under **Actions**, choose **Start training**, and do the following:

   1. Under **Prediction details**, select an IAM permissions role that allows AWS IoT SiteWise to share your asset data with Lookout for Equipment. If you need to create a new role, choose **Create a new role**.

   1. For **Training data settings**, enter a **Training data time range** to select which data to use to train the prediction.

   1. (Optional) Select sampling rate of the data after post processing.

   1. (Optional) For **Data labels**, provide an Amazon S3 bucket and prefix that holds your labeling data. For more information about labeling data, see [Labeling your data](https://docs.aws.amazon.com/lookout-for-equipment/latest/ug/labeling-data.html) in the* Amazon Lookout for Equipment User Guide*.

   1. Choose **Next**.

1. (Optional) If you want the prediction to be active as soon as it has completed training, under **Advanced settings**, select **Automatically activate the prediction after training**, and then do the following:

   1. Under **Input data**, for **Data upload frequency**, define how often data is uploaded, and for **Offset delay time**, define how much of a buffer to use.

   1. Choose **Next**.

1. Review the details of the prediction and choose **Save and start**.

## Start or stop inference on a prediction (console)


**Note**  
Lookout for Equipment charges apply to scheduled inferences with the data transferred between AWS IoT SiteWise and Lookout for Equipment. For more information, see [Amazon Lookout for Equipment pricing](https://aws.amazon.com/lookout-for-equipment/pricing/).

If you added the prediction `lookoutequipment:CreateDataset`, but did not choose to activate it after training, you must activate it to start monitoring your assets.

**To start inference for a prediction**

1. <a name="sitewise-open-console"></a>Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the navigation pane, choose **Assets**, and select the asset the prediction is added to.

1. Choose **Predictions**.

1. Select the predictions that you want to activate.

1. Under **Actions**, choose **Start inference**, and do the following:

   1. Under **Input data**, for **Data upload frequency**, define how often data is uploaded, and for **Offset delay time**, define how much of a buffer to use.

   1. Choose **Save and start**.

**To stop inference for a prediction**

1. <a name="sitewise-open-console"></a>Navigate to the [AWS IoT SiteWise console](https://console.aws.amazon.com/iotsitewise/).

1. In the navigation pane, choose **Assets**, and select the asset the prediction is added to.

1. Choose **Predictions**.

1. Select the predictions that you want to stop.

1. Under **Actions**, choose **Stop inference**.

## Add a prediction definition (CLI)


To define a prediction definition on a new or existing asset model, you can use the AWS Command Line Interface (AWS CLI). After you define the prediction definition on the asset model, you train, and schedule inference for, a prediction on an asset in AWS IoT SiteWise to do anomaly detection with Lookout for Equipment.

**Prerequisites**

To complete these steps, you must have an asset model and at least one asset created. For more information, see [Create an asset model (AWS CLI)](create-asset-models.md#create-asset-model-cli) and [Create an asset (AWS CLI)](create-assets.md#create-asset-cli).

If you are new to AWS IoT SiteWise, you must call the `CreateBulkImportJob` API operation to import asset property values into AWS IoT SiteWise, which will be used to train the model. For more information, see [Create an AWS IoT SiteWise bulk import job (AWS CLI)](CreateBulkImportJob.md).

**To add a prediction definition**

1. Create a file called `asset-model-payload.json`. Follow the steps in these other sections to add your asset model's details to the file, but don't submit the request to create or update the asset model.
   + For more information about how to create an asset model, see [Create an asset model (AWS CLI)](create-asset-models.md#create-asset-model-cli)
   + For more information about how to update an existing asset model, see [Update an asset model, component model, or interface (AWS CLI)](update-asset-models.md#update-asset-model-cli)

1. Add a Lookout for Equipment composite model (`assetModelCompositeModels`) to the asset model by adding the following code.
   + Replace `Property` with the ID of the properties that you want to include. To get those IDs, call [https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_DescribeAssetModel.html](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_DescribeAssetModel.html).
   + Replace `RoleARN` with the ARN of an IAM role that allows Lookout for Equipment to access your AWS IoT SiteWise data.

   ```
   { 
     ...
     "assetModelCompositeModels": [
       {
         "name": "L4Epredictiondefinition",
         "type": "AWS/L4E_ANOMALY",
         "properties": [
             {
               "name": "AWS/L4E_ANOMALY_RESULT",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_RESULT",
               "unit": "none",
               "type": {
                 "measurement": {}
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_INPUT",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_INPUT",
               "type": {
                  "attribute": {
                    "defaultValue": "{\"properties\": [\"Property1\", \"Property2\"]}"
                  }
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_PERMISSIONS",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_PERMISSIONS",
               "type": {
                 "attribute": {
                   "defaultValue": "{\"roleArn\": \"RoleARN\"}"
                 }
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_DATASET",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_DATASET",
               "type": {
                   "attribute": {}
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_MODEL",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_MODEL",
               "type": {
                 "attribute": {}
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_INFERENCE",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_INFERENCE",
               "type": {
                 "attribute": {}
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_TRAINING_STATUS",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_TRAINING_STATUS",
               "type": {
                 "attribute": {
                   "defaultValue": "{}"
                 }
               }
             },
             {
               "name": "AWS/L4E_ANOMALY_INFERENCE_STATUS",
               "dataType": "STRUCT",
               "dataTypeSpec": "AWS/L4E_ANOMALY_INFERENCE_STATUS",
               "type": {
                 "attribute": {
                   "defaultValue": "{}"
                 }
               }
             }
      ]
   }
   ```

1. Create the asset model or update the existing asset model. Do one of the following:
   + To create the asset model, run the following command:

     ```
     aws iotsitewise create-asset-model --cli-input-json file://asset-model-payload.json
     ```
   + To update the existing asset model, run the following command. Replace `asset-model-id` with the ID of the asset model that you want to update.

     ```
     aws iotsitewise update-asset-model \
       --asset-model-id asset-model-id \
       --cli-input-json file://asset-model-payload.json
     ```

 After you run the command, note the `assetModelId` in the response. 

## Train a prediction and starting inference (CLI)


Now that the prediction definition is defined, you can train assets based on it and start inference. If you want to train your prediction but not start inference, skip to [Train a prediction (CLI)](#ad-train-prediction-cli). To train the prediction and start inference on the asset, you’ll need the `assetId` of the target resource.

**To train and start inference of the prediction**

1. Run the following command to find the `assetModelCompositeModelId` under `assetModelCompositeModelSummaries`. Replace *`asset-model-id`* with the ID of the asset model that you created in [Update an asset model, component model, or interface (AWS CLI)](update-asset-models.md#update-asset-model-cli).

   ```
   aws iotsitewise describe-asset-model \
     --asset-model-id asset-model-id \
   ```

1. Run the following command to find the `actionDefinitionId` of the `TrainingWithInference` action. Replace *`asset-model-id`* with the ID used in previous step and replace *`asset-model-composite-model-id`* with the ID returned in the previous step.

   ```
   aws iotsitewise describe-asset-model-composite-model \
     --asset-model-id asset-model-id \
     --asset-model-composite-model-id asset-model-composite-model-id \
   ```

1. Create a file called `train-start-inference-prediction.json` and add the following code, replacing the following:
   + `asset-id` with the ID of the target asset
   + `action-definition-id` with the ID of the TrainingWithInference action
   + `StartTime` with the start of the training data, provided in epoch seconds
   + `EndTime` with the end of the training data, provided in epoch seconds
   + `TargetSamplingRate` with the sampling rate of the data after post processing by Lookout for Equipment. Allowed values are: `PT1S | PT5S | PT10S | PT15S | PT30S | PT1M | PT5M | PT10M | PT15M | PT30M | PT1H`.

   ```
   {
     "targetResource": {
       "assetId": "asset-id"
     },
     "actionDefinitionId": "action-definition-Id",
     "actionPayload":{
       "stringValue": "{\"l4ETrainingWithInference\":{\"trainingWithInferenceMode\":\"START\",\"trainingPayload\":{\"exportDataStartTime\":StartTime,\"exportDataEndTime\":EndTime},\"targetSamplingRate\":\"TargetSamplingRate\"},\"inferencePayload\":{\"dataDelayOffsetInMinutes\":0,\"dataUploadFrequency\":\"PT5M\"}}}"
     }
   }
   ```

1. Run the following command to start training and inference:

   ```
   aws iotsitewise execute-action --cli-input-json file://train-start-inference-prediction.json
   ```

## Train a prediction (CLI)


Now that the prediction definition is defined, you can train assets based on it. To train the prediction on the asset, you’ll need the `assetId` of the target resource.

**To train the prediction**

1. Run the following command to find the `assetModelCompositeModelId` under `assetModelCompositeModelSummaries`. Replace *`asset-model-id`* with the ID of the asset model that you created in [Update an asset model, component model, or interface (AWS CLI)](update-asset-models.md#update-asset-model-cli).

   ```
   aws iotsitewise describe-asset-model \
     --asset-model-id asset-model-id \
   ```

1. Run the following command to find the `actionDefinitionId` of the `Training` action. Replace *`asset-model-id`* with the ID used in previous step and replace *`asset-model-composite-model-id`* with the ID returned in the previous step.

   ```
   aws iotsitewise describe-asset-model-composite-model \
     --asset-model-id asset-model-id \
     --asset-model-composite-model-id asset-model-composite-model-id \
   ```

1. Create a file called `train-prediction.json` and add the following code, replacing the following:
   + `asset-id` with the ID of the target asset
   + `action-definition-id` with the ID of the training action
   + `StartTime` with the start of the training data, provided in epoch seconds
   + `EndTime` with the end of the training data, provided in epoch seconds
   + (Optional) `BucketName` with the name of the Amazon S3 bucket that holds your label data
   + (Optional) `Prefix` with the prefix associated with the Amazon S3 bucket.
   + `TargetSamplingRate` with the sampling rate of the data after post processing by Lookout for Equipment. Allowed values are: `PT1S | PT5S | PT10S | PT15S | PT30S | PT1M | PT5M | PT10M | PT15M | PT30M | PT1H`.
**Note**  
Include both the bucket name and prefix or neither.

   ```
   {
     "targetResource": {
       "assetId": "asset-id"
     },
     "actionDefinitionId": "action-definition-Id",
     "actionPayload":{ "stringValue": "{\"l4ETraining\": {\"trainingMode\":\"START\",\"exportDataStartTime\": StartTime, \"exportDataEndTime\": EndTime, \"targetSamplingRate\":\"TargetSamplingRate\"}, \"labelInputConfiguration\": {\"bucketName\": \"BucketName\", \"prefix\": \"Prefix\"}}}"
   }
   }
   ```

1. Run the following command to start training:

   ```
   aws iotsitewise execute-action --cli-input-json file://train-prediction.json
   ```

Before you can start inference, training must be completed. To check the status of the training, do one of the following:
+ From the console, navigate to the asset the prediction is on.
+ From the AWS CLI, call `BatchGetAssetPropertyValue` using the `propertyId` of the `trainingStatus` property.

## Start or stop inference on a prediction (CLI)


Once the prediction is trained, you can start inference to tell Lookout for Equipment to start monitoring your assets. To start or stop inference, you’ll need the `assetId` of the target resource.

**To start inference**

1. Run the following command to find the `assetModelCompositeModelId` under `assetModelCompositeModelSummaries`. Replace *`asset-model-id`* with the ID of the asset model that you created in [Update an asset model, component model, or interface (AWS CLI)](update-asset-models.md#update-asset-model-cli).

   ```
   aws iotsitewise describe-asset-model \
     --asset-model-id asset-model-id \
   ```

1. Run the following command to find the `actionDefinitionId` of the `Inference` action. Replace *`asset-model-id`* with the ID used in previous step and replace *`asset-model-composite-model-id`* with the ID returned in the previous step.

   ```
   aws iotsitewise describe-asset-model-composite-model \
     --asset-model-id asset-model-id \
     --asset-model-composite-model-id asset-model-composite-model-id \
   ```

1. Create a file called `start-inference.json` and add the following code, replacing the following:
   + `asset-id` with the ID of the target asset
   + `action-definition-id` with the ID of the start inference action
   + `Offset` with the amount of buffer to use
   + `Frequency` with how often data is uploaded

   ```
   {
     "targetResource": {
       "assetId": "asset-id"
     },
     "actionDefinitionId": "action-definition-Id",
     "actionPayload":{ "stringValue": "{\"l4EInference\": {\"inferenceMode\":\"START\",\"dataDelayOffsetInMinutes\": Offset, \"dataUploadFrequency\": \"Frequency\"}}"
   }}
   ```

1. Run the following command to start inference:

   ```
   aws iotsitewise execute-action --cli-input-json file://start-inference.json 
   ```

**To stop inference**

1. Run the following command to find the `assetModelCompositeModelId` under `assetModelCompositeModelSummaries`. Replace *`asset-model-id`* with the ID of the asset model that you created in [Update an asset model, component model, or interface (AWS CLI)](update-asset-models.md#update-asset-model-cli).

   ```
   aws iotsitewise describe-asset-model \
     --asset-model-id asset-model-id \
   ```

1. Run the following command to find the `actionDefinitionId` of the `Inference` action. Replace *`asset-model-id`* with the ID used in previous step and replace *`asset-model-composite-model-id`* with the ID returned in the previous step.

   ```
   aws iotsitewise describe-asset-model-composite-model \
     --asset-model-id asset-model-id \
     --asset-model-composite-model-id asset-model-composite-model-id \
   ```

1. Create a file called `stop-inference.json` and add the following code, replacing the following:
   + `asset-id` with the ID of the target asset
   + `action-definition-id` with the ID of the start inference action

   ```
   {
     "targetResource": {
       "assetId": "asset-id"
     },
     "actionDefinitionId": "action-definition-Id",
     "actionPayload":{ "stringValue": "{\"l4EInference\":{\"inferenceMode\":\"STOP\"}}"
   }}
   ```

1. Run the following command to stop inference:

   ```
   aws iotsitewise execute-action --cli-input-json file://stop-inference.json 
   ```