IoT, AWS, and the Amazon Dash Button

The internet of things or IoT in is simple way is the ability to connect any to device to internet. There are many uses for this but the most common one is to report state of the device.

With this post I want to show you how easy is to get started with IoT and start thinking on how IoT improve your business.

Amazon sells a IoT button . This button allows you after configure to sell an email to yourself. AWS offers a quick start wizard that takes cares of the creation registration and setup of the button. This is great if you want to get going in 15 minutes without understanding what is going on under the hood

This is what the button looks like


In this post I will show the code in Python 3, the current quick start is written in Node.js and I wanted to write the code in different language. I also will show you how to keep track of how many clicks are left, how to send an email using SNS topics, what IAM permissions are needed and at the how to kill all instances on the region.

One of the drawbacks of the button is that it only has battery for  2000 clicks. The device cost around $20 bucks.  DISCLAIMER YOU SHOULD THIS ON A LAB AWS ACCOUNT AS THE CODE TERMINATE INSTANCES IN YOUR ACCOUNT

AWS account
AWS IoT button
Some basic knowledge about IAM polices, Dynamo and Lambda

  1. We need to create a lambda function and choose author from scratch. Select a name, and for role choose create role from template. Select the AWS IoT Button permissions.
  2. Click on create function. Make the following changes, runtime Python3.6 an handler iot_blog.lambda_handler. Before saving copy this piece of code into the function.
    def lambda_handler(event, context):


  3. Under Environment type “email_address” for your key and then your email address in value
  4. Now lets click on triggers to create the IoT trigger. Click on Add Trigger, and choose AWS IoT.
  5. This will allow us to add our button and configure your button. This will register your button on the IoT hub in AWS and create the certificates to upload to your button.
    Your button has a DSN (device serial number)  on the back that needs to be enter. After that click on generate certificate keys.
  6. After you download the certificates hold the button for 5 seconds until is blinking blue. After that should you see a SSID called “Button ConfigureMe – 2DA”
  7. After you connect in your browser open new tab and go to the following link
    Get the following information from the page the subdomain, region and the password.
    Click save and if you button blink green without red is ready to be configured
  8. Go back to the AWS console, check on Enable trigger and submit. Now that you have created the trigger lets add additional policies to the role on IAM.
    Add the following policies
  9. Now that we have all setup, lets go back to the lambda and copy the the following code into your lambda.

import os
import logging #for proper function logging
import boto3
import time
logger = logging.getLogger()
personal_email = os.environ['email_address']
topic_name = 'aws-iot-button-sns-topic-python'
client_sns = boto3.client('sns')
client_dynamo = boto3.client('dynamodb')
resource_dynamo = boto3.resource('dynamodb')
client_ec2 = boto3.client('ec2')
list_instances = []
def create_sns_topic():
# This function is idempotent no need to manually check if topic already exits
response = client_sns.create_topic(Name=topic_name)
return response
# This funtion is called to create_sns_subscription check
# if the subscription is on Pending confirmaion or accepted
def find_existing_subscription(topic_arn_iot):
response = client_sns.list_subscriptions_by_topic(
TopicArn= topic_arn_iot
return response
# Create SNS topic to email specified on the envrron
def create_sns_subscription(topic_arn_iot):
state_subscription = find_existing_subscription(topic_arn_iot) # Function to check if subscriptopn exists
# If handles if subscription already exits or not
if not state_subscription['Subscriptions']:
response = client_sns.subscribe(
TopicArn= topic_arn_iot,
Protocol= 'email',
Endpoint = personal_email
return response
result_subscription = state_subscription['Subscriptions'][0]['SubscriptionArn']
if result_subscription == 'PendingConfirmation':
response= client_sns.subscribe(
return response
return response
except Exception as err:
logger.error('Program could not set proper subscription {}'.format(err))
#Send email with informatio about the IoT button
def email_subscription(topic_arn_iot, event, item_table_count, delete_instances):
item_table_count = 2000 item_table_count
Message="""{} — processed by Python 3.6 Lambda
Battery voltage: {}
There are {} clicks left.
The following instances were deleted {}""".format(event['serialNumber'], event['batteryVoltage'], item_table_count, delete_instances),
Subject="Hello from your IoT Button {}: {}".format(event['serialNumber'], event['clickType'])
)'Message sent')
except Exception as err:
logger.error('Could not send email please topic {}'.format(err))
#Creates dynamo table
def create_dynamo_table(event):
iot_button_count = event['serialNumber']
#Checks if table exist if not creates table
response_query = client_dynamo.list_tables()
if iot_button_count not in response_query['TableNames']:
response = client_dynamo.create_table(
'AttributeName': 'count',
'AttributeType': 'S'
'AttributeName': 'count',
'KeyType': 'HASH'
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
)"table created {}".format(response))
else:"table is already created {}".format(iot_button_count))
def create_item_dynamo(event):
iot_button_count = event['serialNumber']
unix_time = str(time.time())
TableName= iot_button_count,
Item= {
'count': {
'S': unix_time
response = resource_dynamo.Table(iot_button_count)
return response.scan()['ScannedCount']
def delete_ec2_intances():
response_ec2 = client_ec2.describe_instances()
if not response_ec2:
for reservation in response_ec2["Reservations"]:
for instance in reservation['Instances']:
list_instances.append(instance['InstanceId'])'intances to be deleted {}'.format(list_instances))
response = client_ec2.terminate_instances(
return list_instances
# Min point of entry to the function
def lambda_handler(event, context):'Starting Function')'The following payload was received')
# print infomation about the payload being passed
print('serial number {}'.format(event['serialNumber']))
print('batteryVoltage {}'.format(event['batteryVoltage']))
print('clickType {}'.format(event['clickType']))
print('email to be used {}'.format(personal_email))
#Calls function to create topic
topic_arn_iot = create_sns_topic()'Topic ARN is {}'.format(topic_arn_iot['TopicArn']))
#Calls function to create subscription
subscription = create_sns_subscription(topic_arn_iot['TopicArn'])
#Calls function to create dynamo_table
#Add events to dynamo table to keep track of click
item_table_count = create_item_dynamo(event)
#Delete any EC2 instances
delete_instances = delete_ec2_intances()
#Calls function to email data
email_subscription(topic_arn_iot['TopicArn'], event, item_table_count, delete_instances)

view raw

hosted with ❤ by GitHub

Should look like this

This is what the code above does

  1. Create a SNS topic in AWS
  2. Create a subscription based on the email address on the lambda environment file
  3. Creates a dynamo table to keep track of the number of clicks. The name of the table will match your device DSN

    In the table I am keeping the unix time each a person clicks on the button.

    4. Will delete any instances on the account. If you dont want for this to execute change line 159 to

    delete_instances = ‘no’

#Add events to dynamo table to keep track of click
item_table_count = create_item_dynamo(event)
#Delete any EC2 instances
delete_instances = 'no'
#Calls function to email data
email_subscription(topic_arn_iot['TopicArn'], event, item_table_count, delete_instances)

  1. Will send an email with the information collected that will look like this when you press the button on your IoT device



In summary this show you the potential of IoT and how is changing our lives. But more importantly that is within everybody’s reach and it is not rocket science

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s