Skip to content

Instantly share code, notes, and snippets.

@jameshi16
Created September 5, 2019 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameshi16/851dc9de904811c1b2304cfc1f819f1d to your computer and use it in GitHub Desktop.
Save jameshi16/851dc9de904811c1b2304cfc1f819f1d to your computer and use it in GitHub Desktop.
[Mine] ESP32 -> AWS IoT -> DynamoDB via MQTT WiTh AWS Lambda
/* Env translated constants */
const TABLE_NAME = process.env.TABLE_NAME;
const IOT_ENDPOINT = process.env.IOT_ENDPOINT;
const IOT_PUBLISH_TOPIC = process.env.IOT_PUBLISH_TOPIC;
/* AWS related constants */
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB();
const iotdata = new AWS.IotData({endpoint: IOT_ENDPOINT})
exports.handler = (event, context, callback) => { //inb4 "lol noob not using async". our operations
// are mostly synchronous; you cannot know if you need to scan the table again until you scan the table
// because the lambda is written for the sole purpose
// of AWS IoT calling it, therefore, we can assume
// that AWS IoT is the one calling it.
// what that means is that we don't have to care
// about the event variable
// note that dynamodb.describeTable is not good enough;
// it updates the item count every 6 hours, which is unindeal.
// also, before you roast me about the amount of database throughput this will
// generate, i'm aware. it's the most basic tutorial for the most basic needs.
// gimmie a break.
// if you want to fix this issue, then maintain a count of the table somewhere else
// then you won't waste throughput
let totalCount = 0;
let callback_function = (err, data) => {
if (err !== null) {
callback({ statusCode: 500, body: "Can't seem to do DynamoDB things" });
return;
}
totalCount += data.Count; //adds to the total count
console.log(data);
if (!('LastEvaluatedKey' in data) || data.LastEvaluatedKey === {}) {
let ledOn = Math.min(1, totalCount % 10); //remember that 0 is on and 1 is off
iotdata.publish({ topic: IOT_PUBLISH_TOPIC, payload: ledOn.toString() }, (err, data) => {
if (err !== null) {
callback({ statusCode: 500, body: "Can't seem to do IoT things" });
return;
}
callback(null, { statusCode: 200, body: "Right on the money." });
});
} else { //we haven't scanned the whole database
dynamodb.scan({TableName: TABLE_NAME, ExclusiveStartKey: data.LastEvaluatedKey}, callback_function);
}
}
dynamodb.scan({TableName: TABLE_NAME}, callback_function);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment