

# Explore AWS IoT Core in hands-on tutorials
Advanced connect tutorial

In this tutorial, you'll install the software and create the AWS IoT resources necessary to connect a device to AWS IoT Core so that it can send and receive MQTT messages with AWS IoT Core. You'll see the messages in the MQTT client in the AWS IoT console.

You can expect to spend 20-30 minutes on this tutorial. If you are using an IoT device or a Raspberry Pi, this tutorial might take longer if, for example, you need to install the operating system and configure the device.

![\[Getting started with AWS IoT Core page.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/iot-getting-started.png)


This tutorial is best for developers who want to get started with AWS IoT Core so they can continue to explore more advanced features, such as the [rules engine](https://docs.aws.amazon.com//iot/latest/developerguide/iot-rules.html) and [shadows](https://docs.aws.amazon.com//iot/latest/developerguide/iot-device-shadows.html). This tutorial prepares you to continue learning about AWS IoT Core and how it interacts with other AWS services by explaining the steps in greater detail than [the quick start tutorial](iot-quick-start.md). If you are looking for just a quick, *Hello World*, experience, try the [Try the AWS IoT Core quick connect tutorial](iot-quick-start.md).

After setting up your AWS account and AWS IoT console, you'll follow these steps to see how to connect a device and have it send messages to AWS IoT Core.

**Next steps**
+ [Choose which device option is the best for you](#choosing-a-gs-system)
+ [Create AWS IoT resources](create-iot-resources.md) if you are not going to create a virtual device with Amazon EC2
+ [Configure your device](configure-device.md)
+ [View MQTT messages with the AWS IoT MQTT client](view-mqtt-messages.md)

For more information about AWS IoT Core, see [What Is AWS IoT Core](what-is-aws-iot.md)?

## Which device option is best for you?


If you're not sure which option to pick, use the following list of each option's advantages and disadvantages to help you decide which one is best for you.


| Option | This might be a good option if: | This might not be a good option if: | 
| --- | --- | --- | 
| [Create a virtual device with Amazon EC2](creating-a-virtual-thing.md) |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs-first-thing.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs-first-thing.html)  | 
| [Use your Windows or Linux PC or Mac as an AWS IoT device](using-laptop-as-device.md) |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs-first-thing.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs-first-thing.html)  | 
| [Connect a Raspberry Pi or other device](connecting-to-existing-device.md) |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs-first-thing.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs-first-thing.html)  | 

# Create AWS IoT resources


In this tutorial, you'll create the AWS IoT resources that a device requires to connect to AWS IoT Core and exchange messages.

![\[Create AWS IoT resources page.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/iot-gs-create-resources.png)


1. Create an AWS IoT policy document, which will authorize your device to interact with AWS IoT services.

1. Create a thing object in AWS IoT and its X.509 device certificate, and then attach the policy document. The thing object is the virtual representation of your device in the AWS IoT registry. The certificate authenticates your device to AWS IoT Core, and the policy document authorizes your device to interact with AWS IoT.
**Note**  
If you are planning to [Create a virtual device with Amazon EC2](creating-a-virtual-thing.md), you can skip this page and continue to [Configure your device](configure-device.md). You will create these resources when you create your virtual thing.

This tutorial uses the AWS IoT console to create the AWS IoT resources. If your device supports a web browser, it might be easier to run this procedure on the device's web browser because you will be able to download the certificate files directly to your device. If you run this procedure on another computer, you will need to copy the certificate files to your device before they can be used by the sample app.

## Create an AWS IoT policy


Devices use an X.509 certificate to authenticate with AWS IoT Core. The certificate has AWS IoT policies attached to it. These policies determine which AWS IoT operations, such as subscribing or publishing to MQTT topics, the device is permitted to perform. Your device presents its certificate when it connects and sends messages to AWS IoT Core.

Follow the steps to create a policy that allows your device to perform the AWS IoT operations necessary to run the example program. You must create the AWS IoT policy before you can attach it to the device certificate, which you'll create later.

**To create an AWS IoT policy**

1. In the [AWS IoT console](https://console.aws.amazon.com//iot/home), in the left menu, choose **Security** and then choose **Policies**.

1. On the **You don't have a policy yet** page, choose **Create policy**.

   If your account has existing policies, choose **Create policy**.

1. On the **Create policy** page:

   1. In the **Policy properties** section, in the **Policy name** field, enter a name for the policy (for example, **My\$1Iot\$1Policy**). Don't use personally identifiable information in your policy names.

   1. In the **Policy document** section, create the policy statements that grant or deny resources access to AWS IoT Core operations. To create a policy statement that grants all clients to perform ****iot:Connect****, follow these steps:
      + In the **Policy effect** field, choose **Allow**. This allows all clients that have this policy attached to their certificate to perform the action listed in the **Policy action** field.
      + In the **Policy action** field, choose a policy action such as ****iot:Connect****. Policy actions are the actions that your device needs permission to perform when it runs the example program from the Device SDK.
      + In the **Policy resource** field, enter a resource Amazon Resource Name (ARN) or **\$1**. A **\$1** to select any client (device).

      To create the policy statements for ****iot:Receive****, ****iot:Publish****, and ****iot:Subscribe****, choose **Add new statement** and repeat the steps.  
![\[The page to create a policy.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/gs-create-policy-new.png)
**Note**  
In this quick start, the wildcard (\$1) character is used for simplicity. For higher security, you should restrict which clients (devices) can connect and publish messages by specifying a client ARN instead of the wildcard character as the resource. Client ARNs follow this format: `arn:aws:iot:your-region:your-aws-account:client/my-client-id`.   
However, you must first create the resource (such as a client device or thing shadow) before you can assign its ARN to a policy. For more information, see [AWS IoT Core action resources](https://docs.aws.amazon.com//iot/latest/developerguide/iot-action-resources.html).

1. After you've entered the information for your policy, choose **Create**.

For more information, see [How AWS IoT works with IAM](security_iam_service-with-iam.md).

## Create a thing object


Devices connected to AWS IoT Core are represented by *thing objects* in the AWS IoT registry. A *thing object* represents a specific device or logical entity. It can be a physical device or sensor (for example, a light bulb or a light switch on the wall). It can also be a logical entity, like an instance of an application or physical entity that doesn't connect to AWS IoT, but is related to other devices that do (for example, a car that has engine sensors or a control panel).

**To create a thing in the AWS IoT console**

1. In the [AWS IoT console](https://console.aws.amazon.com/iot/home), in the left menu, choose **All devices** and then choose **Things**.

1. On the **Things** page, choose **Create things**.

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

1. On the **Specify thing properties** page, for **Thing name**, enter a name for your thing, such as **MyIotThing**.

   Choose thing names carefully, because you can't change a thing name later.

   To change a thing's name, you must create a new thing, give it the new name, and then delete the old thing.
**Note**  
Do not use personally identifiable information in your thing name. The thing name can appear in unencrypted communications and reports.

1. Keep the rest of the fields on this page empty. Choose **Next**.

1. On the **Configure device certificate - *optional*** page, choose **Auto-generate a new certificate (recommended)**. Choose **Next**.

1. On the **Attach policies to certificate - *optional*** page, select the policy you created in the previous section. In that section, the policy was named, **My\$1Iot\$1Policy**. Choose **Create thing**.

1. On the **Download certificates and keys** page:

   1. Download each of the certificate and key files and save them for later. You'll need to install these files on your device.

      When you save your certificate files, give them the names in the following table. These are the file names used in later examples.  
**Certificate file names**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/create-iot-resources.html)

   1. To download the root CA file for these files, choose the **Download** link of the root CA certificate file that corresponds to the type of data endpoint and cipher suite you're using. In this tutorial, choose **Download** to the right of **RSA 2048 bit key: Amazon Root CA 1** and download the **RSA 2048 bit key: Amazon Root CA 1** certificate file.
**Important**  
You must save the certificate files before you leave this page. After you leave this page in the console, you will no longer have access to the certificate files.  
If you forgot to download the certificate files that you created in this step, you must exit this console screen, go to the list of things in the console, delete the thing object you created, and then restart this procedure from the beginning.

   1.  Choose **Done**.

After you complete this procedure, you should see the new thing object in your list of things.

# Configure your device


This section describes how to configure your device to connect to AWS IoT Core. If you'd like to get started with AWS IoT Core but don't have a device yet, you can create a virtual device by using Amazon EC2 or you can use your Windows PC or Mac as an IoT device.

Select the best device option for you to try AWS IoT Core. Of course, you can try all of them, but try only one at a time. If you're not sure which device option is best for you, read about how to choose [which device option is the best](iot-gs-first-thing.md#choosing-a-gs-system), and then return to this page.

**Device options**
+ [Create a virtual device with Amazon EC2](creating-a-virtual-thing.md)
+ [Use your Windows or Linux PC or Mac as an AWS IoT device](using-laptop-as-device.md)
+ [Connect a Raspberry Pi or other device](connecting-to-existing-device.md)

# Create a virtual device with Amazon EC2


In this tutorial, you'll create an Amazon EC2 instance to serve as your virtual device in the cloud.

To complete this tutorial, you need an AWS account. If you don't have one, complete the steps described in [Set up AWS account](setting-up.md) before you continue.

**Topics**
+ [

## Set up an Amazon EC2 instance
](#set-up-ec2)
+ [

## Install Git, Node.js and configure the AWS CLI
](#install-git-node)
+ [

## Create AWS IoT resources for your virtual device
](#ec2-create-certificate)
+ [

## Install the AWS IoT Device SDK for JavaScript
](#ec2-sdk)
+ [

## Run the sample application
](#ec2-run-app)
+ [

## View messages from the sample app in the AWS IoT console
](#ec2-view-msg)

## Set up an Amazon EC2 instance


The following steps show you how to create an Amazon EC2 instance that will act as your virtual device in place of a physical device.

If this is the first time you've created an Amazon EC2 instance, you might find the instructions in [Get started with Amazon EC2Linux instances](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/EC2_GetStarted.html) to be more helpful.

**To launch an instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. From the console menu on the left, expand **Instances** section and choose **Instances**. From the **Instances** dashboard, choose **Launch instances** on the right to display a list of basic configurations. 

1. In the **Name and tags** section, enter a name for the instance and optionally add tags.

1. In the **Application and OS Images (Amazon Machine Image)** section, choose an AMI template for your instance, such as *Amazon Linux 2 AMI (HVM)*. Notice that this AMI is marked "Free tier eligible."

1. In the **Instance type** section, you can select the hardware configuration of your instance. Select the `t2.micro` type, which is selected by default. Notice that this instance type is eligible for the free tier.

1. In the **Key pair (login)** section, choose a key pair name from the drop-down list or choose **Create a new key pair** to create a new one. When creating a new key pair, make sure you download the private key file and save it in a safe place, because this is your only chance to download and save it. You'll need to provide the name of your key pair when you launch an instance and the corresponding private key each time you connect to the instance.
**Warning**  
Don't choose the **Proceed without a key pair** option. If you launch your instance without a key pair, then you can't connect to it.

1. In the **Network settings** section and the **Configure storage** section, you can keep the default settings. When you are ready, choose **Launch instances**.

1. A confirmation page lets you know that your instance is launching. Choose **View Instances** to close the confirmation page and return to the console.

1. On the **Instances** screen, you can view the status of the launch. It takes a short time for an instance to launch. When you launch an instance, its initial state is `pending`. After the instance starts, its state changes to `running` and it receives a public DNS name. (If the **Public DNS (IPv4)** column is hidden, choose **Show/Hide Columns** (the gear-shaped icon) in the top right corner of the page and then select **Public DNS (IPv4)**.)

1. It can take a few minutes for the instance to be ready so that you can connect to it. Check that your instance has passed its status checks; you can view this information in the **Status Checks** column.

   After your new instance has passed its status checks, continue to the next procedure and connect to it.

**To connect to your instance**

You can connect to an instance using the browser-based client by selecting the instance from the Amazon EC2 console and choosing to connect using Amazon EC2 Instance Connect. Instance Connect handles the permissions and provides a successful connection.

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the left menu, choose **Instances**.

1. Select the instance and choose **Connect**.

1. Choose **Amazon EC2 Instance Connect **, **Connect**.

You should now have an **Amazon EC2 Instance Connect** window that is logged into your new Amazon EC2 instance.

## Install Git, Node.js and configure the AWS CLI


In this section, you'll install Git and Node.js on your Linux instance.

**To install Git**

1. In your **Amazon EC2 Instance Connect** window, update your instance by using the following command.

   ```
   sudo yum update -y
   ```

1. In your **Amazon EC2 Instance Connect** window, install Git by using the following command.

   ```
   sudo yum install git -y
   ```

1. To check if Git has been installed and the current version of Git, run the following command:

   ```
   git --version
   ```

**To install Node.js**

1. In your **Amazon EC2 Instance Connect** window, install node version manager (nvm) by using the following command.

   ```
   curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
   ```

   We will use nvm to install Node.js because nvm can install multiple versions of Node.js and allow you to switch between them. 

1. In your **Amazon EC2 Instance Connect** window, activate nvm by using this command.

   ```
   . ~/.nvm/nvm.sh
   ```

1. In your **Amazon EC2 Instance Connect** window, use nvm to install the latest version of Node.js by using this command.

   ```
   nvm install 16
   ```
**Note**  
This installs the latest LTS release of Node.js.

   Installing Node.js also installs the Node Package Manager (npm) so you can install additional modules as needed.

1. In your **Amazon EC2 Instance Connect** window, test that Node.js is installed and running correctly by using this command.

   ```
   node -e "console.log('Running Node.js ' + process.version)"
   ```

    This tutorial requires Node v10.0 or later. For more information, see [Tutorial: Setting Up Node.js on an Amazon EC2 Instance](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html).

**To configure AWS CLI**

Your Amazon EC2 instance comes preloaded with the AWS CLI. However, you must complete your AWS CLI profile. For more information on how to configure your CLI, see [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html).

1. The following example shows sample values. Replace them with your own values. You can find these values in your [AWS console in your account info under **Security credentials**](https://console.aws.amazon.com//iam/home#/security_credentials).

   In your **Amazon EC2 Instance Connect** window, enter this command:

   ```
   aws configure
   ```

   Then enter the values from your account at the prompts displayed.

   ```
   AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
   AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   Default region name [None]: us-west-2
   Default output format [None]: json
   ```

1. You can test your AWS CLI configuration with this command:

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

   If your AWS CLI is configured correctly, the command should return an endpoint address from your AWS account.

## Create AWS IoT resources for your virtual device


This section describes how to use the AWS CLI to create the thing object and its certificate files directly on the virtual device. This is done directly on the device to avoid the potential complication that might arise from copying them to the device from another computer. In this section, you will create the following resources for your virtual device:
+ A thing object to represent your virtual device in AWS IoT.
+ A certificate to authenticate your virtual device.
+ A policy document to authorize your virtual device to connect to AWS IoT, and to publish, receive, and subscribe to messages.

**To create an AWS IoT thing object in your Linux instance**

Devices connected to AWS IoT are represented by *thing objects* in the AWS IoT registry. A *thing object* represents a specific device or logical entity. In this case, your *thing object* will represent your virtual device, this Amazon EC2 instance.

1. In your **Amazon EC2 Instance Connect** window, run the following command to create your thing object.

   ```
   aws iot create-thing --thing-name "MyIotThing"
   ```

1. The JSON response should look like this:

   ```
   {
       "thingArn": "arn:aws:iot:your-region:your-aws-account:thing/MyIotThing", 
       "thingName": "MyIotThing",
       "thingId": "6cf922a8-d8ea-4136-f3401EXAMPLE"
   }
   ```

**To create and attach AWS IoT keys and certificates in your Linux instance**

The **[create-keys-and-certificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-keys-and-certificate.html)** command creates client certificates signed by the Amazon Root certificate authority. This certificate is used to authenticate the identity of your virtual device.

1. In your **Amazon EC2 Instance Connect** window, create a directory to store your certificate and key files.

   ```
   mkdir ~/certs
   ```

1. In your **Amazon EC2 Instance Connect** window, download a copy of the Amazon certificate authority (CA) certificate by using this command.

   ```
   curl -o ~/certs/Amazon-root-CA-1.pem \
       https://www.amazontrust.com/repository/AmazonRootCA1.pem
   ```

1. In your **Amazon EC2 Instance Connect** window, run the following command to create your private key, public key, and X.509 certificate files. This command also registers and activates the certificate with AWS IoT.

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

   The response looks like the following. Save the `certificateArn` so that you can use it in subsequent commands. You'll need it to attach your certificate to your thing and to attach the policy to the certificate in a later steps.

   ```
   {
       "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/9894ba17925e663f1d29c23af4582b8e3b7619c31f3fbd93adcb51ae54b83dc2",
       "certificateId": "9894ba17925e663f1d29c23af4582b8e3b7619c31f3fbd93adcb51ae54b83dc2",
       "certificatePem": "
   -----BEGIN CERTIFICATE-----
   MIICiTCCEXAMPLE6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
   VVMxCzAJBgNVBAgEXAMPLEAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
   b24xFDASBgNVBAsTC0lBTSEXAMPLE2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
   BgkqhkiG9w0BCQEWEG5vb25lQGFtYEXAMPLEb20wHhcNMTEwNDI1MjA0NTIxWhcN
   MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCEXAMPLEJBgNVBAgTAldBMRAwDgYD
   VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDAEXAMPLEsTC0lBTSBDb25z
   b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEXAMPLE25lQGFt
   YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+aEXAMPLE
   EXAMPLEfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
   rDHudUZEXAMPLELG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
   Ibb3OhjZnzcvQAEXAMPLEWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
   nUhVVxYUntneD9+h8Mg9qEXAMPLEyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
   FFBjvSfpJIlJ00zbhNYS5f6GuoEDEXAMPLEBHjJnyp378OD8uTs7fLvjx79LjSTb
   NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
   -----END CERTIFICATE-----\n",
       "keyPair": {
           "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkEXAMPLEQEFAAOCAQ8AMIIBCgKCAQEAEXAMPLE1nnyJwKSMHw4h\nMMEXAMPLEuuN/dMAS3fyce8DW/4+EXAMPLEyjmoF/YVF/gHr99VEEXAMPLE5VF13\n59VK7cEXAMPLE67GK+y+jikqXOgHh/xJTwo+sGpWEXAMPLEDz18xOd2ka4tCzuWEXAMPLEahJbYkCPUBSU8opVkR7qkEXAMPLE1DR6sx2HocliOOLtu6Fkw91swQWEXAMPLE\GB3ZPrNh0PzQYvjUStZeccyNCx2EXAMPLEvp9mQOUXP6plfgxwKRX2fEXAMPLEDa\nhJLXkX3rHU2xbxJSq7D+XEXAMPLEcw+LyFhI5mgFRl88eGdsAEXAMPLElnI9EesG\nFQIDAQAB\n-----END PUBLIC KEY-----\n",
           "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nkey omitted for security reasons\n-----END RSA PRIVATE KEY-----\n"
       }
   }
   ```

1. In your **Amazon EC2 Instance Connect** window, attach your thing object to the certificate you just created by using the following command and the *certificateArn* in the response from the previous command.

   ```
   aws iot attach-thing-principal \
       --thing-name "MyIotThing" \
       --principal "certificateArn"
   ```

   If successful, this command does not display any output.

**To create and attach a policy**

1. In your **Amazon EC2 Instance Connect** window, create the policy file by copying and pasting this policy document to a file named **\$1/policy.json**.

   If you don't have a favorite Linux editor, you can open **nano**, by using this command.

   ```
   nano ~/policy.json
   ```

   Paste the policy document for `policy.json` into it. Enter ctrl-x to exit the **nano** editor and save the file.

   Contents of the policy document for `policy.json`.  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Publish",
                   "iot:Subscribe",
                   "iot:Receive",
                   "iot:Connect"
               ],
               "Resource": [
                   "*"
               ]
           }
       ]
   }
   ```

1. In your **Amazon EC2 Instance Connect** window, create your policy by using the following command.

   ```
   aws iot create-policy \
       --policy-name "MyIotThingPolicy" \
       --policy-document "file://~/policy.json"
   ```

   Output:  
****  

   ```
   {
       "policyName": "MyIotThingPolicy",
       "policyArn": "arn:aws:iot:us-east-1:your-aws-account:policy/MyIotThingPolicy",
       "policyDocument": "{
           \"Version\": \"2012-10-17\",
           \"Statement\": [
               {
                   \"Effect\": \"Allow\",
                   \"Action\": [
                       \"iot:Publish\",
                       \"iot:Receive\",
                       \"iot:Subscribe\",
                       \"iot:Connect\"
                   ],
                   \"Resource\": [
                       \"*\"
                   ]
           }
           ]
       }",
       "policyVersionId": "1"
   }
   ```

1. In your **Amazon EC2 Instance Connect** window, attach the policy to your virtual device's certificate by using the following command.

   ```
   aws iot attach-policy \
       --policy-name "MyIotThingPolicy" \
       --target "certificateArn"
   ```

   If successful, this command does not display any output.

## Install the AWS IoT Device SDK for JavaScript


In this section, you'll install the AWS IoT Device SDK for JavaScript, which contains the code that applications can use to communicate with AWS IoT and the sample programs. For more information, see the [AWS IoT Device SDK for JavaScript GitHub repository](https://github.com/aws/aws-iot-device-sdk-js-v2).

**To install the AWS IoT Device SDK for JavaScript on your Linux instance**

1. In your **Amazon EC2 Instance Connect** window, clone the AWS IoT Device SDK for JavaScript repository into the `aws-iot-device-sdk-js-v2` directory of your home directory by using this command.

   ```
   cd ~
   git clone https://github.com/aws/aws-iot-device-sdk-js-v2.git
   ```

1. Navigate to the `aws-iot-device-sdk-js-v2` directory that you created in the preceding step.

   ```
   cd aws-iot-device-sdk-js-v2
   ```

1. Use npm to install the SDK.

   ```
   npm install
   ```

## Run the sample application


 The commands in the next sections assume that your key and certificate files are stored on your virtual device as shown in this table.


**Certificate file names**  

|  File  |  File path  | 
| --- | --- | 
|  Private key  |  `~/certs/private.pem.key`  | 
|  Device certificate  |  `~/certs/device.pem.crt`  | 
|  Root CA certificate  |  `~/certs/Amazon-root-CA-1.pem`  | 

In this section, you'll install and run the `pub-sub.js` sample app found in the `aws-iot-device-sdk-js-v2/samples/node` directory of the AWS IoT Device SDK for JavaScript. This app shows how a device, your Amazon EC2 instance, uses the MQTT library to publish and subscribe to MQTT messages. The `pub-sub.js` sample app subscribes to a topic, `topic_1`, publishes 10 messages to that topic and displays the messages as they're received from the message broker.

**To install and run the sample app**

1. In your **Amazon EC2 Instance Connect** window, navigate to the `aws-iot-device-sdk-js-v2/samples/node/pub_sub` directory that the SDK created and install the sample app by using these commands.

   ```
   cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub
   npm install
   ```

1. In your **Amazon EC2 Instance Connect** window, get *your-iot-endpoint* from AWS IoT by using this command.

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

1. In your **Amazon EC2 Instance Connect** window, insert *your-iot-endpoint* as indicated and run this command.

   ```
   node dist/index.js --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

The sample app:

1. Connects to AWS IoT Core for your account.

1. Subscribes to the message topic, **topic\$11**, and displays the messages it receives on that topic.

1. Publishes 10 messages to the topic, **topic\$11**.

1. Displays output similar to the following:

   ```
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":1}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":2}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":3}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":4}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":5}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":6}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":7}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":8}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":9}
   Publish received. topic:"topic_1" dup:false qos:1 retain:false
   {"message":"Hello world!","sequence":10}
   ```

If you're having trouble running the sample app, review [Troubleshoot problems with the sample application](gs-device-troubleshoot.md).

You can also add the `--verbosity debug` parameter to the command line so the sample app displays detailed messages about what it’s doing. That information might provide you the help you need to correct the problem.

## View messages from the sample app in the AWS IoT console


You can see the sample app's messages as they pass through the message broker by using the **MQTT test client** in the **AWS IoT console**.

**To view the MQTT messages published by the sample app**

1. Review [View MQTT messages with the AWS IoT MQTT client](view-mqtt-messages.md). This helps you learn how to use the **MQTT test client** in the **AWS IoT console** to view MQTT messages as they pass through the message broker.

1. Open the **MQTT test client** in the **AWS IoT console**.

1. In **Subscribe to a topic**, Subscribe to the topic, **topic\$11**.

1. In your **Amazon EC2 Instance Connect** window, run the sample app again and watch the messages in the **MQTT test client** in the **AWS IoT console**.

   ```
   cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub
   node dist/index.js --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

For more information about MQTT and how AWS IoT Core supports the protocol, see [MQTT](https://docs.aws.amazon.com//iot/latest/developerguide/mqtt.html).

# Use your Windows or Linux PC or Mac as an AWS IoT device


In this tutorial, you'll configure a personal computer for use with AWS IoT. These instructions support Windows and Linux PCs and Macs. To accomplish this, you need to install some software on your computer. If you don't want to install software on your computer, you might try [Create a virtual device with Amazon EC2](creating-a-virtual-thing.md), which installs all software on a virtual machine.

**Topics**
+ [

## Set up your personal computer
](#gs-pc-prereqs)
+ [

## Install Git, Python, and the AWS IoT Device SDK for Python
](#gs-pc-sdk-node)
+ [

## Set up the policy and run the sample application
](#gs-pc-python-app-run)
+ [

## View messages from the sample app in the AWS IoT console
](#gs-pc-view-msg)
+ [

## Run the Shared Subscription example in Python
](#gs-pc-shared-subscription-example)

## Set up your personal computer


To complete this tutorial, you need a Windows or Linux PC or a Mac with a connection to the internet.

Before you continue to the next step, make sure you can open a command line window on your computer. Use **cmd.exe** on a Windows PC. On a Linux PC or a Mac, use **Terminal**.

## Install Git, Python, and the AWS IoT Device SDK for Python


In this section, you'll install Python, and the AWS IoT Device SDK for Python on your computer. 

### Install the latest version of Git and Python


This procedure explains how to install the latest version of Git and Python on your personal computer.

**To download and install Git and Python on your computer**

1. Check to see if you have Git installed on your computer. Enter this command in the command line.

   ```
   git --version
   ```

   If the command displays the Git version, Git is installed and you can continue to the next step.

   If the command displays an error, open [https://git-scm.com/download](https://git-scm.com/download) and install Git for your computer.

1. Check to see if you have already installed Python. Enter the command in the command line.

   ```
   python -V
   ```
**Note**  
If this command gives an error: `Python was not found`, it might be because your operating system calls the Python v3.x executable as `Python3`. In that case, replace all instances of `python` with `python3` and continue the remainder of this tutorial.

   If the command displays the Python version, Python is already installed. This tutorial requires Python v3.7 or later.

1. If Python is installed, you can skip the rest of the steps in this section. If not, continue.

1. Open [https://www.python.org/downloads/](https://www.python.org/downloads/) and download the installer for your computer.

1. If the download didn't automatically start to install, run the downloaded program to install Python.

1. Verify the installation of Python.

   ```
   python -V
   ```

   Confirm that the command displays the Python version. If the Python version isn't displayed, try downloading and installing Python again.

### Install the AWS IoT Device SDK for Python


**To install the AWS IoT Device SDK for Python on your computer**

1. Install v2 of the AWS IoT Device SDK for Python.

   ```
   python3 -m pip install awsiotsdk
   ```

1. Clone the AWS IoT Device SDK for Python repository into the aws-iot-device-sdk-python-v2 directory of your home directory. This procedure refers to the base directory for the files you're installing as *home*.

   The actual location of the *home* directory depends on your operating system.

------
#### [ Linux/macOS ]

   In macOS and Linux, the *home* directory is `~`.

   ```
   cd ~ 
   git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
   ```

------
#### [ Windows ]

   In Windows, you can find the *home* directory path by running this command in the `cmd` window.

   ```
   echo %USERPROFILE%
   cd %USERPROFILE%
   git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
   ```

------
**Note**  
If you're using Windows PowerShell as opposed to **cmd.exe**, then use the following command.  

   ```
   echo $home
   ```

For more information, see the [AWS IoT Device SDK for Python GitHub repository](https://github.com/aws/aws-iot-device-sdk-python-v2).

### Prepare to run the sample applications


**To prepare your system to run the sample application**
+ Create the `certs` directory. Into the `certs` directory, copy the private key, device certificate, and root CA certificate files you saved when you created and registered the thing object in [Create AWS IoT resources](create-iot-resources.md). The file names of each file in the destination directory should match those in the table.

   The commands in the next section assume that your key and certificate files are stored on your device as shown in this table.

------
#### [ Linux/macOS ]

  Run this command to create the `certs` subdirectory that you'll use when you run the sample applications.

  ```
  mkdir ~/certs
  ```

  Into the new subdirectory, copy the files to the destination file paths shown in the following table.  
**Certificate file names**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/using-laptop-as-device.html)

  Run this command to list the files in the `certs` directory and compare them to those listed in the table.

  ```
  ls -l ~/certs
  ```

------
#### [ Windows ]

  Run this command to create the `certs` subdirectory that you'll use when you run the sample applications.

  ```
  mkdir %USERPROFILE%\certs
  ```

  Into the new subdirectory, copy the files to the destination file paths shown in the following table.  
**Certificate file names**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/using-laptop-as-device.html)

  Run this command to list the files in the `certs` directory and compare them to those listed in the table.

  ```
  dir %USERPROFILE%\certs
  ```

------

## Set up the policy and run the sample application


In this section, you'll set up your policy and run the `pubsub.py` sample script found in the `aws-iot-device-sdk-python-v2/samples` directory of the AWS IoT Device SDK for Python. This script shows how your device uses the MQTT library to publish and subscribe to MQTT messages.

The `pubsub.py` sample app subscribes to a topic, `test/topic`, publishes 10 messages to that topic, and displays the messages as they're received from the message broker.

To run the `pubsub.py` sample script, you need the following information:


**Application parameter values**  

|  Parameter  |  Where to find the value  | 
| --- | --- | 
| your-iot-endpoint |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/using-laptop-as-device.html)  | 

The *your-iot-endpoint* value has a format of: `endpoint_id-ats.iot.region.amazonaws.com`, for example, `a3qj468EXAMPLE-ats.iot.us-west-2.amazonaws.com`.

Before running the script, make sure your thing's policy provides permissions for the sample script to connect, subscribe, publish, and receive. 

**To find and review the policy document for a thing resource**

1. In the [AWS IoT console](https://console.aws.amazon.com//iot/home#/thinghub), in the **Things** list, find the thing resource that represents your device.

1. Choose the **Name** link of the thing resource that represents your device to open the **Thing details** page.

1. In the **Thing details** page, in the **Certificates** tab, choose the certificate that is attached to the thing resource. There should only be one certificate in the list. If there is more than one, choose the certificate whose files are installed on your device and that will be used to connect to AWS IoT Core.

   In the **Certificate** details page, in the **Policies** tab, choose the policy that's attached to the certificate. There should only be one. If there is more than one, repeat the next step for each to make sure that at least one policy grants the required access.

1. In the **Policy** overview page, find the JSON editor and choose **Edit policy document** to review and edit the policy document as required.

1. The policy JSON is displayed in the following example. In the `"Resource"` element, replace `region:account` with your AWS Region and AWS account in each of the `Resource` values.  
****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Publish",
                   "iot:Receive"
               ],
               "Resource": [
               "arn:aws:iot:us-east-1:123456789012:topic/test/topic"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Subscribe"
               ],
               "Resource": [
               "arn:aws:iot:us-east-1:123456789012:topicfilter/test/topic"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "iot:Connect"
               ],
               "Resource": [
               "arn:aws:iot:us-east-1:123456789012:client/test-*"
               ]
           }
       ]
   }
   ```

------
#### [ Linux/macOS ]

**To run the sample script on Linux/macOS**

1. In your command line window, navigate to the `~/aws-iot-device-sdk-python-v2/samples/node/pub_sub` directory that the SDK created by using these commands.

   ```
   cd ~/aws-iot-device-sdk-python-v2/samples
   ```

1. In your command line window, replace *your-iot-endpoint* as indicated and run this command.

   ```
   python3 pubsub.py --endpoint your-iot-endpoint --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key
   ```

------
#### [ Windows ]

**To run the sample app on a Windows PC**

1. In your command line window, navigate to the `%USERPROFILE%\aws-iot-device-sdk-python-v2\samples` directory that the SDK created and install the sample app by using these commands.

   ```
   cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples
   ```

1. In your command line window, replace *your-iot-endpoint* as indicated and run this command.

   ```
   python3 pubsub.py --endpoint your-iot-endpoint --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key
   ```

------

The sample script:

1. Connects to the AWS IoT Core for your account.

1. Subscribes to the message topic, **test/topic**, and displays the messages it receives on that topic.

1. Publishes 10 messages to the topic, **test/topic**.

1. Displays output similar to the following:

```
Connected!
Subscribing to topic 'test/topic'...
Subscribed with QoS.AT_LEAST_ONCE
Sending 10 message(s)
Publishing message to topic 'test/topic': Hello World! [1]
Received message from topic 'test/topic': b'"Hello World! [1]"'
Publishing message to topic 'test/topic': Hello World! [2]
Received message from topic 'test/topic': b'"Hello World! [2]"'
Publishing message to topic 'test/topic': Hello World! [3]
Received message from topic 'test/topic': b'"Hello World! [3]"'
Publishing message to topic 'test/topic': Hello World! [4]
Received message from topic 'test/topic': b'"Hello World! [4]"'
Publishing message to topic 'test/topic': Hello World! [5]
Received message from topic 'test/topic': b'"Hello World! [5]"'
Publishing message to topic 'test/topic': Hello World! [6]
Received message from topic 'test/topic': b'"Hello World! [6]"'
Publishing message to topic 'test/topic': Hello World! [7]
Received message from topic 'test/topic': b'"Hello World! [7]"'
Publishing message to topic 'test/topic': Hello World! [8]
Received message from topic 'test/topic': b'"Hello World! [8]"'
Publishing message to topic 'test/topic': Hello World! [9]
Received message from topic 'test/topic': b'"Hello World! [9]"'
Publishing message to topic 'test/topic': Hello World! [10]
Received message from topic 'test/topic': b'"Hello World! [10]"'
10 message(s) received.
Disconnecting...
Disconnected!
```

If you're having trouble running the sample app, review [Troubleshoot problems with the sample application](gs-device-troubleshoot.md).

You can also add the `--verbosity Debug` parameter to the command line so the sample app displays detailed messages about what it’s doing. That information might help you correct the problem.

## View messages from the sample app in the AWS IoT console


You can see the sample app's messages as they pass through the message broker by using the **MQTT test client** in the **AWS IoT console**.

**To view the MQTT messages published by the sample app**

1. Review [View MQTT messages with the AWS IoT MQTT client](view-mqtt-messages.md). This helps you learn how to use the **MQTT test client** in the **AWS IoT console** to view MQTT messages as they pass through the message broker.

1. Open the **MQTT test client** in the **AWS IoT console**.

1. In **Subscribe to a topic**, subscribe to the topic, **test/topic**.

1. In your command line window, run the sample app again and watch the messages in the **MQTT client** in the **AWS IoT console**.

------
#### [ Linux/macOS ]

   ```
   cd ~/aws-iot-device-sdk-python-v2/samples
   python3 pubsub.py --topic test/topic --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

------
#### [ Windows ]

   ```
   cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples
   python3 pubsub.py --topic test/topic --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key --endpoint your-iot-endpoint
   ```

------

For more information about MQTT and how AWS IoT Core supports the protocol, see [MQTT](https://docs.aws.amazon.com//iot/latest/developerguide/mqtt.html).

## Run the Shared Subscription example in Python


AWS IoT Core supports [Shared Subscriptions](mqtt.md#mqtt5-shared-subscription) for both MQTT 3 and MQTT 5. Shared Subscriptions allow multiple clients to share a subscription to a topic and only one client will receive messages published to that topic using a random distribution. To use Shared Subscriptions, clients subscribe to a Shared Subscription's [topic filter](https://docs.aws.amazon.com//iot/latest/developerguide/topics.html#topicfilters): `$share/{ShareName}/{TopicFilter}`. 

**To set up the policy and run the Shared Subscription example**

1. To run the Shared Subscription example, you must set up your thing's policy as documented in [MQTT 5 Shared Subscription](https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/samples/mqtt5_shared_subscription.md#mqtt5-shared-subscription). 

1. To run the Shared Subscription example, run the following commands.

------
#### [ Linux/macOS ]

**To run the sample script on Linux/macOS**

   1. In your command line window, navigate to the `~/aws-iot-device-sdk-python-v2/samples` directory that the SDK created by using these commands.

      ```
      cd ~/aws-iot-device-sdk-python-v2/samples
      ```

   1. In your command line window, replace *your-iot-endpoint* as indicated and run this command.

      ```
      python3 mqtt5_shared_subscription.py --endpoint your-iot-endpoint --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --group_identifier consumer
      ```

------
#### [ Windows ]

**To run the sample app on a Windows PC**

   1. In your command line window, navigate to the `%USERPROFILE%\aws-iot-device-sdk-python-v2\samples` directory that the SDK created and install the sample app by using these commands.

      ```
      cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples
      ```

   1. In your command line window, replace *your-iot-endpoint* as indicated and run this command.

      ```
      python3 mqtt5_shared_subscription.py --endpoint your-iot-endpoint --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key --group_identifier consumer
      ```

------
**Note**  
You can optionally specify a group identifier based on your needs when you run the sample (e.g., `--group_identifier consumer`). If you don't specify one, `python-sample` is the default group identifier.

1. The output in your command line can look like the following:

   ```
   Publisher]: Lifecycle Connection Success
   [Publisher]: Connected
   Subscriber One]: Lifecycle Connection Success
   [Subscriber One]: Connected
   Subscriber Two]: Lifecycle Connection Success
   [Subscriber Two]: Connected
   [Subscriber One]: Subscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber One]: Full subscribed topic is: '$share/consumer/test/topic' with SubAck code: [<SubackReasonCode.GRANTED_QOS_1: 1>]
   [Subscriber Two]: Subscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber Two]: Full subscribed topic is: '$share/consumer/test/topic' with SubAck code: [<SubackReasonCode.GRANTED_QOS_1: 1>]
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [1]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [2]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [3]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [4]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [5]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [6]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [7]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [8]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber Two] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [9]"'
   [Publisher]: Sent publish and got PubAck code: <PubackReasonCode.SUCCESS: 0>
   [Subscriber One] Received a publish
           Publish received message on topic: test/topic
           Message: b'"Hello World!  [10]"'
   [Subscriber One]: Unsubscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber One]: Full unsubscribed topic is: '$share/consumer/test/topic' with UnsubAck code: [<UnsubackReasonCode.SUCCESS: 0>]
   [Subscriber Two]: Unsubscribed to topic 'test/topic' in shared subscription group 'consumer'.
   [Subscriber Two]: Full unsubscribed topic is: '$share/consumer/test/topic' with UnsubAck code [<UnsubackReasonCode.SUCCESS: 0>]
   Publisher]: Lifecycle Disconnected
   [Publisher]: Lifecycle Stopped
   [Publisher]: Fully stopped
   Subscriber One]: Lifecycle Disconnected
   [Subscriber One]: Lifecycle Stopped
   [Subscriber One]: Fully stopped
   Subscriber Two]: Lifecycle Disconnected
   [Subscriber Two]: Lifecycle Stopped
   [Subscriber Two]: Fully stopped
   Complete!
   ```

1. Open **MQTT test client** in the **AWS IoT console**. In **Subscribe to a topic**, subscribe to the Shared Subscription’s topic such as: `$share/consumer/test/topic`. You can specify a group identifier based on your needs when you run the sample (e.g., `--group_identifier consumer`). If you don't specify a group identifier, the default value is `python-sample`. For more information, see [MQTT 5 Shared Subscription Python example](https://github.com/aws/aws-iot-device-sdk-python-v2/blob/main/samples/mqtt5_shared_subscription.md#mqtt5-shared-subscription) and [Shared Subscriptions](mqtt.md#mqtt5-shared-subscription) from *AWS IoT Core Developer Guide*.

   In your command line window, run the sample app again and watch the distribution of messages in your **MQTT test client** of the **AWS IoT console** and the command line.  
![\[The shared subscriptions output page.\]](http://docs.aws.amazon.com/iot/latest/developerguide/images/shared-subscription-output.png)

# Connect a Raspberry Pi or other device


In this section, we'll configure a Raspberry Pi for use with AWS IoT. If you have another device that you'd like to connect, the instructions for the Raspberry Pi include references that can help you adapt these instructions to your device.

This normally takes about 20 minutes, but it can take longer if you have many system software upgrades to install.

**Topics**
+ [

## Set up your device
](#gs-device-prereqs)
+ [

## Install the required tools and libraries for the AWS IoT Device SDK
](#gs-device-sdk-tools)
+ [

## Install AWS IoT Device SDK
](#gs-device-install-sdk)
+ [

## Install and run the sample app
](#gs-device-node-app-run)
+ [

## View messages from the sample app in the AWS IoT console
](#gs-device-view-msg)

**Important**  
Adapting these instructions to other devices and operating systems can be challenging. You'll need to understand your device well enough to be able to interpret these instructions and apply them to your device.  
If you encounter difficulties while configuring your device for AWS IoT, you might try one of the other device options as an alternative, such as [Create a virtual device with Amazon EC2](creating-a-virtual-thing.md) or [Use your Windows or Linux PC or Mac as an AWS IoT device](using-laptop-as-device.md).

## Set up your device


The goal of this step is to collect what you'll need to configure your device so that it can start the operating system (OS), connect to the internet, and allow you to interact with it at a command line interface.

To complete this tutorial, you need the following:
+ An AWS account. If you don't have one, complete the steps described in [Set up AWS account](setting-up.md) before you continue.
+ A [Raspberry Pi 3 Model B](https://www.raspberrypi.com/products/) or more recent model. This might work on earlier versions of the Raspberry Pi, but they have not been tested.
+ [Raspberry Pi OS (32-bit)](https://www.raspberrypi.com/software/operating-systems/) or later. We recommend using the latest version of the Raspberry Pi OS. Earlier versions of the OS might work, but they have not been tested.

  To run this example, you do not need to install the desktop with the graphical user interface (GUI); however, if you're new to the Raspberry Pi and your Raspberry Pi hardware supports it, using the desktop with the GUI might be easier.
+ An Ethernet or WiFi connection.
+ Keyboard, mouse, monitor, cables, power supplies, and other hardware required by your device.

**Important**  
Before you continue to the next step, your device must have its operating system installed, configured, and running. The device must be connected to the internet and you will need to be able to access the device by using its command line interface. Command line access can be through a directly-connected keyboard, mouse, and monitor, or by using an SSH terminal remote interface.

 If you are running an operating system on your Raspberry Pi that has a graphical user interface (GUI), open a terminal window on the device and perform the following instructions in that window. Otherwise, if you are connecting to your device by using a remote terminal, such as PuTTY, open a remote terminal to your device and use that.

## Install the required tools and libraries for the AWS IoT Device SDK


Before you install the AWS IoT Device SDK and sample code, make sure your system is up to date and has the required tools and libraries to install the SDKs.

1. 

**Update the operating system and install required libraries**  
Before you install an AWS IoT Device SDK, run these commands in a terminal window on your device to update the operating system and install the required libraries.

   ```
   sudo apt-get update
   ```

   ```
   sudo apt-get upgrade
   ```

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

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

1. 

**Install Git**  
If your device's operating system doesn't come with Git installed, you must install it to install the AWS IoT Device SDK for JavaScript. 

   1. Test to see if Git is already installed by running this command.

      ```
      git --version
      ```

   1. If the previous command returns the Git version, Git is already installed and you can skip to Step 3.

   1. If an error is displayed when you run the **git** command, install Git by running this command.

      ```
      sudo apt-get install git
      ```

   1. Test again to see if Git is installed by running this command.

      ```
      git --version
      ```

   1. If Git is installed, continue to the next section. If not, troubleshoot and correct the error before continuing. You need Git to install the AWS IoT Device SDK for JavaScript.

## Install AWS IoT Device SDK


Install the AWS IoT Device SDK.

------
#### [ Python ]

In this section, you'll install Python, its development tools, and the AWS IoT Device SDK for Python on your device. These instructions are for a Raspberry Pi running the latest Raspberry Pi OS. If you have another device or are using another operating system, you might need to adapt these instructions for your device.

1. 

**Install Python and its development tools**  
The AWS IoT Device SDK for Python requires Python v3.5 or later to be installed on your Raspberry Pi.

   In a terminal window to your device, run these commands.

   1. Run this command to determine the version of Python installed on your device.

      ```
      python3 --version
      ```

      If Python is installed, it will display its version.

   1. If the version displayed is `Python 3.5` or greater, you can skip to Step 2.

   1. If the version displayed is less than `Python 3.5`, you can install the correct version by running this command.

      ```
      sudo apt install python3
      ```

   1. Run this command to confirm that the correct version of Python is now installed.

      ```
      python3 --version
      ```

1. 

**Test for pip3**  
In a terminal window to your device, run these commands.

   1. Run this command to see if **pip3** is installed.

      ```
      pip3 --version
      ```

   1. If the command returns a version number, **pip3** is installed and you can skip to Step 3.

   1. If the previous command returns an error, run this command to install **pip3**.

      ```
      sudo apt install python3-pip
      ```

   1. Run this command to see if **pip3** is installed.

      ```
      pip3 --version
      ```

1. 

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

   On your device, run these commands.

   ```
   cd ~
   python3 -m pip install awsiotsdk
   ```

   ```
   git clone https://github.com/aws/aws-iot-device-sdk-python-v2.git
   ```

------
#### [ JavaScript ]

In this section, you'll install Node.js, the npm package manager, and the AWS IoT Device SDK for JavaScript on your device. These instructions are for a Raspberry Pi running the Raspberry Pi OS. If you have another device or are using another operating system, you might need to adapt these instructions for your device.

1. 

**Install the latest version of Node.js**  
The AWS IoT Device SDK for JavaScript requires Node.js and the npm package manager to be installed on your Raspberry Pi.

   1. Download the latest version of the Node repository by entering this command.

      ```
      cd ~
      curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
      ```

   1. Install Node and npm.

      ```
      sudo apt-get install -y nodejs
      ```

   1. Verify the installation of Node.

      ```
      node -v
      ```

      Confirm that the command displays the Node version. This tutorial requires Node v10.0 or later. If the Node version isn't displayed, try downloading the Node repository again.

   1. Verify the installation of npm.

      ```
      npm -v
      ```

      Confirm that the command displays the npm version. If the npm version isn't displayed, try installing Node and npm again.

   1. Restart the device.

      ```
      sudo shutdown -r 0
      ```

      Continue after the device restarts.

1. 

**Install the AWS IoT Device SDK for JavaScript**  
Install the AWS IoT Device SDK for JavaScript on your Raspberry Pi.

   1. Clone the AWS IoT Device SDK for JavaScript repository into the `aws-iot-device-sdk-js-v2` directory of your *home* directory. On the Raspberry Pi, the *home* directory is `~/`, which is used as the *home* directory in the following commands. If your device uses a different path for the *home* directory, you must replace `~/` with the correct path for your device in the following commands.

      These commands create the `~/aws-iot-device-sdk-js-v2` directory and copy the SDK code into it.

      ```
      cd ~
      git clone https://github.com/aws/aws-iot-device-sdk-js-v2.git
      ```

   1. Change to the `aws-iot-device-sdk-js-v2` directory that you created in the preceding step and run `npm install` to install the SDK. The command `npm install` will invoke the `aws-crt` library build that can take a few minutes to complete.

      ```
      cd ~/aws-iot-device-sdk-js-v2
      npm install
      ```

------

## Install and run the sample app


In this section, you'll install and run the `pubsub` sample app found in the AWS IoT Device SDK. This app shows how your device uses the MQTT library to publish and subscribe to MQTT messages. The sample app subscribes to a topic, `topic_1`, publishes 10 messages to that topic, and displays the messages as they're received from the message broker.

**Install the certificate files**  
The sample app requires the certificate files that authenticate the device to be installed on the device.

**To install the device certificate files for the sample app**

1. Create a `certs` subdirectory in your *home* directory by running these commands.

   ```
   cd ~
   mkdir certs
   ```

1. Into the `~/certs` directory, copy the private key, device certificate, and root CA certificate that you created earlier in [Create AWS IoT resources](create-iot-resources.md).

   How you copy the certificate files to your device depends on the device and operating system and isn't described here. However, if your device supports a graphical user interface (GUI) and has a web browser, you can perform the procedure described in [Create AWS IoT resources](create-iot-resources.md) from your device's web browser to download the resulting files directly to your device.

   The commands in the next section assume that your key and certificate files are stored on the device as shown in this table.  
**Certificate file names**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.html)

To run the sample app, you need the following information:


**Application parameter values**  

|  Parameter  |  Where to find the value  | 
| --- | --- | 
| your-iot-endpoint |  In the [AWS IoT console](https://console.aws.amazon.com/iot/home), choose **All devices**, and then choose **Things**. On the **Settings** page in the AWS IoT menu. Your endpoint is displayed in the **Device data endpoint** section.  | 

The *your-iot-endpoint* value has a format of: `endpoint_id-ats.iot.region.amazonaws.com`, for example, `a3qj468EXAMPLE-ats.iot.us-west-2.amazonaws.com`.

------
#### [ Python ]

**To install and run the sample app**

1. Navigate to the sample app directory.

   ```
   cd ~/aws-iot-device-sdk-python-v2/samples
   ```

1. In the command line window, replace *your-iot-endpoint* as indicated and run this command.

   ```
   python3 pubsub.py --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

1. Observe that the sample app:

   1. Connects to the AWS IoT service for your account.

   1. Subscribes to the message topic, **topic\$11**, and displays the messages it receives on that topic.

   1. Publishes 10 messages to the topic, **topic\$11**.

   1. Displays output similar to the following:

   ```
   Connecting to a3qEXAMPLEffp-ats.iot.us-west-2.amazonaws.com with client ID 'test-0c8ae2ff-cc87-49d2-a82a-ae7ba1d0ca5a'...
   Connected!
   Subscribing to topic 'topic_1'...
   Subscribed with QoS.AT_LEAST_ONCE
   Sending 10 message(s)
   Publishing message to topic 'topic_1': Hello World! [1]
   Received message from topic 'topic_1': b'Hello World! [1]'
   Publishing message to topic 'topic_1': Hello World! [2]
   Received message from topic 'topic_1': b'Hello World! [2]'
   Publishing message to topic 'topic_1': Hello World! [3]
   Received message from topic 'topic_1': b'Hello World! [3]'
   Publishing message to topic 'topic_1': Hello World! [4]
   Received message from topic 'topic_1': b'Hello World! [4]'
   Publishing message to topic 'topic_1': Hello World! [5]
   Received message from topic 'topic_1': b'Hello World! [5]'
   Publishing message to topic 'topic_1': Hello World! [6]
   Received message from topic 'topic_1': b'Hello World! [6]'
   Publishing message to topic 'topic_1': Hello World! [7]
   Received message from topic 'topic_1': b'Hello World! [7]'
   Publishing message to topic 'topic_1': Hello World! [8]
   Received message from topic 'topic_1': b'Hello World! [8]'
   Publishing message to topic 'topic_1': Hello World! [9]
   Received message from topic 'topic_1': b'Hello World! [9]'
   Publishing message to topic 'topic_1': Hello World! [10]
   Received message from topic 'topic_1': b'Hello World! [10]'
   10 message(s) received.
   Disconnecting...
   Disconnected!
   ```

   If you're having trouble running the sample app, review [Troubleshoot problems with the sample application](gs-device-troubleshoot.md).

   You can also add the `--verbosity Debug` parameter to the command line so the sample app displays detailed messages about what it’s doing. That information might provide you the help you need to correct the problem.

------
#### [ JavaScript ]

**To install and run the sample app**

1. In your command line window, navigate to the `~/aws-iot-device-sdk-js-v2/samples/node/pub_sub` directory that the SDK created and install the sample app by using these commands. The command `npm install` will invoke the `aws-crt` library build that can take a few minutes to complete.

   ```
   cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub
   npm install
   ```

1. In the command line window, replace *your-iot-endpoint* as indicated and run this command.

   ```
   node dist/index.js --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

1. Observe that the sample app:

   1. Connects to the AWS IoT service for your account.

   1. Subscribes to the message topic, **topic\$11**, and displays the messages it receives on that topic.

   1. Publishes 10 messages to the topic, **topic\$11**.

   1. Displays output similar to the following:

   ```
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":1}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":2}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":3}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":4}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":5}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":6}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":7}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":8}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":9}
   Publish received on topic topic_1
   {"message":"Hello world!","sequence":10}
   ```

   If you're having trouble running the sample app, review [Troubleshoot problems with the sample application](gs-device-troubleshoot.md).

   You can also add the `--verbosity Debug` parameter to the command line so the sample app displays detailed messages about what it’s doing. That information might provide you the help you need to correct the problem.

------

## View messages from the sample app in the AWS IoT console


You can see the sample app's messages as they pass through the message broker by using the **MQTT test client** in the **AWS IoT console**.

**To view the MQTT messages published by the sample app**

1. Review [View MQTT messages with the AWS IoT MQTT client](view-mqtt-messages.md). This helps you learn how to use the **MQTT test client** in the **AWS IoT console** to view MQTT messages as they pass through the message broker.

1. Open the **MQTT test client** in the **AWS IoT console**.

1. Subscribe to the topic, **topic\$11**.

1. In your command line window, run the sample app again and watch the messages in the **MQTT client** in the **AWS IoT console**.

------
#### [ Python ]

   ```
   cd ~/aws-iot-device-sdk-python-v2/samples
   python3 pubsub.py --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

------
#### [ JavaScript ]

   ```
   cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub
   node dist/index.js --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint your-iot-endpoint
   ```

------

# Troubleshoot problems with the sample application


If you encounter an error when you try to run the sample app, here are some things to check.

## Check the certificate


If the certificate is not active, AWS IoT will not accept any connection attempts that use it for authorization. When creating your certificate, it's easy to overlook the **Activate** button. Fortunately, you can activate your certificate from the [AWS IoT console](https://console.aws.amazon.com/iot/home).

**To check your certificate's activation**

1. In the [AWS IoT console](https://console.aws.amazon.com/iot/home), in the left menu, choose **Secure**, and then choose **Certificates**.

1. In the list of certificates, find the certificate you created for the exercise and check its status in the **Status** column.

   If you don't remember the certificate's name, check for any that are **Inactive** to see if they might be the one you're using.

   Choose the certificate in the list to open its detail page. In the detail page, you can see its **Create date** to help you identify the certificate.

1. **To activate an inactive certificate**, from the certificate's detail page, choose **Actions** and then choose **Activate**. 

If you found the correct certificate and it's active, but you're still having problems running the sample app, check its policy as the next step describes.

You can also try to create a new thing and a new certificate by following the steps in [Create a thing object](create-iot-resources.md#create-aws-thing). If you create a new thing, you will need to give it a new thing name and download the new certificate files to your device.

## Check the policy attached to the certificate


Policies authorize actions in AWS IoT. If the certificate used to connect to AWS IoT does not have a policy, or does not have a policy that allows it to connect, the connection will be refused, even if the certificate is active.

**To check the policies attached to a certificate**

1. Find the certificate as described in the previous item and open its details page.

1. In the left menu of the certificate's details page, choose **Policies** to see the policies attached to the certificate.

1. If there are no policies attached to the certificate, add one by choosing the **Actions** menu, and then choosing **Attach policy**. 

   Choose the policy that you created earlier in [Create AWS IoT resources](create-iot-resources.md).

1. If there is a policy attached, choose the policy tile to open its details page.

   In the details page, review the **Policy document** to make sure it contains the same information as the one you created in [Create an AWS IoT policy](create-iot-resources.md#create-iot-policy).

## Check the command line


Make sure you used the correct command line for your system. The commands used on Linux and macOS systems are often different from those used on Windows systems.

## Check the endpoint address


Review the command you entered and double-check the endpoint address in your command to the one in your [AWS IoT console](https://console.aws.amazon.com/iot/home).

## Check the file names of the certificate files


Compare the file names in the command you entered to the file names of the certificate files in the `certs` directory.

Some systems might require the file names to be in quotes to work correctly.

## Check the SDK installation


Make sure that your SDK installation is complete and correct.

If in doubt, reinstall the SDK on your device. In most cases, that's a matter of finding the section of the tutorial titled **Install the AWS IoT Device SDK for **SDK language**** and following the procedure again.

If you are using the **AWS IoT Device SDK for JavaScript**, remember to install the sample apps before you try to run them. Installing the SDK doesn't automatically install the sample apps. The sample apps must be installed manually after the SDK has been installed.