Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dave-malone/611800d7afa90561f3b40ca6b2380faf to your computer and use it in GitHub Desktop.
Save dave-malone/611800d7afa90561f3b40ca6b2380faf to your computer and use it in GitHub Desktop.
AWS Lambda function example of how to update IoT Thing Shadows
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))
}
@UnHumbleBen
Copy link

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, 
    };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment