From 3f3b475d76db14db5e2091f2eb335d4c7010fd22 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Sun, 13 Sep 2015 22:41:16 +0200 Subject: [PATCH 1/4] Add rest sensor --- homeassistant/components/sensor/rest.py | 141 ++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 homeassistant/components/sensor/rest.py diff --git a/homeassistant/components/sensor/rest.py b/homeassistant/components/sensor/rest.py new file mode 100644 index 00000000000..4779c38e232 --- /dev/null +++ b/homeassistant/components/sensor/rest.py @@ -0,0 +1,141 @@ +""" +homeassistant.components.sensor.rest +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The rest sensor will consume JSON responses sent by an exposed REST API. + +Configuration: + +To use the rest sensor you will need to add something like the following +to your configuration.yaml file. + +sensor: + platform: arest + name: REST sensor + resource: http://IP_ADDRESS/ENDPOINT + variable: temperature + unit: '°C' + +Variables: + +name +*Optional +The name of the sensor. Default is 'REST Sensor'. + +resource +*Required +The full URL of the REST service/endpoint that provide the JSON response. + +variable +*Required +The name of the variable inside the JSON response you want to monitor. + +unit +*Optional +Defines the units of measurement of the sensor, if any. + +For more details about this platform, please refer to the documentation at +https://home-assistant.io/components/sensor.rest.html +""" +import logging +from requests import get, exceptions +from datetime import timedelta + +from homeassistant.util import Throttle +from homeassistant.helpers.entity import Entity + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_NAME = "REST Sensor" + +# Return cached results if last scan was less then this time ago +MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60) + + +# pylint: disable=unused-variable +def setup_platform(hass, config, add_devices, discovery_info=None): + """ Get the REST sensor. """ + + resource = config.get('resource', None) + + try: + response = get(resource, timeout=10) + except exceptions.MissingSchema: + _LOGGER.error("Missing resource or schema in configuration. " + "Add http:// to your URL.") + return False + except exceptions.ConnectionError: + _LOGGER.error("No route to resource/endpoint. " + "Please check the URL in the configuration file.") + return False + + rest = RestData(resource) + + dev = [] + add_devices([RestSensor(rest, + config.get('name', DEFAULT_NAME), + config.get('variable'), + config.get('unit'))]) + add_devices(dev) + + +class RestSensor(Entity): + """ Implements a REST sensor. """ + + def __init__(self, rest, name, variable, unit_of_measurement): + self.rest = rest + self._name = name + self._variable = variable + self._state = 'n/a' + self._unit_of_measurement = unit_of_measurement + self.update() + + @property + def name(self): + """ The name of the sensor. """ + return self._name + + @property + def unit_of_measurement(self): + """ Unit the value is expressed in. """ + return self._unit_of_measurement + + @property + def state(self): + """ Returns the state of the device. """ + return self._state + + def update(self): + """ Gets the latest data from REST API and updates the state. """ + self.rest.update() + value = self.rest.data + + if 'error' in value: + self._state = value['error'] + else: + try: + self._state = value[self._variable] + except KeyError: + _LOGGER.error('Variable "%s" not found in response: "%s".', + self._variable, value) + self._state = 'N/A' + + +# pylint: disable=too-few-public-methods +class RestData(object): + """ Class for handling the data retrieval. """ + + def __init__(self, resource): + self.resource = resource + self.data = dict() + + @Throttle(MIN_TIME_BETWEEN_UPDATES) + def update(self): + """ Gets the latest data from REST service. """ + try: + response = get(self.resource, timeout=10) + if 'error' in self.data: + del self.data['error'] + self.data = response.json() + except exceptions.ConnectionError: + _LOGGER.error("No route to resource/endpoint.") + self.data['error'] = 'N/A' From 246184507c206bb8430c3d738e70959bd427af2a Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Sun, 13 Sep 2015 22:41:37 +0200 Subject: [PATCH 2/4] Add rest sensor --- .coveragerc | 1 + 1 file changed, 1 insertion(+) diff --git a/.coveragerc b/.coveragerc index 9cb5bdc63dd..e4e07dd7b02 100644 --- a/.coveragerc +++ b/.coveragerc @@ -67,6 +67,7 @@ omit = homeassistant/components/sensor/forecast.py homeassistant/components/sensor/mysensors.py homeassistant/components/sensor/openweathermap.py + homeassistant/components/sensor/rest.py homeassistant/components/sensor/rfxtrx.py homeassistant/components/sensor/rpi_gpio.py homeassistant/components/sensor/sabnzbd.py From 7e066e11ad54da5fba99dcf503dd0d82d536587b Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Mon, 14 Sep 2015 08:55:20 +0200 Subject: [PATCH 3/4] Remove left-over --- homeassistant/components/sensor/rest.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/homeassistant/components/sensor/rest.py b/homeassistant/components/sensor/rest.py index 4779c38e232..ee2707c5230 100644 --- a/homeassistant/components/sensor/rest.py +++ b/homeassistant/components/sensor/rest.py @@ -70,12 +70,10 @@ def setup_platform(hass, config, add_devices, discovery_info=None): rest = RestData(resource) - dev = [] add_devices([RestSensor(rest, config.get('name', DEFAULT_NAME), config.get('variable'), config.get('unit'))]) - add_devices(dev) class RestSensor(Entity): From b0441aadc44fa9eba495f3783efe42f4f40b8fcc Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Mon, 14 Sep 2015 10:06:40 +0200 Subject: [PATCH 4/4] Add new checks and move var check to setup --- homeassistant/components/sensor/rest.py | 31 +++++++++++++++++-------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/sensor/rest.py b/homeassistant/components/sensor/rest.py index ee2707c5230..6fe84288796 100644 --- a/homeassistant/components/sensor/rest.py +++ b/homeassistant/components/sensor/rest.py @@ -38,6 +38,7 @@ https://home-assistant.io/components/sensor.rest.html """ import logging from requests import get, exceptions +from json import loads from datetime import timedelta from homeassistant.util import Throttle @@ -59,13 +60,28 @@ def setup_platform(hass, config, add_devices, discovery_info=None): try: response = get(resource, timeout=10) + if not response.ok: + _LOGGER.error('Response status is "%s"', response.status_code) except exceptions.MissingSchema: - _LOGGER.error("Missing resource or schema in configuration. " - "Add http:// to your URL.") + _LOGGER.error('Missing resource or schema in configuration. ' + 'Add http:// to your URL.') return False except exceptions.ConnectionError: - _LOGGER.error("No route to resource/endpoint. " - "Please check the URL in the configuration file.") + _LOGGER.error('No route to resource/endpoint. ' + 'Please check the URL in the configuration file.') + return False + + try: + data = loads(response.text) + except ValueError: + _LOGGER.error('No valid JSON in the response in: %s', data) + return False + + try: + data[config.get('variable')] + except KeyError: + _LOGGER.error('Variable "%s" not found in response: "%s"', + config.get('variable'), data) return False rest = RestData(resource) @@ -110,12 +126,7 @@ class RestSensor(Entity): if 'error' in value: self._state = value['error'] else: - try: - self._state = value[self._variable] - except KeyError: - _LOGGER.error('Variable "%s" not found in response: "%s".', - self._variable, value) - self._state = 'N/A' + self._state = value[self._variable] # pylint: disable=too-few-public-methods