Last active
May 25, 2022 05:57
-
-
Save dave-malone/611800d7afa90561f3b40ca6b2380faf to your computer and use it in GitHub Desktop.
AWS Lambda function example of how to update IoT Thing Shadows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require('aws-sdk') | |
AWS.config.region = process.env.AWS_REGION | |
const AWS_IOT_CORE_ENDPOINT = process.env.MQTT_BROKER_ENDPOINT | |
const IOT_THING_NAME = process.env.THING_NAME | |
const iotdata = new AWS.IotData({ | |
endpoint: AWS_IOT_CORE_ENDPOINT, | |
}) | |
const openState = "open" | |
const closedState = "closed" | |
let currentState = closedState | |
function toggleGarageDoor(thingName) { | |
return new Promise((resolve, reject) => { | |
let desiredState = (currentState === closedState) ? openState : closedState | |
var params = { | |
payload: `{"state":{"desired":{"door":"${desiredState}"}}}`, | |
thingName: thingName | |
} | |
iotdata.updateThingShadow(params, (err, data) => { | |
if (err){ | |
console.log(err, err.stack) | |
reject(`Failed to update thing shadow: ${err.errorMessage}`) | |
}else{ | |
console.log(`update thing shadow response: ${JSON.stringify(data)}`) | |
currentState = desiredState | |
resolve({"update thing shadow response": data}) | |
} | |
}) | |
}) | |
} | |
exports.handler = async (event, context, callback) => { | |
await toggleGarageDoor(IOT_THING_NAME) | |
.then((result) => callback(null, result)) | |
.catch((err) => callback(err)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @dave-malone !
The fix turned out to be setting a shadowName variable. In my case, I had a thing with multiple shadows, thus a shadowName was necessary to specify which shadow to target. Essentially: