# AWS IoT Core

Easily and securely connect devices to [**AWS IoT Core**](https://aws.amazon.com/iot-core/). AWS IoT Core uses MQTT to transmit and receive messages, a lightweight IoT messaging protocol. This tutorial explain how to set up AWS IoT Core and start sending IoT data from a Raspberry Pi connected over cellular.

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FAKlxcWhjujLWLbopxgYa%2FAWS%20Monogoto%202.png?alt=media&#x26;token=8e8d7a07-9c41-498f-ae8a-9cbc4a0fa1cc" alt=""><figcaption></figcaption></figure>

### Quick Navigation

* [Create a Thing in AWS](#create-a-thing-in-aws)
* [Connect your device to AWS IoT Core](#connect-your-device-to-aws-iot-core)
* [Create your python script](#create-your-python-script)

### Prerequisites

* [AWS account](https://console.aws.amazon.com/)
* Monogoto SIM
* Raspberry Pi 3 or 4

## Create a Thing in AWS

Start by visiting the [**AWS portal**](https://console.aws.amazon.com/console/home)

Search for the **IoT Core** service

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2Fflc4YfToqVzQZVZ8sKKO%2FAWS%20IoT%20Core.png?alt=media&#x26;token=6d0858fc-5116-4f6c-8b69-204812770f7b" alt=""><figcaption></figcaption></figure>

In the left side menu, navigate to **Manage > All devices > Things**&#x20;

Click the button **Create Things** to create your digital Thing.

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2F5yknY5edejUXDy1OhaM2%2Fcreate%20thing.png?alt=media&#x26;token=582f34da-7472-4d42-ad4e-d1557bcd9544" alt=""><figcaption></figcaption></figure>

**Name your thing**, e.g. <mark style="color:red;">`mqtt-thing`</mark>

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FYT2MIef3gVitBNHJU9Qo%2Fcreate%20thing%203.png?alt=media&#x26;token=f6437ea4-e385-44b8-88e0-4cff5d42b5a3" alt=""><figcaption></figcaption></figure>

Select **Auto-generate a new certificate**

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FJWfbCIV0BQfu4Lvqkev5%2Fcreate%20thing%204.png?alt=media&#x26;token=d979a778-baa4-4a42-9505-956f54ae6012" alt=""><figcaption></figcaption></figure>

Attach an existing policy, or create a new one by clicking “**Create policy**”

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2Fm2cYdNRsIALX2uJpeOc7%2Fcreate%20thing%205.png?alt=media&#x26;token=a713a0a8-365d-491d-8921-5d4bd23b9d3e" alt=""><figcaption></figcaption></figure>

When creating a new policy, add 4 statements allowing the Thing to **Connect**, **Publish**, **Receive** and **Subscribe**. Under Policy resource, add an asterisk <mark style="color:red;">`*`</mark> to allow all topic names to connect to AWS IoT Core.&#x20;

```
Policy effect    Policy action    Policy resource
Allow            iot:Connect      *  
Allow            iot:Publish      *   
Allow            iot:Receive      *  
Allow            iot:Subscribe    * 
```

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FcAynuAWYTfMsy89xEQ1C%2Fcreate%20thing%206.png?alt=media&#x26;token=ecf1cd91-5fa3-4a03-8332-d08ab3c0e3a8" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
When using AWS IoT Core in production, restrict the Policy resource to specific topics to increase the security of your application.
{% endhint %}

#### **Download all keys and CA files**

Download and store the **Device certificate**, **Private key file** and **Amazon Root CA 1** in a directory called <mark style="color:red;">`certs`</mark>. Make sure to name the files properly as described in the table below.

| **Device certificate** | device.pem.crt    |
| ---------------------- | ----------------- |
| **Private key file**   | private.pem.key   |
| **Amazon Root CA 1**   | AmazonRootCA1.pem |

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FJRaBy09wwzb51qOJRyfW%2Fcreate%20thing%207.png?alt=media&#x26;token=7708ac87-324c-4fa0-9482-ecbabb387717" alt=""><figcaption></figcaption></figure>

## Connect your device to AWS IoT Core

*This section explains how to run a python scrip on a Raspberry Pi, connected to Monogoto. For more information on how to connect the Raspberry Pi to Monogoto, see* [*this tutorial*](https://docs.monogoto.io/getting-started/general-device-configurations/raspberry-pi)*.*

**Access the Raspberry Pi** over ssh or by connecting a screen and keyboard

**Install the required libraries**

Before you install an AWS IoT Device SDK, run these commands in a terminal window on your Linux device to install the required libraries.

```bash
sudo apt-get install cmake
```

```bash
sudo apt-get install libssl-dev
```

Install the **AWS IoT Device SDK** for Python and download the sample apps to your device.

```bash
cd ~
pip3 install awsiotsdk
pip3 install AWSIoTPythonSDK
```

**Add certificates to the Raspberry Pi**

Add the **Device certificate**, **Private key file** and **Amazon Root CA 1** to a folder called <mark style="color:red;">`certs`</mark>.

```
cd ~
mkdir certs
```

{% hint style="info" %}
If you downloaded the certificates to a different machine, move the certificates to the RPI using the below command: <mark style="color:red;">`scp -r ~/certspi@<ip address>:~/certs`</mark>
{% endhint %}

## Create your python script

#### Create a new file called <mark style="color:red;">`publish.py`</mark> containing the below script &#x20;

{% code lineNumbers="true" %}

```python
# publish.py

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

import time as t
import json
import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT

# Define ENDPOINT, CLIENT_ID, PATH_TO_CERTIFICATE, PATH_TO_PRIVATE_KEY, PATH_TO_AMAZON_ROOT_CA_1, MESSAGE, TOPIC, and RANGE
ENDPOINT = "<your AWS endpoint>"
CLIENT_ID = "basicPubSub"
PATH_TO_CERTIFICATE = "/home/pi/certs/device.pem.crt"
PATH_TO_PRIVATE_KEY = "/home/pi/certs/private.pem.key"
PATH_TO_AMAZON_ROOT_CA_1 = "/home/pi/certs/AmazonRootCA1.pem"

MESSAGE = "hello world"
TOPIC = "device/RPI"
RANGE = 3

myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient(CLIENT_ID)
myAWSIoTMQTTClient.configureEndpoint(ENDPOINT, 8883)
myAWSIoTMQTTClient.configureCredentials(PATH_TO_AMAZON_ROOT_CA_1, PATH_TO_PRIVATE_KEY, PATH_TO_CERTIFICATE)

myAWSIoTMQTTClient.connect()
print('Begin Publish')
for i in range (RANGE):
    data = "{} [{}]".format(MESSAGE, i+1)
    message = {"message" : data}
    myAWSIoTMQTTClient.publish(TOPIC, json.dumps(message), 1) 
    print("Published: '" + json.dumps(message) + "' to the topic: " + TOPIC)
    t.sleep(0.1)
print('Publish End')
myAWSIoTMQTTClient.disconnect()

```

{% endcode %}

Replace <mark style="color:red;">`<your AWS endpoint>`</mark> with your **AWS endpoint** to the <mark style="color:red;">`publish.py`</mark> file (line 11)

{% hint style="info" %}
**To find your AWS endpoint**, go to the [AWS IoT console](https://console.aws.amazon.com/iot/home), near the bottom of the navigation pane, choose **Settings**.

In the **Settings** page you will find the **Endpoint**, which is unique to your AWS account and looks something like: <mark style="color:red;">`abcdef1234567-ats.iot.eu-west-1.amazonaws.com`</mark>.
{% endhint %}

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FQSWGwMvHY4diHseQmqEh%2Fendpoint%20highlight%202.png?alt=media&#x26;token=92032a49-67d6-4a7a-b9df-a5c95ff26e50" alt=""><figcaption></figcaption></figure>

In the AWS IoT Portal, open the **MQTT test client** and subscribe to the topic **device/RPI**

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2FglefMvamPg5UMUWIDIxz%2Fsubscribe.png?alt=media&#x26;token=d2feb36a-63fe-44bf-bdd6-d061f4e848e2" alt=""><figcaption></figcaption></figure>

**Go back to your Raspberry Pi** and run the <mark style="color:red;">`publish.py`</mark> script using the command:

```bash
python3 publish.py
```

Expected response

```bash
Begin Publish
Published: '{"message": "hello world [1]"}' to the topic: device/data
Published: '{"message": "hello world [2]"}' to the topic: device/data
Published: '{"message": "hello world [3]"}' to the topic: device/data
Publish End
```

When looking at the MQTT test client in AWS IoT Core, you can see the messages:

<figure><img src="https://3922449203-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0mPxGpottOEfcucXOR%2Fuploads%2F2FbtinOdxzbx56BlAQtk%2Fsubscribe%20data.png?alt=media&#x26;token=8dd566b1-5c84-44e9-a23d-f894bf528fab" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
**Congratulations!** I’ve successfully sent data from a Raspberry Pi connected to Monogoto, to AWS IoT Core using the MQTT protocol.
{% endhint %}

### Next steps

* **Trigger actions using Lambdas** - [learn more](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.html#iot-func-aws-lambda)
* **Store data in DynamoDB** - [learn more](https://docs.aws.amazon.com/iot/latest/developerguide/iot-ddb-rule.html)<br>
