hass-core/homeassistant/components/sensor/arest.py

116 lines
3.5 KiB
Python
Raw Normal View History

2015-09-05 13:09:55 +02:00
"""
homeassistant.components.sensor.arest
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The arest sensor will consume an exposed aREST API of a device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.arest.html
2015-09-05 13:09:55 +02:00
"""
import logging
2015-10-08 23:50:04 -07:00
import requests
from datetime import timedelta
2015-09-05 13:09:55 +02:00
from homeassistant.util import Throttle
2015-09-05 13:09:55 +02:00
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago
2015-10-18 00:41:12 +02:00
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
2015-10-08 23:50:04 -07:00
CONF_RESOURCE = 'resource'
CONF_MONITORED_VARIABLES = 'monitored_variables'
2015-09-05 13:09:55 +02:00
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the aREST sensor. """
2015-10-08 23:50:04 -07:00
resource = config.get(CONF_RESOURCE)
var_conf = config.get(CONF_MONITORED_VARIABLES)
if None in (resource, var_conf):
_LOGGER.error('Not all required config keys present: %s',
', '.join((CONF_RESOURCE, CONF_MONITORED_VARIABLES)))
return False
2015-09-05 13:09:55 +02:00
try:
2015-10-08 23:50:04 -07:00
response = requests.get(resource, timeout=10).json()
except requests.exceptions.MissingSchema:
2015-09-05 13:26:29 +02:00
_LOGGER.error("Missing resource or schema in configuration. "
2015-09-05 13:09:55 +02:00
"Add http:// to your URL.")
return False
2015-10-08 23:50:04 -07:00
except requests.exceptions.ConnectionError:
2015-09-05 13:09:55 +02:00
_LOGGER.error("No route to device. "
"Please check the IP address in the configuration file.")
return False
2015-10-08 23:50:04 -07:00
arest = ArestData(resource)
2015-09-05 13:09:55 +02:00
dev = []
for variable in config['monitored_variables']:
2015-10-08 23:50:04 -07:00
if variable['name'] not in response['variables']:
2015-09-05 13:09:55 +02:00
_LOGGER.error('Variable: "%s" does not exist', variable['name'])
2015-10-08 23:50:04 -07:00
continue
2015-10-18 00:41:12 +02:00
dev.append(ArestSensor(arest,
config.get('name', response['name']),
variable['name'],
2015-10-08 23:50:04 -07:00
variable.get('unit')))
2015-09-05 13:09:55 +02:00
add_devices(dev)
class ArestSensor(Entity):
""" Implements an aREST sensor. """
2015-10-08 23:50:04 -07:00
def __init__(self, arest, location, variable, unit_of_measurement):
self.arest = arest
2015-09-05 13:09:55 +02:00
self._name = '{} {}'.format(location.title(), variable.title())
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. """
2015-10-08 23:50:04 -07:00
values = self.arest.data
if 'error' in values:
2015-10-08 23:50:04 -07:00
return values['error']
2015-09-05 13:09:55 +02:00
else:
2015-10-08 23:50:04 -07:00
return values.get(self._variable, 'n/a')
def update(self):
""" Gets the latest data from aREST API. """
self.arest.update()
2015-09-05 13:09:55 +02:00
# pylint: disable=too-few-public-methods
class ArestData(object):
""" Class for handling the data retrieval. """
def __init__(self, resource):
self.resource = resource
2015-10-08 23:50:04 -07:00
self.data = {}
2015-09-05 13:09:55 +02:00
@Throttle(MIN_TIME_BETWEEN_UPDATES)
2015-09-05 13:09:55 +02:00
def update(self):
""" Gets the latest data from aREST device. """
2015-09-05 13:09:55 +02:00
try:
2015-10-08 23:50:04 -07:00
response = requests.get(self.resource, timeout=10)
self.data = response.json()['variables']
2015-10-08 23:50:04 -07:00
except requests.exceptions.ConnectionError:
2015-09-05 13:09:55 +02:00
_LOGGER.error("No route to device. Is device offline?")
2015-10-08 23:50:04 -07:00
self.data = {'error': 'error fetching'}