2017-07-07 136 views
0

我是AWS IOT的新用戶。我有以下python代碼,將隨機溫度發佈到主題「溫度」。 我正在關注Hackster.io項目教程,但在該教程中,作者只是將數據發送到AWS IOT並使用其他Python腳本接收數據。我想將這些數據存儲到DynamoDB中。AWS IOT將溫度存儲到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表中。我究竟做錯了什麼?

回答

0

轉到AWS IoT控制檯,然後設置並啓用CloudWatch Logs,以便我們可以看到發生了什麼。 另外,檢查您的事情政策是否允許您將數據放入DynamoDB。 既然你只是做一個教程,你可以使用這樣的策略:

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

不要忘了這個策略附加到您的證書。