-
-
Save dave-malone/611800d7afa90561f3b40ca6b2380faf to your computer and use it in GitHub Desktop.
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)) | |
} |
Thank you very much for sharing this code. But I am not getting updated thing shadow. Any suggestion?
Check your Lambda logs to ensure you aren't getting any errors. It's likely an IAM permissions error.
Thank you very much for sharing this code. But I am not getting updated thing shadow. Any suggestion?
Were you ever able to figure this out? @NiiCoder
@UnHumbleBen I've updated the code to hopefully make it more obvious which environment variables need to be set on your Lambda function. If you aren't setting MQTT_BROKER_ENDPOINT
or THING_NAME
environment vars on your Lambda, the code won't work.
There was no need to explicitly set the access key pair since AWS Lambda permissions are granted on the Execution Role. The Execution Role must have a policy attached that allows for iot:UpdateThingShadow
for the ARN of your AWS IoT Thing, otherwise you will get permissions errors.
Feel free to come back and share any errors you are encountering and I'll see what I can do to help you out.
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:
var params = {
payload: post_body,
thingName: process.env.THING_NAME,
shadowName: process.env.SHADOW_NAME,
};
Thank you very much for sharing this code. But I am not getting updated thing shadow. Any suggestion?