Recently, Amazon announced AWS IoT, a new platform that makes it easy for devices — cars, turbines, sensor grids, light bulbs, and more – to connect to AWS services so that companies can store, process, analyze, and act on the volumes of data generated by connected devices on a global scale.

In this topic, we will see how you can connect your devices or 'things' in this case Raspberry Pi --> AWS IoT platform using MQTT protocol.

Connecting to AWS IoT involves quite a few steps before your device can be configured and will be able to send and receive messages.Let us go through each of these steps -

1. To begin it from IoT Portal, we need to first sign in to AWS Management console

AWS IoT Portal

A. Click on Get started

Get started

2. Create, Download and Activate Certificate

Every Devices connecting to AWS IoT must have a valid certificates. In this step, we will generate, download and activate the certificates through AWS IoT console.

B. Click on Create a resource button

Create a resource

C. Now, select Create a certificate option and then click on Click certificate create button as shown in screenshot below -

Create a certificate

D. Download all the keys & the certificates

Download certificates

E. To activate already created certificate, select particular certificate and then Activate it from the Actions menu.

Activate Certificate

F. After activation is done from the Actions menu, your certificate will appear as Active

Active Certificate

3. Creating a Raspberry Pi Thing

After the certificates are downloaded and activated; we need to create the thing. Thing is the actual device (in our case Raspberry Pi ) which will be connected to AWS IoT. For now, you may imagine it as a placeholder for our device.

G. Click on Create a resource button

Create a resource

H. Select Create a thing option and fill in the desired name for thing. In this case “raspberry-pi”. Then, Click on Create button.

Create a thing

I. To view the details of newly created thing click on View thing button

View thing

J. You can see details of thing on the right side as in screenshot below -

Details of thing

4. Attaching the Thing with certificate

After creating the thing we need to attach it to our generated certificates.

K. To attach a thing with the certificate we need to select a certificate and then Attach a thing from the Actions menu.

Attach a thing

L. Click on Attach a thing opens a pop-up box, enter the name of thing and click on attach button.

Click Attach a thing

5. Connect Raspberry Pi to AWS IoT

We just performed AWS IoT setup and now ready to our Raspberry pi to it. As an example, we are using the following device configuration:

  • Raspberry Pi Model B ( 700MHz, 512Mb RAM ) with Raspbian GNU/Linux 8 (jessie) as its operating system.
  • Programming Language: Python v3.4.2
  • Required Libraries: Paho MQTT Python Client. You can get it from https://eclipse.org/paho/clients/python/

M. Creating an IOT MQTT subscriber in python

You can find a ready script i.e. “iot-mqtt-subscriber.py” for AWS IoT MQTT Subscriber This subscriber will listen to AWS IoT topic for messages. Before you use the script, copy the generated and downloaded certificate, private key and root certificate (pre-obtained in Step-D) to the Raspberry PI:

#!/usr/bin/python3

#required libraries
import sys                                 
import ssl
import paho.mqtt.client as mqtt

#called while client tries to establish connection with the server
def on_connect(mqttc, obj, flags, rc):
    if rc==0:
        print ("Subscriber Connection status code: "+str(rc)+" | Connection status: successful")
    elif rc==1:
        print ("Subscriber Connection status code: "+str(rc)+" | Connection status: Connection refused")

#called when a topic is successfully subscribed to
def on_subscribe(mqttc, obj, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos)+"data"+str(obj))

#called when a message is received by a topic
def on_message(mqttc, obj, msg):
    print("Received message from topic: "+msg.topic+" | QoS: "+str(msg.qos)+" | Data Received: "+str(msg.payload))

#creating a client with client-id=mqtt-test
mqttc = mqtt.Client(client_id="mqtt-test")

mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message

#Configure network encryption and authentication options. Enables SSL/TLS support.
#adding client-side certificates and enabling tlsv1.2 support as required by aws-iot service
mqttc.tls_set("/home/username/root-CA.crt",
                certfile="/home/username/6fdda68178-certificate.pem.crt",
                keyfile="/home/username/6fdda68178-private.pem.key",
              tls_version=ssl.PROTOCOL_TLSv1_2,
              ciphers=None)

#connecting to aws-account-specific-iot-endpoint
mqttc.connect("A2DL8ZE59089FKF.iot.us-west-2.amazonaws.com", port=8883) #AWS IoT service hostname and portno

#the topic to publish to
mqttc.subscribe("$aws/things/mqtt-listener/shadow/update/#", qos=1) #The names of these topics start with $aws/things/thingName/shadow."

#automatically handles reconnecting
mqttc.loop_forever()

Make sure you have following artifacts in place -

  • AWS IoT certificate. Eg. /home/user/cert.pem
  • AWS IoT private key. Eg: /home/user/thing-private-key.pem
  • Root CA certificates that are trusted. Download the root CA certificate file from root certificate. Eg: /home/user/rootCA.pem
  • You also need to note down you AWS IoT Endpoint from left panel. Eg: A2DL8ZE59089FKF.iot.us-west-2.amazonaws.com.
  • Port to use on the service host. Eg: 8883 ( default port no )
  • MQTT Quality of Service (QoS) level
  • Topic (thing name) to publish to. The names of AWS IoT MQTT topics start with “$aws/things/raspberry-pi/shadow”.
  • Client ID

N. To initiate listening to the topic run the script you just created “iot-mqtt-subscriber.py” using

python3 iot-mqtt-subscriber.py          

The messages received by the subscriber will be shown on the console. If everything works well then you should be able to see the status of device on IoT console.

Device Connected

Raspberry Device Connected

That's it! Your Raspberry pi is connected to AWS IoT.


You may visit our website for ready IoT Connect solution built with Flint IT Automation Platform'

Flint is free to use. Download it today!

Next Post Previous Post