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

Refactor how alarm state is manipulated, to use the proper endpoints that...

Refactor how alarm state is manipulated, to use the proper endpoints that actually change SHM, not just its representation within HA.
parent 52ae0609
No related branches found
No related tags found
No related merge requests found
......@@ -21,25 +21,25 @@ Object.keys( config.buttons ).forEach( function( index ) {
button.on( 'detected', buttonActivated );
} );
var homeAssistantUrl = config.home_assistant_proto + '://' + config.home_assistant_host + ':' + config.home_assistant_port + '/api/';
var homeAssistantAlarmApi = homeAssistantUrl + 'states/' + config.home_assistant_alarm_entity_id;
var homeAssistantUrl = config.home_assistant_proto + '://' + config.home_assistant_host + ':' + config.home_assistant_port + '/api/';
/**
* BUTTON FUNCTIONALITY
*/
/**
*
* Make HTTP(s) requests to Home Assistant to change SHM's status
*/
function buttonActivated( mac ) {
var req = {
url: homeAssistantAlarmApi,
url: homeAssistantUrl + 'states/' + config.home_assistant_alarm_entity_id,
headers: {
"Content-Type": "application/json",
"x-ha-access": config.home_assistant_pass
}
};
// First, check the current status so we can toggle
request( req, function( err, res, body ) {
// Handle error states
if ( err ) {
......@@ -52,20 +52,24 @@ function buttonActivated( mac ) {
return;
}
// HA only deals with JSON
body = JSON.parse( body );
// Identify new state based on current state
var stateUpdate = {};
// Identify service URL based on current state
var serviceBase = 'services/alarm_control_panel/';
if ( 'disarmed' === body.state ) {
stateUpdate.state = 'armed_home';
req.url = homeAssistantUrl + serviceBase + 'alarm_arm_home';
} else if ( 'armed_home' === body.state ) {
req.url = homeAssistantUrl + serviceBase + 'alarm_disarm';
} else {
stateUpdate.state = 'disarmed';
console.error( 'Invalid request based on current SHM status' );
return;
}
// Build new request to update state
req.method = 'POST';
req.body = JSON.stringify( stateUpdate );
req.body = JSON.stringify( { "entity_id": config.home_assistant_alarm_entity_id } );
request( req, function( err, res, body ) {
// Handle error states
......@@ -79,10 +83,9 @@ function buttonActivated( mac ) {
return;
}
body = JSON.parse( body );
// Output new state to console, just for fun
console.log( body.state );
// 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