Amazon AWS IoT Core and my fridge

We had problem with our fridge which was causing it to make stuff inside more cooler than expected. I thought of looking at its pattern of heating (at condenser) side so I can check how that causing any issues at cooling side. Though this may not be right way to diagnose the freeze, but I thought of trying my hands with Raspberry Pi + DHT 11 Sensor + AWS IoT Core.

Note that AWS IoT core is too much for this analysis, I might create the same analysis with Google Worksheet as well ( Which I might try next).

Raspberry Pi + DHT11 Sensor Connection :

Note that below instructions assumes that you have Raspberry pi with Raspbian OS already installed and you are aware how to connect to Raspberry pi via putty like software.

You can connect raspberry pi i/o pins with DHT11 sensor as below :

RBPI

 

 

 

 

 

 

To know more about Adafruit Library and how to use the same to capture Temperature and Humidity.

  1. Enter this at the command prompt to download the library:

git clone https://github.com/adafruit/Adafruit_Python_DHT.git

  1. Change directories with:

cd Adafruit_Python_DHT

  1. Now enter this:

sudo apt-get install build-essential python-dev

  1. Then install the library with:

sudo python setup.py install

Test the sensor with following python script (Make sure you create python script outside the ‘Adafruit_Python_DHT’ folder.

#!/usr/bin/python

import sys

import Adafruit_DHT

while True:

humidity, temperature = Adafruit_DHT.read_retry(11, 4)

print ‘Temp: {0:0.1f} C  Humidity: {1:0.1f} %’.format(temperature, humidity)

If above script shows output on command prompt of Raspberry Pi, then we are good with our hardware setup.

Set up AWS IoT Core :

Note : You need to have access to AWS portal for which you need to pay around INR 2 where you can get access for 1 year for free. Though there are few limitations with this free account.

  1. Goto IoT Core service and click on manage :1
  2. Register Single Thing2
  3. Create a single thing . Write name of thing with description.3
  4. Add type , here raspberry pi based sensor can be one type.4
  5. Create certificate for given thing. It is part of security bundle which requires to be added in raspberry pi.56
  6. Activate the certificate.7
  7. Device got created now.8
  8. Since thing is added , it requires to create bundle which would have all security certificate . So Interact –> Connect Device option.9-19-ConnetDevice
  9. Select OS as Linux and SDK as Python (for raspberry pi)1011
  10. Download connection kit , which is zip format. Unzip and then transfer to Raspberry pi via winscp (from your windows machine).13
  11. On AWS portal , you will get following screen , which is waiting for message from your sensor device.12
  12. Login to Raspberry Pi via putty and navigate to folder which has been transferred in previous steps. 14
  13. Note steps shown on AWS screen to change executable access for start.sh and try to execute the script.15
  14. You can see it downloads python SDK files along with one root certificate. But script fails to run actual python sample scripts. You can do that manually by executing command shown at end of start.sh script.

 

pushd aws-iot-device-sdk-python (This line gives error , which actually navigate control to aws-iot-device-sdk-python folder)

 python setup.py install

So navigate to aws-iot-device-sdk-python folder which is just got created via start script.

And run command

Sudo python setup.py install

Once above command got executed , navigate back to parent folder and run following command and run following command which appears in your start.sh script.

python aws-iot-device-sdk-python/samples/basicPubSub/basicPubSub.py -e xxxxxxxxxxx-ats.iot.ap-south-1.amazonaws.com -r root-CA.crt -c rbPi-2.cert.pem -k rbPi-2.private.key

16

You can see messages started coming onto AWS portal.

Press Done and navigate back to Monitor option. You can see connections have been shown.

17

Let us modify the existing python script to push temperature and humidity values to new topic

  • Use same command which you have used previously but with new command line option ‘-t ‘ with new topic which you would like to have .

sudo python aws-iot-device-sdk-python/samples/basicPubSub/basicPubSub.py -e xxxxxxxxxxxxxx.iot.ap-south-1.amazonaws.com -r root-CA.crt -c rbPi-2.cert.pem -k rbPi-2.private.key -t freeze/openclose

You shall get error as below.18

  • Let us fix this issue by updating policy in section Secure –> Policies. Just make sure you select correct policy for update.2021
  • Now after updating the policy try same command again and you can check the messages coming to given topic “freeze/openclose” by navigating to section Test –> Subscribe to a Topic22
  • Now update the temperature , humidity and timestamp values to be sent via python script. You have to create copy of sample python script as below and execute the same with all parameters as previous command
import datetime
import sys
import Adafruit_DHT
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import logging
import time
import argparse
import json

AllowedActions = ['both', 'publish', 'subscribe']
# Custom MQTT message callback
def customCallback(client, userdata, message):
    print("Received a new message: ")
    print(message.payload)
    print("from topic: ")
    print(message.topic)
    print("--------------\n\n")
# 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("-id", "--clientId", action="store", dest="clientId", default="basicPubSub",
                    help="Targeted client id")
parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic")
parser.add_argument("-m", "--mode", action="store", dest="mode", default="both",
                    help="Operation modes: %s"%str(AllowedActions))
parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!",
                    help="Message to publish")

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

if args.mode not in AllowedActions:

    parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions)))

    exit(2)

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 AWSIoTMQTTClient

myAWSIoTMQTTClient = None

if useWebsocket:

    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)

    myAWSIoTMQTTClient.configureEndpoint(host, port)

    myAWSIoTMQTTClient.configureCredentials(rootCAPath)

else:

    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)

    myAWSIoTMQTTClient.configureEndpoint(host, port)

    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration

myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)

myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing

myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz

myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec

myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT

myAWSIoTMQTTClient.connect()

if args.mode == 'both' or args.mode == 'subscribe':

    myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)

time.sleep(2)

# Publish to the same topic in a loop forever
loopCount = 0
while True:
    if args.mode == 'both' or args.mode == 'publish':
        ts = time.time()    #Get Current Time
        st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')  # Conver into particular format
        humidity, temperature = Adafruit_DHT.read_retry(11, 4)
        message = {}
        message['temperature'] = temperature
        message['humidity'] = humidity
        message['timestamp'] = st
        messageJson = json.dumps(message)
        myAWSIoTMQTTClient.publish(topic, messageJson, 1)
        if args.mode == 'publish':
            print('Published topic %s: %s\n' % (topic, messageJson))
    loopCount += 1
    time.sleep(10)

 

Note that newly added code is marked red for your reference.

You can navigate back to AWS portal to check values from sensor coming properly.

23

This blog is only providing steps to publish sensor values to AWS IoT core. Once you get the messages , you can add new business rules and AWS Analytics channel as well.

Please go through the AWS training to know more about the same.

IoT Foundation : Telemetry

https://www.aws.training/Details/eLearning?id=23507

Ref :

img-20190916-wa0007

I hope this blog would help you to get going with AWS IoT.  I have my makerspace which I run in my part time. If you like to visit and see what we do as part of our maker activities, then you are welcome.

Thanks,

Atul Yadav

2 thoughts on “Amazon AWS IoT Core and my fridge

    1. If you look at HVAC cycle, the temp of inside fridge (evaporator) and the temp of outside (condenser) are indicative of performance. I was just checking how many times condenser operates (by knowing the temp), I could plot cycle over time.
      To be honest, I am not able to draw any conclusion yet. This was just a try.

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.