Make API calls to Home Assistant based on Dash button pushes.

parent ecf3825f
'use strict';
/**
* LIBRARIES
*/
var dashButton = require( 'node-dash-button' );
var request = require( 'request' );
/**
* CONFIGURATION & EVENT BINDING
*/
var config = require( './config.json' );
Object.keys( config.buttons ).forEach( function( index ) {
var buttonConfig = config.buttons[index];
var button = dashButton( buttonConfig.mac, config.arp_interface );
button.on( 'detected', buttonActivated );
} );
var homeAssistantApiBase = config.home_assistant_proto + '://' + config.home_assistant_host + ':' + config.home_assistant_port + '/api/';
/**
* BUTTON FUNCTIONALITY
*/
/**
* Make HTTP(s) requests to Home Assistant to toggle status of device assigned to pushed button
*/
function buttonActivated( mac ) {
var buttonConfig = config.buttons[mac];
var req = {
url: homeAssistantApiBase + 'states/' + buttonConfig.status.entity_id,
headers: {
'Content-Type': 'application/json',
'x-ha-access': config.home_assistant_pass
}
};
console.log( req );
// First, check the current status so we can toggle
request( req, function( err, res, body ) {
// Handle error states
if ( err ) {
console.error( err );
return;
}
if ( 200 !== res.statusCode ) {
console.error( res.statusCode );
return;
}
// HA only deals with JSON
body = JSON.parse( body );
var service = null,
postBody = {};
if ( 'off' === body.state ) {
service = buttonConfig.on.entity + '/turn_on';
postBody.entity_id = buttonConfig.on.entity_id;
} else if ( 'on' === body.state ) {
service = buttonConfig.off.entity + '/turn_off';
postBody.entity_id = buttonConfig.off.entity_id;
} else {
console.error( 'Unknown state: ' + body.state );
return;
}
// Build new request to update state
req.url = homeAssistantApiBase + service;
req.method = 'POST';
req.body = JSON.stringify( postBody );
// Make request to change alarm status
request( req, function( err, res, body ) {
// Handle error states
if ( err ) {
console.error( err );
return;
}
if ( 200 !== res.statusCode ) {
console.error( res.statusCode );
return;
}
// Nothing more to do
// services endpoints don't return anything useful
return true;
} );
} );
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment