Skip to content
Snippets Groups Projects
Verified Commit 3a3c1e8e authored by Erick Hitter's avatar Erick Hitter
Browse files

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

parent ecf3825f
No related branches found
No related tags found
No related merge requests found
index.js 0 → 100644
'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;
} );
} );
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment