이 포스팅은 W5100S-EVB-Pico로부터 MQTT Message를 받아서 이를 DynamoDB에 저장하는 튜토리얼입니다. 먼저 MQTT Message를 IoT Core에서 받아서 rule에 따라 처리됩니다. 이 rule은 MQTT Message를 DynamoDB에 저장하게 해주는 Lambda를 트리거 해줍니다. 이 Lambda를 통해서DynamoDB Table에 데이터가 저장됩니다.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "iot:Connect",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Receive",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": "*"
}
]
}
/* AWS IoT */
#define MQTT_DOMAIN "account-specific-prefix-ats.iot.ap-northeast-2.amazonaws.com"
#define MQTT_PUB_TOPIC "$aws/things/my_rp2040_thing/shadow/update"
#define MQTT_SUB_TOPIC "$aws/things/my_rp2040_thing/shadow/update/accepted"
#define MQTT_USERNAME NULL
#define MQTT_PASSWORD NULL
#define MQTT_CLIENT_ID "my_rp2040_thing"
{"temperature":23, "humidity":25}
Function name 설정하고, Runtime은 Node.js 선택 후 생성.
index.js를 아래의 내용을 변경 후 deploy 해줍니다.
console.log('Loading function');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
const collection ="RawDataTbl" // DB Table Name
function addHours(date, hours) {
const newDate = new Date(date);
newDate.setHours(newDate.getHours() + hours);
return newDate;
}
const deleteTime = addHours(Date.now(), 12) // DynamoDB TTL
// Handler lamda function
exports.handler = function(event, context) {
console.log('Received event:', JSON.stringify(event, null, 2));
const params = {
TableName: collection,
Item:{
"deviceId": event.clientId, // = thing Name
"createTime": event.timestamp,
"deleteTime": Math.floor(deleteTime / 1000),
"payload": event.payload // MQTT Message
}
};
console.log("Saving Telemetry Data");
dynamo.put(params, function(err, data) {
if (err) {
console.error("Unable to add Data. Error JSON:", JSON.stringify(err, null, 2));
context.fail();
} else {
console.log(data)
console.log("Data saved:", JSON.stringify(params, null, 2));
context.succeed();
return {"message": "Item created in DB"}
}
});
}
SELECT * as payload, clientId() as clientId, timestamp() as timestamp FROM '$aws/things/picoThing/shadow/update'