I'm learning about AWS services and I'm attempting to create a data pipeline from my ESP32 (photoresistor data) to DynamoDB.
I have created a rule that takes incoming MQTT messages from my ESP32 and triggers a lambda function that pushes the data to my DynamoDB.
I have it working for hardcoded values in the lambda function, but how can I modify the following code to read in real-time sensor data from the ESP32?
Here is the lambda code (node.js):
const AWS = require("aws-sdk");
const ddb = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'});
exports.handler = async (event, context, callback) => {
// Captures the requestId from the context message
const requestId = context.awsRequestId;
// Handle promise fulfilled/rejected states
await createMessage(requestId).then(() => {
callback(null, {
statusCode: 201,
body: '',
headers: {
'Access-Control-Allow-Origin' : '*'
}
});
}).catch((err) => {
console.error(err)
})
};
// Function createMessage
// Writes message to DynamoDb table Message
function createMessage(requestId) {
const params = {
TableName: 'my-ddd-data',
Item: {
'partKey' : requestId,
'Dropouts': "67476", // this is successfully sent to my database but I'd like real time sensor data
'Runtime' : "0 mins"
}
}
return ddb.put(params).promise();
}
The json format of the data being fed to this lambda function:
{
"Dropouts": "1",
"Runtime": "0 mins"
}
CodePudding user response:
Please, consider logging your event and see how it looks like. Probably it will contain the JSON information from your sensor. I think you could directly pass that information to DynamoDB:
const AWS = require("aws-sdk");
const ddb = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'});
exports.handler = async (event, context, callback) => {
// Log your event, and see how it looks like
console.log('Event\n', JSON.stringify(event))
// Captures the requestId from the context message
const requestId = context.awsRequestId;
// Handle promise fulfilled/rejected states
// Pass the event that is being processed
await createMessage(requestId, event).then(() => {
callback(null, {
statusCode: 201,
body: '',
headers: {
'Access-Control-Allow-Origin' : '*'
}
});
}).catch((err) => {
console.error(err)
})
};
// Function createMessage
// Writes message to DynamoDb table Message
function createMessage(requestId, event) {
const params = {
TableName: 'my-ddd-data',
Item: {
'partKey' : requestId,
'Dropouts': event['Dropouts'], // read values from the event
'Runtime' : event['Runtime']
}
}
return ddb.put(params).promise();
}
Although implemented in Python, I think this tutorial from the Amazon documentation could be of help as well.