This post is a tutorial to receive MQTT Message from W5100S-EVB-Pico and store it in DynamoDB. First, MQTT Message is received from IoT Core and processed according to the rule. This rule triggers Lambda, which allows the MQTT message to be stored in DynamoDB. Data is stored in a DynamoDB Table through this Lambda.
- Select "Create single thing"
- Create and connect a policy for using IoT Core.
{
"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": "*"
}
]
}
2. Publish MQTT Message- I used a repository that connects the RP2040 and AWS.
- I changed the thing name to the thing name created above.
/* 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"
- Message payload:
{"temperature":23, "humidity":25}
3. Save MQTT Message in DynamoDB Table3.1. Create DynamoDB Table
3.2. Create Lambda
- Deploy index.js after changing the contents below.
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"}
}
});
}
3.3. Create IoT Rule
- Create rule and rule enabled.
3.4. Check DynamoDB Table
Comments