├── README.md └── lightbulbSwitch.js /README.md: -------------------------------------------------------------------------------- 1 | # lightbulbSwitch 2 | Sample AWS Lambda function to use AWS IoT Device Shadow to switch a connected lightbulb ON or OFF 3 | 4 | To get your endpoint for the Device Shadow API, you can use the AWS CLI: 5 | 6 | aws iot describe-endpoint 7 | 8 | -------------------------------------------------------------------------------- /lightbulbSwitch.js: -------------------------------------------------------------------------------- 1 | console.log('Loading function'); 2 | 3 | var config = { 4 | "thingName": 'lightbulb', 5 | "endpointAddress": "" 6 | } 7 | 8 | var AWS = require('aws-sdk'); 9 | var iotdata = new AWS.IotData({endpoint: config.endpointAddress}); 10 | 11 | exports.handler = function(event, context) { 12 | console.log('Received event:', JSON.stringify(event, null, 2)); 13 | iotdata.getThingShadow({ 14 | thingName: config.thingName 15 | }, function(err, data) { 16 | if (err) { 17 | context.fail(err); 18 | } else { 19 | console.log(data); 20 | var jsonPayload = JSON.parse(data.payload); 21 | var status = jsonPayload.state.reported.status; 22 | console.log('status: ' + status); 23 | var newStatus; 24 | if (status == 'ON') { 25 | newStatus = 'OFF'; 26 | } else { 27 | newStatus = 'ON'; 28 | } 29 | var update = { 30 | "state": { 31 | "desired" : { 32 | "status" : newStatus 33 | } 34 | } 35 | }; 36 | iotdata.updateThingShadow({ 37 | payload: JSON.stringify(update), 38 | thingName: config.thingName 39 | }, function(err, data) { 40 | if (err) { 41 | context.fail(err); 42 | } else { 43 | console.log(data); 44 | context.succeed('newStatus: ' + newStatus); 45 | } 46 | }); 47 | } 48 | }); 49 | }; 50 | 51 | --------------------------------------------------------------------------------