From 6f01405aad3568b1e9fcef0f3947fdb13740a587 Mon Sep 17 00:00:00 2001 From: Erick Hitter <services@ethitter.com> Date: Sat, 10 Sep 2016 15:31:16 -0700 Subject: [PATCH] Refactor how alarm state is manipulated, to use the proper endpoints that actually change SHM, not just its representation within HA. --- index.js | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/index.js b/index.js index 4f3c5c5..3bce2a2 100644 --- a/index.js +++ b/index.js @@ -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; } ); } ); } -- GitLab