

# Add a destination for your Sidewalk end device
<a name="iot-sidewalk-qsg-destination"></a>

**Note**  
For Bluetooth Low Energy based location, AWS IoT returns location coordinates based on the approximate location of nearby Sidewalk Gateways that are connected to Amazon Sidewalk and have the Community Finding feature enabled. Gateway Location Data is AWS Content and is provided to you solely for the purpose of assisting you in locating your devices that are connected to Amazon Sidewalk, and you must only use the data for that purpose. You must only use and access location data via the interface and functionality that we generally make available to you, and you must not attempt to re-identify, reverse engineer, or re-map any Gateway location data provided by us to you.

AWS IoT Core for Amazon Sidewalk destinations describe the AWS IoT rule or MQTT topic that processes a device's data for use by other AWS services and applications. Use AWS IoT rules or MQTT topics to process the data and device messages and route it to other services.

Because most Sidewalk devices don't send data to AWS IoT Core for Amazon Sidewalk in a format that can be used by AWS services, an AWS IoT rule must process it first. The AWS IoT rule contains the SQL statement that interprets the device's data and the topic rule actions that send the result of the SQL statement to the services that will use it.

The AWS IoT rule processes binary messages received from a device and converts the messages to other formats that make other services easy to use them. Destinations associate your Sidewalk end device with the rule that processes the device data to send to other AWS services. For more information about rules, see [Rules for AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html) in the *AWS IoT Core documentation*.

## How to create and use a destination
<a name="iot-sidewalk-destination-how"></a>

1. Create an AWS IoT rule and an IAM role for the destination. The AWS IoT rule specifies the rules that will process the device's data and routes it for use by other AWS services and your applications. The IAM role grants permission to access the rule.

1. Create a destination for your Sidewalk devices using the `CreateDestination` API operation. Specify the destination name, rule name, role name, and any optional parameters. The API will return a unique identifier for the destination, which you can specify when adding your end device to AWS IoT Core for Amazon Sidewalk.

The following shows how to create a destination, and an AWS IoT rule and IAM role for the destination.

**Topics**
+ [How to create and use a destination](#iot-sidewalk-destination-how)
+ [Create a destination for your Sidewalk device](iot-sidewalk-destination-create.md)
+ [Create an IAM role and IoT rule for your destination](sidewalk-destination-rule-role.md)

# Create a destination for your Sidewalk device
<a name="iot-sidewalk-destination-create"></a>

You can add a destination to your account for AWS IoT Core for Amazon Sidewalk either from the using the [Destinations hub](https://console.aws.amazon.com/iot/home#/wireless/destinations) or using the `CreateDestination`. When creating your destination, specify:
+ A unique name for the destination to use for your Sidewalk end device.
**Note**  
If you already add your device using a destination name, you must use that name when creating your destination. For more information, see [Step 2: Add your Sidewalk device](iot-sidewalk-add-device.md#iot-sidewalk-device-create). 
+ The name of the AWS IoT rule that will process the device's data, and the topic to which messages are published.
+ An IAM role that grants the device's data permission to access the rule.

The following sections describe how to create the AWS IoT rule and IAM role for your destination.

## Create a destination (console)
<a name="iot-sidewalk-destination-create-console"></a>

To create a destination using the AWS IoT console, go to the [Destinations hub](https://console.aws.amazon.com/iot/home#/wireless/destinations) and choose **Add destination**.

![\[Add a Sidewalk destination using the AWS IoT console.\]](http://docs.aws.amazon.com/iot-wireless/latest/developerguide/images/iot-sidewalk-add-destination.PNG)


To process a device's data, specify the following fields when creating a destination, and then choose **Add destination**.
+ 

**Destination details**  
Enter a **Destination name** and an optional description for your destination.
+ 

**Rule name**  
The AWS IoT rule that is configured to evaluate messages sent by your device and process the device's data. The rule name will be mapped to your destination. The destination requires the rule to process the messages that it receives. You can choose for the messages to be processed by either invoking an AWS IoT rule or by publishing to the AWS IoT message broker.
  + If you choose **Enter a rule name**, enter a name, and then choose **Copy** to copy the rule name that you'll enter when creating the AWS IoT rule. You can either choose **Create rule** to create the rule now or navigate to the [Rules](https://console.aws.amazon.com/iot/home#/create/rule) Hub of the AWS IoT console and create a rule with that name.

    You can also enter a rule and use the **Advanced** setting to specify a topic name. The topic name is provided during rule invocation and is accessed by using the `topic` expression inside the rule. For more information about AWS IoT rules, see [AWS IoT rules](https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html).
  + If you choose **Publish to AWS IoT message broker**, enter a topic name. You can then copy the MQTT topic name and multiple subscribers can subscribe to this topic to receive messages published to that topic. For more information, see [MQTT topics](https://docs.aws.amazon.com/iot/latest/developerguide/topics.html).

  For more information about AWS IoT rules for destinations, see [Create rules to process LoRaWAN device messages](https://docs.aws.amazon.com/iot-wireless/latest/developerguide/lorawan-destination-rules.html).
+ 

**Role name**  
The IAM role that grants the device's data permission to access the rule named in **Rule name**. In the console, you can create a new service role or select an existing service role. If you're creating a new service role, you can either enter a role name (for example, **SidewalkDestinationRole**), or leave it blank for AWS IoT Core for LoRaWAN to generate a new role name. AWS IoT Core for LoRaWAN will then automatically create the IAM role with the appropriate permissions on your behalf.

## Create a destination (CLI)
<a name="iot-sidewalk-destination-create-cli"></a>

To create a destination, use the [https://docs.aws.amazon.com/iot-wireless/latest/apireference/API_CreateDestination.html](https://docs.aws.amazon.com/iot-wireless/latest/apireference/API_CreateDestination.html) API operation or the [https://docs.aws.amazon.com/cli/latest/reference/iotwireless/create-destination.html](https://docs.aws.amazon.com/cli/latest/reference/iotwireless/create-destination.html) CLI command. For example, the following command creates a destination for your Sidewalk end device:

```
aws iotwireless create-destination --name SidewalkDestination \
    --expression-type RuleName --expression SidewalkRule \
    --role-arn arn:aws:iam::123456789012:role/SidewalkRole
```

Running this command returns the destination details, which include the Amazon Resource Name (ARN) and the destination name.

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:Destination/SidewalkDestination",
    "Name": "SidewalkDestination"
}
```

For more information about creating a destination, see [Create rules to process LoRaWAN device messages](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-destination-rules.html).

# Create an IAM role and IoT rule for your destination
<a name="sidewalk-destination-rule-role"></a>

Your destination can be an MQTT topic or an AWS IoT rule. In this example, you configure an AWS IoT rule as a destination.

AWS IoT rules send device messages to other services. AWS IoT rules can also process the binary messages received from a Sidewalk end device for other services to use. AWS IoT Core for Amazon Sidewalk destinations associate a wireless device with the rule that processes the device's message data to send to other services. The rule acts on the device's data as soon as AWS IoT Core for Amazon Sidewalk receives it. For all devices that send their data to the same service, you can create a destination that can be shared by all devices. You must also create an IAM role that grants permission to send data to the rule.

## Create an IAM role for your destination
<a name="iot-sidewalk-destination-role"></a>

Create an IAM role that grants AWS IoT Core for Amazon Sidewalk permission to send data to the AWS IoT rule. To create the role, use the [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html) API operation or [https://docs.aws.amazon.com/cli/latest/reference/iam/create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role) CLI command. You can name the role as *`SidewalkRole`*.

```
aws iam create-role --role-name SidewalkRole \ 
    --assume-role-policy-document '{"Version": "2012-10-17",		 	 	 "Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}'
```

You can also define the trust policy for the role using a JSON file.

```
aws iam create-role --role-name SidewalkRole \ 
    --assume-role-policy-document file://trust-policy.json
```

The following shows the contents of the JSON file.

**Contents of trust-policy.json**

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

## Create a rule for your destination
<a name="iot-sidewalk-destination-rule"></a>

Use the AWS IoT Core API operation, [https://docs.aws.amazon.com/iot/latest/apireference/API_CreateTopicRule.html](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateTopicRule.html), or the AWS CLI command, [https://docs.aws.amazon.com/cli/latest/reference/iot/create-topic-rule.html](https://docs.aws.amazon.com/cli/latest/reference/iot/create-topic-rule.html), to create a rule. The topic rule will be used by your destination to route the data received from your Sidewalk end device to other AWS services. For example, you can create a rule action that sends a message to a Lambda function. You can define the Lambda function such that it receives the application data from your device and uses base64 to decode the payload data so that it can be used by other applications.

The following steps show how you create the Lambda function and then a topic rule that sends a message to this function.

1. 

**Create execution role and policy**

   Create an IAM role that grants your function permission to access AWS resources. You can also define the trust policy for the role using a JSON file.

   ```
   aws iam create-role --role-name lambda-ex \ 
       --assume-role-policy-document file://lambda-trust-policy.json
   ```

   The following shows the contents of the JSON file.

   **Contents of lambda-trust-policy.json**  
****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "lambda.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

1. 

**Create and test Lambda function**

   Perform the following steps to create a AWS Lambda function that base64 decodes the payload data.

   1. Write the code for decoding the payload data. For example, you can use the following sample Python code. Specify a name for the script, such as *`base64_decode.py`*.

      **Contents of base64\$1decode.py**

      ```
      // -----------------------------------------------------------
      // ----- Python script to decode incoming binary payload -----
      // -----------------------------------------------------------
      import json
      import base64
      
      def lambda_handler(event, context):
      
          message = json.dumps(event)
          print (message)
      
          payload_data = base64.b64decode(event["PayloadData"])
          print(payload_data)
          print(int(payload_data,16))
      ```

   1. Create a deployment package as a zip file that contains the Python file and name it as `base64_decode.zip`. Use the `CreateFunction` API or the `create-function` CLI command to create a Lambda function for the sample code, *`base64_decode.py`*.

   1. 

      ```
      aws lambda create-function --function-name my-function \
      --zip-file fileb://base64_decode.zip --handler index.handler \ 
      --runtime python3.9 --role arn:aws:iam::123456789012:role/lambda-ex
      ```

      You should see the following output. You'll use the Amazon Resource Name (ARN) value from the output, `FunctionArn`, when creating the topic rule.

      ```
      {
          "FunctionName": "my-function",
          "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function",
          "Runtime": "python3.9",
          "Role": "arn:aws:iam::123456789012:role/lambda-ex",
          "Handler": "index.handler",
          "CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=",
          "Version": "$LATEST",
          "TracingConfig": {
              "Mode": "PassThrough"
          },
          "RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff",
          ...
      }
      ```

   1. To get logs for an invocation from the command line, use the `--log-type` option with the `invoke` command. The response includes a LogResult field that contains up to 4 KB of base64-encoded logs from the invocation. 

      ```
      aws lambda invoke --function-name my-function out --log-type Tail
      ```

      You should receive a response with a `StatusCode` of 200. For more information about creating and using Lambda functions from the AWS CLI, see [Using Lambda with the AWS CLI](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-awscli.html).

1. Create a topic rule

   Use the `CreateTopicRule` API or the `create-topic-rule` CLI command to create a topic rule that sends a message to this Lambda function. You can also add a second rule action that republishes to an AWS IoT topic. Name this topic rule as `Sidewalkrule`.

   ```
   aws iot create-topic-rule --rule-name Sidewalkrule \ 
       --topic-rule-payload file://myrule.json
   ```

   You can use the `myrule.json` file to specify more details about the rule. For example, the following JSON file shows how to republish to an AWS IoT topic and send a message to a Lambda function.

   ```
   {
       "sql": "SELECT * ",
       "actions": [
          {
               // You obtained this functionArn when creating the Lambda function using the 
               // create-function command.
               "lambda": {
                   "functionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function"
                }
           },
           {
               // This topic can be used to observe messages exchanged between the device and 
               // AWS IoT Core for Amazon Sidewalk after the device is connected.
                "republish": {
                    "roleArn": "arn:aws:iam::123456789012:role/service-role/SidewalkRepublishRole",
                    "topic": "project/sensor/observed"
                }
           }
       ],
   }
   ```