

# IoT
<a name="iot-pattern-list"></a>

**Topics**
+ [Extract and query AWS IoT SiteWise metadata attributes in a data lake](extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake.md)
+ [Set up and troubleshoot AWS IoT Greengrass with client devices](set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.md)
+ [More patterns](iot-more-patterns-pattern-list.md)

# Extract and query AWS IoT SiteWise metadata attributes in a data lake
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake"></a>

*Ambarish Dongaonkar, Amazon Web Services*

## Summary
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-summary"></a>

AWS IoT SiteWise uses asset models and hierarchies to represent your industrial equipment, processes, and facilities. Each model or asset can have multiple attributes that are specific to your environment. Example metadata attributes include the site or physical location of the asset, plant details, and equipment identifiers. These attribute values complement asset measurement data to maximize the business value. Machine learning (ML) can provide additional insights into this metadata and streamline engineering tasks.

However, metadata attributes can’t be queried directly from the AWS IoT SiteWise service. To make the attributes queryable, you must extract and ingest them into a data lake. This pattern uses a Python script to extract the attributes for all AWS IoT SiteWise assets and ingest them into a data lake in an Amazon Simple Storage Service (Amazon S3) bucket. When you have completed this process, you can use SQL queries in Amazon Athena to access the AWS IoT SiteWise metadata attributes and other datasets, such as measurement datasets. The metadata attribute information is also useful when working with AWS IoT SiteWise monitors or dashboards. You can also build an [Amazon Quick Sight dashboard](https://docs.aws.amazon.com/quicksuite/latest/userguide/quick-bi.html) by using the extracted attributes in the Amazon S3 bucket.

The pattern has reference code, and you can you can implement the code by using the best compute services for your use case, such as AWS Lambda or AWS Glue.

## Prerequisites and limitations
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-prereqs"></a>

**Prerequisites **
+ An active AWS account.
+ Permissions to set up AWS Lambda functions or AWS Glue jobs.
+ An Amazon S3 bucket.
+ The asset models and hierarchies are set up in AWS IoT SiteWise. For more information, see [Creating asset models](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/create-asset-models.html) in the AWS IoT SiteWise documentation.

## Architecture
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-architecture"></a>

You can use a Lambda function or an AWS Glue job to complete this process. We recommend using Lambda if you have less than 100 models and each model has an average of 15 or fewer attributes. For all other use cases, we recommend using AWS Glue.

The solution architecture and workflow are shown in the following diagram.

![\[Architecture diagram showing the extraction and query process described.\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/22b59ff7-3df3-4a5b-9973-d43967bd58fd/images/fa3d80bf-df9a-49fe-971c-a055339b2cd2.png)


1. The scheduled AWS Glue job or Lambda function runs. It extracts the asset metadata attributes from AWS IoT SiteWise and ingests them into an Amazon S3 bucket.

1. An AWS Glue crawler crawls the extracted data in the Amazon S3 bucket and creates tables in an AWS Glue Data Catalog.

1. Using standard SQL, Amazon Athena queries the tables in the AWS Glue Data Catalog.

**Automation and scale**

You can schedule the Lambda function or AWS Glue job to run daily or weekly, according to the update frequency of your AWS IoT SiteWise asset configurations.

There is no limit to the number of AWS IoT SiteWise assets that the sample code can process, but a large number of assets can increase the amount of time required to complete the process.

## Tools
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-tools"></a>
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) is an interactive query service that helps you analyze data directly in Amazon S3 by using standard SQL.
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) is a fully managed extract, transform, and load (ETL) service. It helps you reliably categorize, clean, enrich, and move data between data stores and data streams.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) helps you securely manage access to your AWS resources by controlling who is authenticated and authorized to use them.
+ [AWS IoT SiteWise](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/what-is-sitewise.html) helps you collect, model, analyze, and visualize data from industrial equipment at scale.
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) is a compute service that helps you run code without needing to provision or manage servers. It runs your code only when needed and scales automatically, so you pay only for the compute time that you use.
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) is a cloud-based object storage service that helps you store, protect, and retrieve any amount of data.
+ [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) is a software development kit that helps you integrate your Python application, library, or script with AWS services.

## Epics
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-epics"></a>

### Set up the job or function
<a name="set-up-the-job-or-function"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Configure permissions in IAM. | In the IAM console, grant permissions to the IAM role assumed by the Lambda function or AWS Glue job to do the following:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake.html)For more information, see [Creating a role for an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html#roles-creatingrole-service-console) in the IAM documentation. | General AWS | 
| Create the Lambda function or AWS Glue job. | If you are using Lambda, create a new Lambda function. For **Runtime**, choose **Python**. For more information, see [Building Lambda functions with Python](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html) in the Lambda documentation.If you are using AWS Glue, create a new Python shell job in the AWS Glue console. For more information, see [Adding Python shell jobs](https://docs.aws.amazon.com/glue/latest/dg/add-job-python.html#create-job-python-properties) in the AWS Glue documentation.  | General AWS | 
| Update the Lambda function or AWS Glue job. | Modify the new Lambda function or AWS Glue job, and enter the code sample in the [Additional information](#extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-additional) section. Modify the code as needed for your use case. For more information, see [Edit code using the console editor](https://docs.aws.amazon.com/lambda/latest/dg/foundation-console.html#code-editor) in the Lambda documentation and see [Working with scripts](https://docs.aws.amazon.com/glue/latest/dg/console-edit-script.html) in theAWS Glue documentation. | General AWS | 

### Run the job or function
<a name="run-the-job-or-function"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Run the Lambda function or AWS Glue job. | Run the Lambda function or AWS Glue job. For more information, see [Invoke the Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html#get-started-invoke-manually) in the Lambda documentation or see [Starting jobs using triggers](https://docs.aws.amazon.com/glue/latest/dg/trigger-job.html) in the AWS Glue documentation. This extracts the metadata attributes for the assets and models in the AWS IoT SiteWise hierarchy and stores them in the specified Amazon S3 bucket. | General AWS | 
| Set up an AWS Glue crawler. | Set up an AWS Glue crawler with the necessary format classifier for a CSV-formatted file. Use the Amazon S3 bucket and prefix details used in the Lambda function or AWS Glue job. For more information, see [Defining crawlers](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html) in the AWS Glue documentation. | General AWS | 
| Run the AWS Glue crawler. | Run the crawler to process the data file created by the Lambda function or AWS Glue job. The crawler creates a table in the specified AWS Glue Data Catalog. For more information, see or [Starting crawlers using triggers](https://docs.aws.amazon.com/glue/latest/dg/trigger-job.html) in the AWS Glue documentation. | General AWS | 
| Query the metadata attributes. | Using Amazon Athena, use standard SQL to query the AWS Glue Data Catalog as needed for your use case. You can join the metadata attribute table with other databases and tables. For more information, see [Getting Started](https://docs.aws.amazon.com/athena/latest/ug/getting-started.html) in the Amazon Athena documentation. | General AWS | 

## Related resources
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-resources"></a>
+ [Amazon Athena documentation](https://docs.aws.amazon.com/athena/latest/ug/what-is.html)
+ [AWS Glue documentation](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html)
+ [AWS IoT SiteWise API reference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/index.html)
+ [AWS IoT SiteWise user guide](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/what-is-sitewise.html)
  + [Getting started](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/getting-started.html)
  + [Modeling industrial assets](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/industrial-asset-models.html)
  + [Defining relationships between asset models (hierarchies)](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/asset-hierarchies.html)
  + [Associating and disassociating assets](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/add-associated-assets.html)
  + [Creating the AWS IoT SiteWise demo](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/getting-started-demo.html#create-getting-started-demo)
+ [IOTSiteWise](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/iotsitewise.html) (SDK for Python documentation)
+ [Lambda documentation](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)

## Additional information
<a name="extract-and-query-aws-iot-sitewise-metadata-attributes-in-a-data-lake-additional"></a>

**Code**

The sample code provided is for reference, and you can customize this code as needed for your use case.

```
# Following code can be used in an AWS Lambda function or in an AWS Glue Python shell job. 
# IAM roles used for this job need read access to the AWS IoT SiteWise service and write access to the S3 bucket.
sw_client = boto3.client('iotsitewise')
s3_client = boto3.client('s3')
output = io.StringIO()
 
attribute_list=[]
bucket = '{3_bucket name}'
prefix = '{s3_bucket prefix}'
output.write("model_id,model_name,asset_id,asset_name,attribuet_id,attribute_name,attribute_value\n")
     
m_resp = sw_client.list_asset_models()
for m_rec in m_resp['assetModelSummaries']:
     model_id = m_rec['id']
     model_name = m_rec['name']
 
     attribute_list.clear()
     dam_response = sw_client.describe_asset_model(assetModelId=model_id)
     for rec in dam_response['assetModelProperties']:
         if 'attribute' in rec['type']:
            attribute_list.append(rec['name'])
     
     response = sw_client.list_assets(assetModelId=model_id, filter='ALL')
     for asset in response['assetSummaries']:
         asset_id = asset['id']
         asset_name = asset['name']
         resp = sw_client.describe_asset(assetId=asset_id)
         for rec in resp['assetProperties']:
            if rec['name'] in attribute_list:
                p_resp = sw_client.get_asset_property_value(assetId=asset_id, propertyId=rec['id'])
                if 'propertyValue' in p_resp:
                    if p_resp['propertyValue']['value']:
                        if 'stringValue' in p_resp['propertyValue']['value']:
                             output.write(model_id + "," + model_name + "," + asset_id + "," + asset_name + "," + rec['id'] + "," + rec['name'] + "," + str(p_resp['propertyValue']['value']['stringValue']) + "\n")                             
                        if 'doubleValue' in p_resp['propertyValue']['value']:
                             output.write(model_id + "," + model_name + "," + asset_id + "," + asset_name + "," + rec['id'] + "," + rec['name'] + "," + str(p_resp['propertyValue']['value']['doubleValue']) + "\n")
                        if 'integerValue' in p_resp['propertyValue']['value']:
                             output.write(model_id + "," + model_name + "," + asset_id + "," + asset_name + "," + rec['id'] + "," + rec['name'] + "," + str(p_resp['propertyValue']['value']['integerValue']) + "\n")
                         if 'booleanValue' in p_resp['propertyValue']['value']:
                             output.write(model_id + "," + model_name + "," + asset_id + "," + asset_name + "," + rec['id'] + "," + rec['name'] + "," + str(p_resp['propertyValue']['value']['booleanValue']) + "\n")
 
output.seek(0)
s3_client.put_object(Bucket=bucket, Key= prefix + '/data.csv', Body=output.getvalue())
output.close()
```

# Set up and troubleshoot AWS IoT Greengrass with client devices
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices"></a>

*Marouane Sefiani and Akalanka De Silva, Amazon Web Services*

## Summary
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-summary"></a>

AWS IoT Greengrass is an open-source edge runtime and cloud service for building, deploying, and managing Internet of Things (IoT) software on edge devices. Use cases for AWS IoT Greengrass include:
+ Smart homes where an AWS IoT Greengrass gateway is used as a hub for home automation
+ Smart factories where AWS IoT Greengrass can facilitate ingestion and local processing of data from the shop floor

AWS IoT Greengrass can act as a secure, authenticated, MQTT connection endpoint for other edge devices (also known as *client devices*), which otherwise would typically connect directly to AWS IoT Core. This capability is useful when client devices do not have direct network access to the AWS IoT Core endpoint.

You can set up AWS IoT Greengrass for use with client devices for the following use cases:
+ For client devices to send data to AWS IoT Greengrass
+ For AWS IoT Greengrass to forward data to AWS IoT Core
+ To take advantage of advanced AWS IoT Core rules engine features

These capabilities require installing and configuring the following components on the AWS IoT Greengrass device:
+ MQTT broker
+ MQTT bridge
+ Client device authentication
+ IP detector

In addition, published messages from client devices must be in JSON format or [Protocol Buffers (protobuf)](https://protobuf.dev/) format.

This pattern describes how to install and configure these required components, and provides troubleshooting tips and best practices.

## Prerequisites and limitations
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-prereqs"></a>

**Prerequisites**
+ An active AWS account
+ [AWS Command Line Interface (AWS CLI) version 2](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)
+ Two client devices running Python 3.7 or later
+ One core device running Java Runtime Environment (JRE) version 8 or later, and [Amazon Corretto 11](https://aws.amazon.com/corretto/) or [OpenJDK 11](https://openjdk.java.net/)

**Limitations**
+ You must choose an AWS Region where AWS IoT Core is available. For the current list of Regions for AWS IoT Core, see [AWS Services by Region](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).
+ The core device must have at least 172 MB RAM and 512 MB of disk space.

## Architecture
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-architecture"></a>

The following diagram shows the solution architecture for this pattern.

![\[Solution architecture for setting up AWS IoT Greengrass with client devices\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/a340e6ea-dcfa-42a4-a370-c16ee08a6842/images/0656c5ae-d979-4cf7-be92-a46fa81cab0d.png)


The architecture includes:
+ Two client devices. Each device contains a private key, a device certificate, and a root certificate authority (CA) certificate. The AWS IoT Device SDK, which contains an MQTT client, is also installed on each client device.
+ A core device that has AWS IoT Greengrass deployed with the following components:
  + MQTT broker
  + MQTT bridge
  + Client device authentication
  + IP detector

This architecture supports the following scenarios:
+ Client devices can use their MQTT client to communicate with one another through the core device’s MQTT broker.
+ Client devices can also communicate with AWS IoT Core in the cloud through the core device’s MQTT broker and the MQTT bridge.
+ AWS IoT Core in the cloud can send messages to client devices through the MQTT test client and the core device’s MQTT bridge and MQTT broker.

For more information about the communications between client devices and the core device, see the [Additional information](#set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-additional) section.

## Tools
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-tools"></a>

**AWS services**
+ [AWS IoT Greengrass](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html) is an open source Internet of Things (IoT) edge runtime and cloud service that helps you build, deploy, and manage IoT applications on your devices.
+ [AWS IoT Core](https://docs.aws.amazon.com/iot/latest/developerguide/what-is-aws-iot.html) provides secure, bidirectional communication for internet-connected devices to connect to the AWS Cloud.
+ [AWS IoT Device SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) is a software development kit that includes open-source libraries, developer guides with samples, and porting guides so that you can build innovative IoT products or solutions on your choice of hardware platforms.
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) helps you securely manage access to your AWS resources by controlling who is authenticated and authorized to use them.

## Best practices
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-best-practices"></a>
+ The payload of the messages from client devices should be in either JSON or Protobuf format in order to take advantage of the advanced features of the AWS IoT Core rules engine, such as transformation and conditional actions.
+ Configure the MQTT bridge to allow bidirectional communication.
+ Configure and deploy the IP detector component in AWS IoT Greengrass to ensure that the core device’s IP addresses are included in the subject alternative name (SAN) field of the MQTT broker certificate.

## Epics
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-epics"></a>

### Set up the core device
<a name="set-up-the-core-device"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Set up AWS IoT Greengrass on your core device. | Install the AWS IoT Greengrass Core software by following the instructions in the [developer guide](https://docs.aws.amazon.com/greengrass/v2/developerguide/install-greengrass-core-v2.html). | AWS IoT Greengrass | 
| Check the status of your installation. | Use the following command to check the status of the AWS IoT Greengrass service on your core device:<pre>sudo systemctl status greengrass.service</pre>The expected output of the command is:<pre>Launched Nucleus successfully</pre> | General AWS | 
| Set up an IAM policy and attach it to the Greengrass service role. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html) | General AWS | 
| Configure and deploy required components in the AWS IoT Greengrass core device. | Configure and deploy the following components:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html) | AWS IoT Greengrass | 
| Confirm that the MQTT bridge allows bidirectional communication. | To relay MQTT messages between client devices and AWS IoT Core, configure and deploy the MQTT bridge component and specify the topics to relay. Here’s an example:<pre>{<br />  "mqttTopicMapping": {<br />    "ClientDevicesToCloud": {<br />      "topic": "dt/#",<br />      "source": "LocalMqtt",<br />      "target": "IotCore"<br />    },<br />    "CloudToClientDevices": {<br />      "topic": "cmd/#",<br />      "source": "IotCore",<br />      "target": "LocalMqtt"<br />    }<br />  }<br />}</pre> | AWS IoT Greengrass | 
| Confirm that the auth component allows client devices to connect and publish or subscribe to topics.  | The following `aws.greengrass.clientdevices.Auth` configuration allows all client devices to connect, publish messages, and subscribe to all topics.<pre>{<br />  "deviceGroups": {<br />    "formatVersion": "2021-03-05",<br />    "definitions": {<br />      "MyPermissiveDeviceGroup": {<br />        "selectionRule": "thingName: *",<br />        "policyName": "MyPermissivePolicy"<br />      }<br />    },<br />    "policies": {<br />      "MyPermissivePolicy": {<br />        "AllowAll": {<br />          "statementDescription": "Allow client devices to perform all actions.",<br />          "operations": [<br />            "*"<br />          ],<br />          "resources": [<br />            "*"<br />          ]<br />        }<br />      }<br />    }<br />  }<br />}</pre> | AWS IoT Greengrass | 

### Set up client devices
<a name="set-up-client-devices"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Install the AWS IoT Device SDK. | Install the AWS IoT Device SDK on client devices. For a full list of supported languages and the associated SDKs, see the [AWS IoT Core documentation](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html).For example, the AWS IoT Device SDK for Python SDK is [located on GitHub](https://github.com/aws/aws-iot-device-sdk-python-v2). To install this SDK:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html)Alternatively, you can install the SDK from the source repository:<pre># Create a workspace directory to hold all the SDK files<br />mkdir sdk-workspace<br />cd sdk-workspace<br /># Clone the repository<br />git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git<br /># Install using Pip (use 'python' instead of 'python3' on Windows)<br />python3 -m pip install ./aws-iot-device-sdk-python-v2</pre> | General AWS IoT | 
| Create a thing. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html) | AWS IoT Core | 
| Download the CA certificate from the Greengrass core device. | If you expect the Greengrass core device to work in offline environments, you have to make the Greengrass core CA certificate available to the client device so it can verify the MQTT broker’s certificate (which is issued by the Greengrass core CA). Therefore, it is important to obtain a copy of this certificate. Use one of the following approaches to download the CA certificate:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html) | General AWS | 
| Copy credentials in the client devices. | Copy the Greengrass core CA certificate, the device certificate, and the private key in the client devices. | General AWS | 
| Associate client devices with the core device. | Associate client devices with a core device so that they can discover the core device. The client devices can then use the [Greengrass discovery API](https://docs.aws.amazon.com/greengrass/v2/developerguide/greengrass-discover-api.html) to retrieve connectivity information and certificates for their associated core devices. For more information, see [Associate client devices](https://docs.aws.amazon.com/greengrass/v2/developerguide/associate-client-devices.html) in the AWS IoT Greengrass documentation.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html)The client devices that you associated can now use the Greengrass discovery API to discover this core device. | AWS IoT Greengrass | 

### Send and receive data
<a name="send-and-receive-data"></a>


| Task | Description | Skills required | 
| --- | --- | --- | 
| Send data from one client device to another client device. | Use the MQTT client in your device to publish a message on the `dt/client1/sensor` topic. | General AWS | 
| Send data from the client device to AWS IoT Core. | Use the MQTT client in your device to publish a message on the `dt/client1/sensor` topic.In the MQTT test client, subscribe to the topic that the device is sending messages on, or subscribe to **\$1** for all topics (see [details](https://docs.aws.amazon.com/iot/latest/developerguide/view-mqtt-messages.html)). | General AWS | 
| Send messages from AWS IoT Core to client devices. | On the MQTT test client page, in the **Publish to a topic** tab, in the **Topic name** field, enter the topic name of your message. In this example, use `cmd/client1` for the topic. | General AWS | 

## Troubleshooting
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-troubleshooting"></a>


| Issue | Solution | 
| --- | --- | 
| **Unable to verify server certificate error** | This error occurs when the MQTT client cannot verify the certificate that’s presented by the MQTT broker during the TLS handshake. The most common reason is that the MQTT client doesn’t have the CA certificate. Follow these steps to make sure that the CA certificate is provided to the MQTT client.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices.html) | 
| **Unable to verify server name error** | This errors occurs when the MQTT client can’t verify that it’s connecting to the correct server. The most common reason is that the IP address of the Greengrass device isn’t listed in the SAN field of the certificate.Follow the instructions in the previous solution to obtain the MQTT broker certificate and verify that the SAN field contains the IP address of the AWS IoT Greengrass device, as explained in the [Additional information](#set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-additional) section. If not, confirm that the IP detector component is installed correctly and restart the core device. | 
| **Unable to verify server name only when connecting from an embedded client device** | Mbed TLS, which is a popular TLS library used in embedded devices, currently supports DNS name verification only in the SAN field of the certificate, as shown in the Mbed TLS library code. Because the core device doesn’t have its own domain name and depends on the IP address, TLS clients that use Mbed TLS will fail the server name verification during the TLS handshake, causing a connection failure. We recommend that you add the SAN IP address verification to your Mbed TLS library at the [x509\$1crt\$1check\$1san function](https://github.com/Mbed-TLS/mbedtls/blob/6a327a5fdc2786cb50b4dbe5e3a75884a1f8435a/library/x509_crt.c#L2548). | 

## Related resources
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-resources"></a>
+ [AWS IoT Greengrass documentation](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html)
+ [AWS IoT Core documentation](https://docs.aws.amazon.com/iot/latest/developerguide/what-is-aws-iot.html)
+ [MQTT broker component](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-broker-moquette-component.html)
+ [MQTT bridge component](https://docs.aws.amazon.com/greengrass/v2/developerguide/mqtt-bridge-component.html)
+ [Client device auth component](https://docs.aws.amazon.com/greengrass/v2/developerguide/client-device-auth-component.html)
+ [IP detector component](https://docs.aws.amazon.com/greengrass/v2/developerguide/ip-detector-component.html)
+ [AWS IoT Device SDK](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html)s
+ [Implementing Local Client Devices with AWS IoT Greengrass](https://aws.amazon.com/blogs/iot/implementing-local-client-devices-with-aws-iot-greengrass/) (AWS blog post)
+ [RFC 5280 – Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile](https://www.rfc-editor.org/rfc/rfc5280)

## Additional information
<a name="set-up-and-troubleshoot-aws-iot-greengrass-with-client-devices-additional"></a>

This section provides additional information about the communications between the client devices and the core device.

The MQTT broker listens on port 8883 in the core device for a TLS client connection attempt. The following illustration shows an example MQTT broker’s server certificate.

![\[Example of MQTT broker server certificate\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/a340e6ea-dcfa-42a4-a370-c16ee08a6842/images/b2c324a1-60cd-4194-80e7-e5184662146a.png)


The example certificate displays the following details:
+ The certificate is issued by the AWS IoT Greengrass Core CA, which is local and specific to the core device; that is, it acts as a local CA.
+ This certificate is automatically rotated every week by the client auth component as shown in the following illustration. You can set this interval in the client auth component configuration.

![\[Rotating the MQTT broker's server certificate\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/a340e6ea-dcfa-42a4-a370-c16ee08a6842/images/65bcdc5c-a71c-4f52-adcd-21910fabfc2a.png)

+ The subject alternative name (SAN) plays a critical role in the server name verification on the TLS client end. It helps the TLS client ensure that it connects to the correct server and helps avoid man-in-the-middle attacks during TLS session setup. In the example certificate, the SAN field indicates that this server is listening on localhost (the local Unix domain socket), and the network interface has the IP address 192.168.1.12.

The TLS client uses the SAN field in the certificate to verify that it’s connecting to a legitimate server during server verification. In contrast, during a typical TLS handshake between an HTTP server and a browser, the domain name in the common name (CN) field or SAN field is used to cross-check the domain that the browser is actually connecting to during the server verification process. If the core device doesn’t have a domain name, the IP address included in the SAN field serves the same purpose. For more information, see the [Subject Alternative Name section](https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6) of *RFC 5280 – Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile*.

Th IP detector component in AWS IoT Greengrass ensures that the correct IP addresses are included in the SAN field of the certificate.

The certificate in the example is signed by the AWS IoT Greengrass device acting as a local CA. The TLS client (MQTT client) isn’t aware of this CA, so we must provide a CA certificate that looks like the following.

![\[Example CA certificate\]](http://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/images/pattern-img/a340e6ea-dcfa-42a4-a370-c16ee08a6842/images/b08b3bcb-9e12-4f5a-9204-cf65ea32902f.png)


# More patterns
<a name="iot-more-patterns-pattern-list"></a>

**Topics**
+ [Cost-effectively ingest IoT data directly into Amazon S3 using AWS IoT Greengrass](cost-effectively-ingest-iot-data-directly-into-amazon-s3-using-aws-iot-greengrass.md)
+ [Deploy agentic systems on Amazon Bedrock with the CrewAI framework by using Terraform](deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.md)
+ [Deploy containerized applications on AWS IoT Greengrass V2 running as a Docker container](deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.md)