2013-10-25 10:05:58 +00:00
|
|
|
"""
|
|
|
|
homeassistant.remote
|
|
|
|
~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
A module containing drop in replacements for core parts that will interface
|
|
|
|
with a remote instance of home assistant.
|
2013-10-28 00:39:54 +00:00
|
|
|
|
|
|
|
If a connection error occurs while communicating with the API a
|
2014-01-24 06:03:13 +00:00
|
|
|
HomeAssistantError will be raised.
|
2013-10-25 10:05:58 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
import threading
|
|
|
|
import logging
|
|
|
|
import json
|
2013-10-29 07:22:38 +00:00
|
|
|
import urlparse
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
import requests
|
|
|
|
|
2013-10-28 00:39:54 +00:00
|
|
|
import homeassistant as ha
|
2013-12-11 08:07:30 +00:00
|
|
|
import homeassistant.components.httpinterface as hah
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
METHOD_GET = "get"
|
|
|
|
METHOD_POST = "post"
|
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
def _setup_call_api(host, port, api_password):
|
2013-10-25 10:05:58 +00:00
|
|
|
""" Helper method to setup a call api method. """
|
2013-10-29 07:22:38 +00:00
|
|
|
port = port or hah.SERVER_PORT
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
base_url = "http://{}:{}".format(host, port)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
def _call_api(method, path, data=None):
|
2013-10-25 10:05:58 +00:00
|
|
|
""" Makes a call to the Home Assistant api. """
|
|
|
|
data = data or {}
|
|
|
|
data['api_password'] = api_password
|
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
url = urlparse.urljoin(base_url, path)
|
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
try:
|
|
|
|
if method == METHOD_GET:
|
|
|
|
return requests.get(url, params=data)
|
|
|
|
else:
|
|
|
|
return requests.request(method, url, data=data)
|
|
|
|
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
|
|
logging.getLogger(__name__).exception("Error connecting to server")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError("Error connecting to server")
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
return _call_api
|
|
|
|
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
class JSONEncoder(json.JSONEncoder):
|
|
|
|
""" JSONEncoder that supports Home Assistant objects. """
|
|
|
|
|
|
|
|
def default(self, obj): # pylint: disable=method-hidden
|
|
|
|
""" Checks if Home Assistat object and encodes if possible.
|
|
|
|
Else hand it off to original method. """
|
|
|
|
if isinstance(obj, ha.State):
|
2014-01-23 03:40:19 +00:00
|
|
|
return obj.as_dict()
|
2014-01-20 03:10:40 +00:00
|
|
|
|
|
|
|
return json.JSONEncoder.default(self, obj)
|
|
|
|
|
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
class Bus(ha.Bus):
|
|
|
|
""" Drop-in replacement for a normal bus that will forward interaction to
|
|
|
|
a remote bus.
|
2013-10-25 10:05:58 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, host, api_password, port=None):
|
2013-11-20 07:48:08 +00:00
|
|
|
ha.Bus.__init__(self)
|
|
|
|
|
|
|
|
self.logger = logging.getLogger(__name__)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
self._call_api = _setup_call_api(host, port, api_password)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
@property
|
|
|
|
def services(self):
|
|
|
|
""" List the available services. """
|
|
|
|
try:
|
|
|
|
req = self._call_api(METHOD_GET, hah.URL_API_SERVICES)
|
|
|
|
|
|
|
|
if req.status_code == 200:
|
|
|
|
data = req.json()
|
|
|
|
|
|
|
|
return data['services']
|
|
|
|
|
|
|
|
else:
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-20 07:48:08 +00:00
|
|
|
"Got unexpected result (3): {}.".format(req.text))
|
|
|
|
|
|
|
|
except ValueError: # If req.json() can't parse the json
|
|
|
|
self.logger.exception("Bus:Got unexpected result")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-20 07:48:08 +00:00
|
|
|
"Got unexpected result: {}".format(req.text))
|
|
|
|
|
|
|
|
except KeyError: # If not all expected keys are in the returned JSON
|
|
|
|
self.logger.exception("Bus:Got unexpected result (2)")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-20 07:48:08 +00:00
|
|
|
"Got unexpected result (2): {}".format(req.text))
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-11-01 19:28:18 +00:00
|
|
|
@property
|
2013-11-20 07:48:08 +00:00
|
|
|
def event_listeners(self):
|
2013-11-01 19:28:18 +00:00
|
|
|
""" List of events that is being listened for. """
|
|
|
|
try:
|
|
|
|
req = self._call_api(METHOD_GET, hah.URL_API_EVENTS)
|
|
|
|
|
|
|
|
if req.status_code == 200:
|
|
|
|
data = req.json()
|
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
return data['event_listeners']
|
2013-11-01 19:28:18 +00:00
|
|
|
|
|
|
|
else:
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-11 00:46:48 +00:00
|
|
|
"Got unexpected result (3): {}.".format(req.text))
|
2013-11-01 19:28:18 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
except ValueError: # If req.json() can't parse the json
|
2013-11-20 07:48:08 +00:00
|
|
|
self.logger.exception("Bus:Got unexpected result")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-11 00:46:48 +00:00
|
|
|
"Got unexpected result: {}".format(req.text))
|
2013-11-01 19:28:18 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
except KeyError: # If not all expected keys are in the returned JSON
|
2013-11-20 07:48:08 +00:00
|
|
|
self.logger.exception("Bus:Got unexpected result (2)")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-11 00:46:48 +00:00
|
|
|
"Got unexpected result (2): {}".format(req.text))
|
2013-11-01 19:28:18 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def call_service(self, domain, service, service_data=None):
|
|
|
|
""" Calls a service. """
|
|
|
|
|
|
|
|
if service_data:
|
|
|
|
data = {'service_data': json.dumps(service_data)}
|
|
|
|
else:
|
|
|
|
data = None
|
|
|
|
|
|
|
|
req = self._call_api(METHOD_POST,
|
|
|
|
hah.URL_API_SERVICES_SERVICE.format(
|
|
|
|
domain, service),
|
|
|
|
data)
|
|
|
|
|
|
|
|
if req.status_code != 200:
|
|
|
|
error = "Error calling service: {} - {}".format(
|
|
|
|
req.status_code, req.text)
|
|
|
|
|
|
|
|
self.logger.error("Bus:{}".format(error))
|
2014-01-24 06:03:13 +00:00
|
|
|
|
|
|
|
if req.status_code == 400:
|
|
|
|
raise ha.ServiceDoesNotExistError(error)
|
|
|
|
else:
|
|
|
|
raise ha.HomeAssistantError(error)
|
2013-11-20 07:48:08 +00:00
|
|
|
|
|
|
|
def register_service(self, domain, service, service_callback):
|
|
|
|
""" Not implemented for remote bus.
|
|
|
|
|
|
|
|
Will throw NotImplementedError. """
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def fire_event(self, event_type, event_data=None):
|
2013-10-25 10:05:58 +00:00
|
|
|
""" Fire an event. """
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
if event_data:
|
|
|
|
data = {'event_data': json.dumps(event_data, cls=JSONEncoder)}
|
|
|
|
else:
|
|
|
|
data = None
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
req = self._call_api(METHOD_POST,
|
|
|
|
hah.URL_API_EVENTS_EVENT.format(event_type),
|
|
|
|
data)
|
2013-10-28 00:39:54 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
if req.status_code != 200:
|
|
|
|
error = "Error firing event: {} - {}".format(
|
|
|
|
req.status_code, req.text)
|
2013-10-28 00:39:54 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
self.logger.error("Bus:{}".format(error))
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(error)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def listen_event(self, event_type, listener):
|
|
|
|
""" Not implemented for remote bus.
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
Will throw NotImplementedError. """
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
def listen_once_event(self, event_type, listener):
|
|
|
|
""" Not implemented for remote bus.
|
|
|
|
|
|
|
|
Will throw NotImplementedError. """
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def remove_event_listener(self, event_type, listener):
|
|
|
|
""" Not implemented for remote bus.
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
Will throw NotImplementedError. """
|
|
|
|
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2013-10-28 00:39:54 +00:00
|
|
|
class StateMachine(ha.StateMachine):
|
2013-10-25 10:05:58 +00:00
|
|
|
""" Drop-in replacement for a normal statemachine that communicates with a
|
|
|
|
remote statemachine.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, host, api_password, port=None):
|
2013-10-28 00:39:54 +00:00
|
|
|
ha.StateMachine.__init__(self, None)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
self._call_api = _setup_call_api(host, port, api_password)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
self.lock = threading.Lock()
|
|
|
|
self.logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
@property
|
2014-01-20 07:37:40 +00:00
|
|
|
def entity_ids(self):
|
|
|
|
""" List of entity ids which states are being tracked. """
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
try:
|
2013-10-29 07:22:38 +00:00
|
|
|
req = self._call_api(METHOD_GET, hah.URL_API_STATES)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
return req.json()['entity_ids']
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
|
|
self.logger.exception("StateMachine:Error connecting to server")
|
|
|
|
return []
|
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
except ValueError: # If req.json() can't parse the json
|
2013-10-25 10:05:58 +00:00
|
|
|
self.logger.exception("StateMachine:Got unexpected result")
|
|
|
|
return []
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
except KeyError: # If 'entity_ids' key not in parsed json
|
2013-10-28 00:39:54 +00:00
|
|
|
self.logger.exception("StateMachine:Got unexpected result (2)")
|
|
|
|
return []
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def remove_entity(self, entity_id):
|
2014-01-20 03:10:40 +00:00
|
|
|
""" This method is not implemented for remote statemachine.
|
|
|
|
|
|
|
|
Throws NotImplementedError. """
|
|
|
|
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def set_state(self, entity_id, new_state, attributes=None):
|
|
|
|
""" Set the state of a entity, add entity if it does not exist.
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
Attributes is an optional dict to specify attributes of this state. """
|
|
|
|
|
|
|
|
attributes = attributes or {}
|
|
|
|
|
|
|
|
self.lock.acquire()
|
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
data = {'new_state': new_state,
|
2013-10-25 10:05:58 +00:00
|
|
|
'attributes': json.dumps(attributes)}
|
|
|
|
|
|
|
|
try:
|
2013-10-29 07:22:38 +00:00
|
|
|
req = self._call_api(METHOD_POST,
|
2014-01-20 07:37:40 +00:00
|
|
|
hah.URL_API_STATES_ENTITY.format(entity_id),
|
2013-10-29 07:22:38 +00:00
|
|
|
data)
|
2013-10-28 00:39:54 +00:00
|
|
|
|
2013-10-29 07:22:38 +00:00
|
|
|
if req.status_code != 201:
|
2013-10-28 00:39:54 +00:00
|
|
|
error = "Error changing state: {} - {}".format(
|
2013-11-11 00:46:48 +00:00
|
|
|
req.status_code, req.text)
|
2013-10-28 00:39:54 +00:00
|
|
|
|
|
|
|
self.logger.error("StateMachine:{}".format(error))
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(error)
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
|
|
self.logger.exception("StateMachine:Error connecting to server")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError("Error connecting to server")
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
finally:
|
|
|
|
self.lock.release()
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def get_state(self, entity_id):
|
|
|
|
""" Returns the state of the specified entity. """
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
try:
|
2013-10-29 07:22:38 +00:00
|
|
|
req = self._call_api(METHOD_GET,
|
2014-01-20 07:37:40 +00:00
|
|
|
hah.URL_API_STATES_ENTITY.format(entity_id))
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-11-01 18:34:43 +00:00
|
|
|
if req.status_code == 200:
|
|
|
|
data = req.json()
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
return ha.State.from_dict(data)
|
2013-11-01 18:34:43 +00:00
|
|
|
|
|
|
|
elif req.status_code == 422:
|
2014-01-20 07:37:40 +00:00
|
|
|
# Entity does not exist
|
2013-11-01 18:34:43 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
else:
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-11 00:46:48 +00:00
|
|
|
"Got unexpected result (3): {}.".format(req.text))
|
2013-10-25 10:05:58 +00:00
|
|
|
|
|
|
|
except requests.exceptions.ConnectionError:
|
|
|
|
self.logger.exception("StateMachine:Error connecting to server")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError("Error connecting to server")
|
2013-10-25 10:05:58 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
except ValueError: # If req.json() can't parse the json
|
2013-10-25 10:05:58 +00:00
|
|
|
self.logger.exception("StateMachine:Got unexpected result")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-11 00:46:48 +00:00
|
|
|
"Got unexpected result: {}".format(req.text))
|
2013-10-28 00:39:54 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
except KeyError: # If not all expected keys are in the returned JSON
|
2013-10-28 00:39:54 +00:00
|
|
|
self.logger.exception("StateMachine:Got unexpected result (2)")
|
2014-01-24 06:03:13 +00:00
|
|
|
raise ha.HomeAssistantError(
|
2013-11-11 00:46:48 +00:00
|
|
|
"Got unexpected result (2): {}".format(req.text))
|