Tutorial on AWS IoT Core with Raspberry Pi to visualize sensor data

by Mar 27, 2020IoT Cloud, Projects, Raspberry Pi

In this tutorial, we will learn how to build an IoT application using the AWS Cloud Platform. The application will get sensor data from the Raspberry Pi and send it to the AWS IoT Core. This data will be stored in IoT Analytics and plotted in a graph using QuickSight.

Contents

  1. Hardware Requirements
  2. Initial Setup
  3. Setting up AWS IoT Core
  4. Setting up the Raspberry Pi
  5. Creating a rule for IoT Core
  6. Testing your rule
  7. Setting up Amazon QuickSight for visualization

1. Hardware Requirements

  1. Raspberry pi 3
  2. Light Dependent Resistor (or any sensor)
  3. 1 μf capacitor
  4. Breadboard
  5. Jumper cables

NOTE: You can use any sensor you like. Here we will be using the LDR as an example.

2. Initial Setup

  1. You will have to first create an AWS account. (This process requires your credit card details to verify that you are not a robot.)

NOTE: You can use the free trial to follow this tutorial.

3. Setting up AWS IoT Core

  1. In the search bar present at the AWS Management Console page search for “IoT Core” and click it.
IoT core search
  1. Once the IoT Core page opens, on the left menu you will see an option called “Manage”, under this select “Things”.
thing bar
  1. In the “Things” page click on “Register a Thing”.
create a thing
  1. Click on the button that says “Create a Single Thing”.
create a single thing
  1. Give your new “Thing” a name and click on next I’ll call mine “light-sensor”.
name your thing
  1. Next, we’ll create the keys and certificates required to authenticate our requests to AWS. For this click on the “Create Certificate” button. We will be using the one-click certificate creation method.
create a certificate
  1. Once your certificates and keys are created you will get an option to download them. Download the 4 documents, we will need them while setting up the Raspberry Pi.
download certificates
  1. When you try to download the root CA certificate you will be taken to a page as shown below. Choose the “RSA 2048 bit key” under “Amazon Trust Services Endpoints (preferred)”. A new tab will open. Copy the contents of that page and paste it into a file called “root-CA.crt”.
download root-CA
  1. Once you have downloaded all the required certificates click on “Activate” and then click “Done”.
Activate the certs
  1. Next, under the “Secure” section on the menu present on the left side, select the “Policies” option.
policy tab
  1. In the policies page click on the Create a policy” button.
create policy
  1. Give the policy a name and then fill the “Action” with iot:* and “Resource ARN” with * and also select “Allow” under effect. Finally, click on “Create”.
policy statement
  1. Now we have to attach our “Thing” and “Policy” to our “Certificate”. To do this follow the steps in the short video below.

4. Setting up the Raspberry Pi

  1. Make all the connections required to run the photocell as shown in the diagram below.
real image

For a more detailed tutorial on the LDR click here

  1. First, let us create a directory, in the Raspberry Pi, that we will be working in called “tryAWS” and cd into it.
mkdir tryAWS
cd tryAWS
  1. Now lets create a virtual environment and activate it.
virtualenv venv
source venv/bin/activate
  1. Now we are ready to install the required packages.
pip install Rpi.GPIO
pip install AWSIoTPythonSDK
  1. Create a python script called “ldr_data.py” and save the below code in it. This is the function that returns brightness data. You can replace it with the code for the sensor that you are using.

You can also get the code from GitHub here

#measuring the light intensity using a photocell
import RPi.GPIO as GPIO,time,os #import the libraries
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
def RCtime(RCpin):   # function start
    reading=0
    GPIO.setup(RCpin,GPIO.OUT)
    GPIO.output(RCpin,GPIO.LOW)
    time.sleep(4) # time to discharge capacitor
    GPIO.setup(RCpin,GPIO.IN)
    while (GPIO.input(RCpin) == GPIO.LOW): 
 # the loop will run till the capacitor  is charged
        reading += 1                                
 # measuring time which in turn is measuring resistance
    return reading                               


  1. Next, save the following python script in a file called “basicShadowUpdater.py”. This is the script that will use MQTT to update the “Shadow” of the “Thing”.
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import logging
import time
from datetime import datetime
import json
import argparse
import ldr_data

# Custom Shadow callback
def customShadowCallback_Update(payload, responseStatus, token):
    # payload is a JSON string ready to be parsed using json.loads(...)
    # in both Py2.x and Py3.x
    if responseStatus == "timeout":
        print("Update request " + token + " time out!")
    if responseStatus == "accepted":
        payloadDict = json.loads(payload)
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Update request with token: " + token + " accepted!")
        print("brightness: " + str(payloadDict["state"]["desired"]["brightness"]))
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
    if responseStatus == "rejected":
        print("Update request " + token + " rejected!")

def customShadowCallback_Delete(payload, responseStatus, token):
    if responseStatus == "timeout":
        print("Delete request " + token + " time out!")
    if responseStatus == "accepted":
        print("~~~~~~~~~~~~~~~~~~~~~~~")
        print("Delete request with token: " + token + " accepted!")
        print("~~~~~~~~~~~~~~~~~~~~~~~\n\n")
    if responseStatus == "rejected":
        print("Delete request " + token + " rejected!")

# Read in command-line parameters
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint")
parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path")
parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path")
parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path")
parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override")
parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False,
                    help="Use MQTT over WebSocket")
parser.add_argument("-n", "--thingName", action="store", dest="thingName", default="Bot", help="Targeted thing name")
parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicShadowUpdater", help="Targeted client id")

args = parser.parse_args()
host = args.host
rootCAPath = args.rootCAPath
certificatePath = args.certificatePath
privateKeyPath = args.privateKeyPath
port = args.port
useWebsocket = args.useWebsocket
thingName = args.thingName
clientId = args.clientId

if args.useWebsocket and args.certificatePath and args.privateKeyPath:
    parser.error("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.")
    exit(2)

if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath):
    parser.error("Missing credentials for authentication.")
    exit(2)

# Port defaults
if args.useWebsocket and not args.port:  # When no port override for WebSocket, default to 443
    port = 443
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883

# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTShadowClient
myAWSIoTMQTTShadowClient = None
if useWebsocket:
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId, useWebsocket=True)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient(clientId)
    myAWSIoTMQTTShadowClient.configureEndpoint(host, port)
    myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTShadowClient configuration
myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

# Create a deviceShadow with persistent subscription
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)

# Delete shadow JSON doc
deviceShadowHandler.shadowDelete(customShadowCallback_Delete, 5)

# Update shadow in a loop
loopCount = 0
while True:
    brightness = ldr_data.RCtime(12)
    timestamp = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
    JSONPayload = '{"state":{"desired":{"time":"' + str(timestamp) + '","brightness":'+str(brightness) +'}}}'
    print("\n", JSONPayload,"\n")
    deviceShadowHandler.shadowUpdate(JSONPayload, customShadowCallback_Update, 5)
    loopCount += 1
    time.sleep(1)

  1. Now move all the certificates that you downloaded into this directory. At the moment your working directory should look something like this.
directory tree
  1. Now we need to find your “endpoint”, for that go to Manage>Things>(your thing)>interact in the AWS IoT core console.
endpoint
  1. Now, to run the python script you will have to pass the following arguments :
    • -e endpoint
    • -r root CA
    • -c Certificate file path
    • -k private key file path
    • -p port (we will be using 8883)
    • -n targeted thing name
    • -id targeted client id
  1. Run the command. It should look something like this:
run script
  1. You should see an output like this:
output
  1. You can also check it on the AWS console. Go to Manage>Things>(your thing)>Shadow, it should look like this.
shadow output

5. Creating a rule for IoT Core

  1. In the IoT Core menu, select “Rules” under the “Act” category.
rule option in menu
  1. Click on “Create a rule”.
create rule
  1. Enter a name and a short description for the new rule that we have created.
name the rule
  1. In the rule Query statement enter the following :
SELECT cast(state.desired.brightness as decimal) as brightness, timestamp() as timestamp FROM '$aws/things/light-sensor/shadow/update'
  1. Now click on add action under “Set one or more actions” and choose “Send a message to IoT Analytics”, then click “Configure action”.
select IoT analytics
  1. Select “Quick Create IoT Analytics Resource” and enter a resource prefix and click “Quick Create”.
add prefix
  1. Click on “Add Action”.
configure aciton
  1. Then finally click “Create Rule”.

6. Testing your rule

  1. Run the python script in your Raspberry Pi for a few iterations.
  2. Open the IoT Analytics page and go to “Data Sets”.
dataset page
  1. Now click the three dots beside your data set and choose “run now”.
run now
  1. You should see the required data in the result preview.
data review

7. Setting up Amazon QuickSight for visualization

  1. In the search bar present in the AWS Management Console, search for “QuickSight” and select the option.
search result QuickSight
  1. Then in the page that opens select “Sign up For QuickSight”.
sign up for QuickSight
  1. In the options given for the plans choose “standard”, as that is enough for this tutorial. After that click on continue.
choose plan
  1. In this page enter an account name and make sure to select the box that says “AWS IoT Analytics” and also choose the same “region” you used to set up IoT Analytics. Then click “Finish”.
Choose region
  1. Once you are into Quicksight click on the “Create New Analysis” button.
select new analysis
  1. Then click on “New Dataset”.
new dataset
  1. Choose the “AWS IoT Analytics” data source.
select IoT analytics
  1. Choose your “Dataset” and then click on “Create data source”.
select your dataset
  1. Then, click on “Visualize”.
click visualize
  1. Under visual types choose your preferred “Visual Type”. We will be using “line chart” and drag & drop your data into the respective axes. In this example I have moved the “timestamp” into the x axis box and “brightness” into the y axis box.
sample graph
  1. You can also change the aggregate by opening the drop-down menu of the field.
change aggregate

You now have your sensor data from the Raspberry Pi plotted graphically using QuickSight on AWS cloud.

I hope you have a clear understanding of how we can use the AWS IoT core and IoT Analytics to plot the sensor data. Any feedback or questions are welcome, leave them in the comments section below.

Creating a multiplication Skill in Alexa using python

Written By Sashreek Shankar

Hey reader! I am Sashreek, a 16 year old programmer who loves Robotics, IoT and Open Source. I am extremely enthusiastic about the Raspberry Pi and Arduino hardware as well. I also believe in sharing any knowledge I have so feel free to ask me anything 🙂

RELATED POSTS

Creating REST API CRUD with Node.js, Express and MongoDB

Creating REST API CRUD with Node.js, Express and MongoDB

In our previous blog, we explored the fundamentals of creating a REST API with in-memory CRUD operations using Node.js and Express. Now, we're taking a significant step forward by integrating our product data with a database. This transition is pivotal for achieving...

How to create REST API using Node.js and Express?

How to create REST API using Node.js and Express?

In the vast landscape of web development, creating a robust API is a fundamental skill. APIs, or Application Programming Interfaces, serve as the communication bridge between different software applications. Today, we'll embark on a journey to build a simple blog API...

APIs Vs. Microservices: What is the difference?

APIs Vs. Microservices: What is the difference?

You've probably heard two extravagant terms thrown around when discussing software design and integrations: APIs and microservices. Both topics are important in web application development and design nowadays, and their applications overlap. In this article, we will...

How to Simulate IoT projects using Cisco Packet Tracer

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

Understanding Salesforce IoT and Its Importance

Understanding Salesforce IoT and Its Importance

In this post, we are going to discuss Salesforce IoT. All across the globe, people are connecting to the Internet to access information, communicate with other people, and do business. But it's not just people that are using the Internet: objects use it too....

How to design a Wireless Blind Stick using  nRF24L01 Module?

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....