如何将传感器数据从我的 ESP32 读取到 DynamoDB?

How can I read in sensor data from my ESP32 to DynamoDB?

我正在学习 AWS 服务,我正在尝试创建从我的 ESP32(光敏电阻数据)到 DynamoDB 的数据管道。

我创建了一个规则,从我的 ESP32 接收传入的 MQTT 消息并触发一个 lambda 函数,将数据推送到我的 DynamoDB。

我在 lambda 函数中使用硬编码值,但我如何修改以下代码以从 ESP32 读取实时传感器数据?

这是 lambda 代码 (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();
}

提供给此 lambda 函数的数据的 json 格式:

{
  "Dropouts": "1",
  "Runtime": "0 mins"
}

请考虑记录您的事件并查看它的外观。可能它将包含来自您的传感器的 JSON 信息。我认为您可以直接将该信息传递给 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();
}

虽然在 Python 中实现,但我认为亚马逊文档中的 this tutorial 也可能有所帮助。