Making the AWS IoT Dash Button, AWS Lambda and Home Assistant play together!

Here’s a quick bit of code I wrote which accepts an AWS Lambda event and submits it to Home Assistant’s event bus so that you can do automations based on Lambda events. A perfect use of this is with the new AWS IoT Dash Button (which @JshWright helpfully points out costs about $0.02 per button press). After pressing the button I see the message appear in Home Assistant after about 8 seconds.

I’ve also used this same code to get notifications in Home Assistant when my security service calls to tell me I have a new package, delivery or guest.

Just create a new Lambda function, skip the blueprint, put this in, set the role to be basic execution. You also need to change the variables at the top. If you are using HTTP change all occurrences of https to http.

/**
 *
 * The following JSON template shows what is sent as the payload:
    {
        "serialNumber": "GXXXXXXXXXXXXXXXXX",
        "batteryVoltage": "xxmV",
        "clickType": "SINGLE" | "DOUBLE" | "LONG"
    }
 *
 * A "LONG" clickType is sent if the first press lasts longer than 1.5 seconds.
 * "SINGLE" and "DOUBLE" clickType payloads are sent for short clicks.
 *
 * For more documentation, follow the link below.
 * http://docs.aws.amazon.com/iot/latest/developerguide/iot-lambda-rule.html
 */

const HOST = 'myhome.com';
const PASSWORD = 'myapipassword';
const EVENT_NAME = 'dash_button.pressed';

var https = require('https');

exports.handler = (event, context, callback) => {
  console.log('Received event:', event.clickType);
  var post_options = {
    host: HOST,
    path: '/api/events/'+EVENT_NAME,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-HA-Access': PASSWORD
    }
  };

  var post_req = https.request(post_options, function(res) {
    res.setEncoding('utf8');
    console.log('Home Assistant response status code', res.statusCode);
    res.on('data', function (chunk) {
      console.log('Home Assistant Response: ' + chunk);
    });
    res.on('end', function(){
      callback(null);
    });
  });

  post_req.on('error', function(err){
    console.error('Error when notifying Home Assistant!', err);
    callback(err);
  });

  post_req.write(JSON.stringify(event));
  post_req.end();
};
4 Likes

Can you help me out a little with this? I’ve got a couple of IoT buttons that I have registered with AWS, but I’m trying to figure out the process between the button, AWS (Lambda? MQTT?), and HA.

Thanks!
Roddie

Looks like exactly what I would want to do with hass and my AWS IoT Button, but I can’t quite follow what the code is doing. When you say that you “see the message appear” in Home Assistant, where should I see it, or how should I configure a test automation to recognize the incoming event?