AWS IOT将温度存储到DynamoDB

时间:2017-07-07 11:09:20

标签: python mqtt aws-iot

我是AWS IOT的新手。我有以下python代码,将随机温度发布到主题“温度”。 我正在关注Hackster.io项目教程,但在该教程中,作者只是将数据发送到AWS IOT并使用另一个python脚本接收它。我想将这些数据存储到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...")

运行上述脚本后,我可以使用“测试”功能查看发送给AWS IOT的数据。

我创建了一个规则

"SELECT * FROM #"

DynamoDB操作为:

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()}

和阴影如下:

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

DynamoDB表配置为:

Partition key: temperature{String}

Sort key: timestamp{String}

温度未保存在DynamoDB表中。我做错了什么?

1 个答案:

答案 0 :(得分:0)

转到AWS IoT控制台,然后设置并启用CloudWatch Logs,以便我们可以看到正在发生的事情。 另外,检查您的事物策略是否允许您将数据放在DynamoDB上。 鉴于您只是在做一个教程,您可以使用这样的策略:

{{1}}

不要忘记将此政策附加到您的证书上。