我正在通过MQTT协议将Raspberry PI的温度数据保存到Amazon DynamoDB。这是我的数据库的布局:
我设法设置lambda函数来读取并将每个新的db条目作为JSON消息发送回mqtt。所以它可以由用户阅读:
我想要达到的目的是在到达时仅提取温度值。转换为整数类型并简单检查温度是否低于或高于阈值,并根据该检查发送消息打开或关闭到mqtt。然后mqtt特定主题将读取消息(打开或关闭),并将打开或关闭LED(加热器模拟器)
所以我要求的是帮助从dynamodb中提取温度场。我应该休息,希望...
多谢你们!
import boto3
import json
client = boto3.client('iot-data', region_name='eu-west-1')
dynamo = boto3.resource('dynamodb')
table = dynamo.Table('mqtt_table')
# Change topic, qos and payload
def lambda_handler(event, context):
response = table.scan()
body = json.dumps(response['Items'])
response = client.publish(
topic='mytopic/iot2',
qos=1,
payload=body
)
如果您只想获取temperature
字段的值,请尝试以下操作:
for item in response['Items']:
temperature = float(item['temperature'])
这应该将float中的温度值存储在变量中。
---更新03/05/2018 ---
如果要在将项添加到DynamoDB表后立即读取它,请创建DynamoDB触发器。文档可以找到here。您的lambda函数代码应如下所示:
import json
def lambda_handler(event, context):
print json.dumps(event, default=str)
for record in event['Records']:
temperature = record['dynamodb']['NewImage']['temperature']['S']
# temperature variable contains the value of temperature of the item added to the DynamoDB table.
print temperature
# If you need to do something else, please do it here...
return 'Completed'