diff --git a/index.js b/index.js index 4f3c5c58c4e585d2c29d5ccc65348174b6542311..3bce2a2b15b05f0bb15efc69b8a60b8d34325473 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; } ); } ); }