0
votes

I'm new to AWS IOT. I have the following python code that posts random temperature to the topic "temperature". I am following a Hackster.io project tutorial, but in that tutorial, the author is just sending data to AWS IOT and receiving it using another python script. I would like to store this data into DynamoDB.

import paho.mqtt.client as paho
import os
import socket
import ssl
from time import sleep
from random import uniform

connflag = False

def on_connect(client, userdata, flags, rc):
    global connflag
    connflag = True
    print("Connection returned result: " + str(rc) )

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

#def on_log(client, userdata, level, buf):
#    print(msg.topic+" "+str(msg.payload))

mqttc = paho.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
#mqttc.on_log = on_log

awshost = "data.iot.eu-west-1.amazonaws.com"
awsport = 8883
clientId = "myThingName"
thingName = "myThingName"
caPath = "aws-iot-rootCA.crt"
certPath = "cert.pem"
keyPath = "privkey.pem"

mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

mqttc.connect(awshost, awsport, keepalive=60)

mqttc.loop_start()

while 1==1:
    sleep(0.5)
    if connflag == True:
        tempreading = uniform(20.0,25.0)
        mqttc.publish("temperature", tempreading, qos=1)
        print("msg sent: temperature " + "%.2f" % tempreading )
    else:
        print("waiting for connection...")

After running the above script, I am able to view the data that it is sending to AWS IOT using the "Test" function.

I have created a rule as

"SELECT * FROM #"

a DynamoDB action as :

Table name : temperature

Hash key: temperature

Hash key type: STRING

Hash key value: ${temperature()}

Range key: timestamp

Range key type: STRING

Range key value: ${timestamp()}

and a shadow as follows:

https://c1.staticflickr.com/5/4259/35723809136_d968acf299_o.png

The DynamoDB table is configured as:

Partition key: temperature{String}

Sort key: timestamp{String}

The temperature is not getting saved in the DynamoDB table. What am I doing wrong?

1

1 Answers

0
votes

Go to the AWS IoT console, then settings and enable CloudWatch Logs so we can see what is going on. Also, check if your thing policy gives you permission to put data on DynamoDB. Given that you are only doing a tutorial, you can use a policy like this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "iot:*"
      ],
      "Resource": [
        "*"
      ],
      "Effect": "Allow"
    }
  ]
}

Don't forget to attach this policy to your certificate.