Exploring IoT: Utilizing the Rules Engine with Amazon SNS

Chanci Turner Amazon IXD – VGT2 learningLearn About Amazon VGT2 Learning Manager Chanci Turner

Welcome to another edition of our Bites of IoT blog series. In this post, we will demonstrate how to leverage the AWS IoT rules engine to filter and direct messages to Amazon Simple Notification Service (Amazon SNS). Our example will illustrate sending a text message to a phone number when a virtual doorbell is activated.

Key Concepts

The rules engine serves as a crucial component in your IoT solution, allowing for actions based on device messages, such as filtering, routing to other services, and direct message processing. When AWS IoT is combined with Amazon SNS, you can dispatch near real-time notifications based on physical world changes detected by your IoT devices. These notifications can be:

  • Sent to technicians or system operators for necessary human intervention.
  • Integrated into existing ticketing systems.
  • Initiated to trigger automated workflows.

Setting Up the Command Line Interface (CLI)

As with previous Bites of IoT articles, we will utilize the AWS IoT ELF client available on GitHub in AWS Labs. If you’re not yet familiar with the ELF, consider reviewing the first post in this series.

We’ll begin by creating the Amazon SNS topic and the AWS IoT rule through the AWS CLI. Ensure your CLI profile has the following permissions, replacing “012345678901” with your own AWS account ID:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sns:CreateTopic",
                "sns:SetTopicAttributes",
                "sns:Subscribe",
                "sns:Publish",
                "sns:DeleteTopic",
                "iot:CreateTopicRule",
                "iot:DeleteTopicRule",
                "iam:AttachRolePolicy",
                "iam:CreatePolicy",
                "iam:CreateRole",
                "iam:DetachRolePolicy",
                "iam:DeletePolicy",
                "iam:DeleteRole"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::012345678901:role/*"
            ]
        }
    ]
}

Establishing Local Directories

If you’ve followed the steps in the Getting Started guide, you should have a local directory structure at ~/dev/aws-iot-elf (where “~” denotes your home directory). Each Bites of IoT post will require specific local files, so let’s create a directory for this purpose. On Linux or Mac OS, execute:

cd ~/dev
mkdir bites
cd ~/dev/bites 
mkdir sns
cd ~/dev/bites/sns

With the development environment prepared, let’s proceed.

Creating the SNS Topic

Next, we will create the Amazon SNS topic that the AWS IoT rules engine will use to send notifications. Run the following AWS CLI commands to create and name the topic, ensuring you substitute “012345678901” with your AWS account ID.

aws sns create-topic --region us-west-2 --name door-alert
aws sns set-topic-attributes --region us-west-2 --topic-arn arn:aws:sns:us-west-2:012345678901:door-alert --attribute-name DisplayName --attribute-value DOORBELL

Note: The DisplayName value “DOORBELL” will appear as the sender when you receive notifications on your mobile device.

Next, subscribe your mobile number to the topic using this CLI command, replacing “1-012-345-6789” with your actual phone number to receive alerts when the virtual doorbell is rung:

aws sns subscribe --region us-west-2 --topic-arn arn:aws:sns:us-west-2:012345678901:door-alert --protocol sms --notification-endpoint 1-012-345-6789

To verify the subscription, you can use this command:

aws sns publish --region us-west-2 --message "A Bite of Hello" --topic-arn arn:aws:sns:us-west-2:012345678901:door-alert

Setting Permissions for Amazon SNS

Before we create the IoT rule, we need to establish an IAM role that the AWS IoT rules engine will assume to securely publish messages to Amazon SNS. Start by preparing a trust policy that permits AWS IoT to assume the role. Save the following trust policy document in a file named iot-role-trust.json:

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

Run this CLI command to create the role:

aws iam create-role --role-name iot_sns_role --assume-role-policy-document file://iot-role-trust.json

AWS IoT will also need permission to publish to the Amazon SNS topic we created. Copy and paste the following IAM policy document into a new file named iot-policy.json:

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sns:Publish",
        "Resource": "arn:aws:sns:us-west-2:012345678901:door-alert"
    }
}

Execute this command to create the policy:

aws iam create-policy --policy-name iot_sns_policy --policy-document file://iot-policy.json

Then, run this command to attach the policy to the role:

aws iam attach-role-policy --role-name iot_sns_role --policy-arn arn:aws:iam::012345678901:policy/iot_sns_policy

Configuring the AWS IoT Rule

Now, we can create the AWS IoT rule that will trigger a text alert upon ringing the bell. This rule will send every message from the doorbell topic to Amazon SNS. Copy and paste the following rule definition into a file named sns-rule.json:

{
  "sql": "SELECT * FROM 'doorbell/+'",
  "description": "Sends a message to SNS when a message comes across the 'doorbell' topic",
  "actions": [
    {
      "sns": {
        "targetArn":"arn:aws:sns:us-west-2:012345678901:door-alert",
        "roleArn":"arn:aws:iam::012345678901:role/iot_sns_role",
        "messageFormat": "RAW"
      }
    }
  ],
  "ruleDisabled": false
}

Remember to replace “012345678901” in the rule with your AWS account ID. Finally, use this command to create the rule:

aws iot create-topic-rule --region us-west-2 --rule-name sendToSNS --topic-rule-payload file://sns-rule.json

Simulating the Doorbell

Everything is now set up to ask the ELF to trigger the virtual doorbell. Switch to the AWS IoT ELF directory and retrieve the latest version:

cd ~/dev/aws-iot-elf
git pull

Activate the ELF’s virtual environment using:

source ~/dev/aws-iot-elf/venv/bin/activate

For Windows users:

.venvScriptsactivate

Create a thing in AWS IoT service to act as our doorbell:

python elf.py --region us-west-2 create 1

Now, the following command will send a message on the topic as if the ELF pushed the virtual doorbell button:

python elf.py --region us-west-2 send --duration 1 --topic 'doorbell' 'Somebody is at the door!'

Shortly thereafter, you should receive a text message resembling this:
DOORBELL> {"msg": "Somebody is at the door!", "ts": "1468958915.41"}

Cleaning Up

To tidy up your environment, you can use the following commands:

python elf.py --cleanup

For more insights on structuring your resume effectively, check out this blog post. Additionally, for an authoritative take on employer costs for employee compensation, refer to this resource. Lastly, if you’re interested in training and onboarding in Amazon’s warehouses, this article is an excellent resource.

Chanci Turner