core/homeassistant/components/sensor/arest.py

180 lines
6.6 KiB
Python
Raw Normal View History

2015-09-05 11:09:55 +00: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
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/sensor.arest/
2015-09-05 11:09:55 +00:00
"""
2015-11-29 21:49:05 +00:00
from datetime import timedelta
2015-09-05 11:09:55 +00:00
import logging
2015-11-29 21:49:05 +00:00
2015-10-09 06:50:04 +00:00
import requests
2015-09-05 11:09:55 +00:00
2015-10-18 16:05:25 +00:00
from homeassistant.const import DEVICE_DEFAULT_NAME
2015-11-29 21:49:05 +00:00
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
2015-09-05 11:09:55 +00:00
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago
2015-10-17 22:41:12 +00:00
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
2015-10-09 06:50:04 +00:00
CONF_RESOURCE = 'resource'
CONF_MONITORED_VARIABLES = 'monitored_variables'
2015-09-05 11:09:55 +00:00
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the aREST sensor. """
2015-10-09 06:50:04 +00:00
resource = config.get(CONF_RESOURCE)
var_conf = config.get(CONF_MONITORED_VARIABLES)
2015-10-27 22:51:16 +00:00
pins = config.get('pins', None)
if resource is None:
2015-10-09 06:50:04 +00:00
_LOGGER.error('Not all required config keys present: %s',
2015-10-27 22:51:16 +00:00
CONF_RESOURCE)
2015-10-09 06:50:04 +00:00
return False
2015-09-05 11:09:55 +00:00
try:
2015-10-09 06:50:04 +00:00
response = requests.get(resource, timeout=10).json()
except requests.exceptions.MissingSchema:
2015-09-05 11:26:29 +00:00
_LOGGER.error("Missing resource or schema in configuration. "
2015-09-05 11:09:55 +00:00
"Add http:// to your URL.")
return False
2015-10-09 06:50:04 +00:00
except requests.exceptions.ConnectionError:
2015-10-18 16:05:25 +00:00
_LOGGER.error("No route to device at %s. "
"Please check the IP address in the configuration file.",
resource)
2015-09-05 11:09:55 +00:00
return False
2015-10-09 06:50:04 +00:00
arest = ArestData(resource)
2015-09-05 11:09:55 +00:00
dev = []
2015-10-18 16:05:25 +00:00
2015-10-27 22:51:16 +00:00
if var_conf is not None:
for variable in config['monitored_variables']:
if variable['name'] not in response['variables']:
_LOGGER.error('Variable: "%s" does not exist',
variable['name'])
continue
dev.append(ArestSensor(arest,
resource,
config.get('name', response['name']),
variable['name'],
variable=variable['name'],
unit_of_measurement=variable.get(
'unit_of_measurement')))
if pins is not None:
for pinnum, pin in pins.items():
dev.append(ArestSensor(ArestData(resource, pinnum),
resource,
config.get('name', response['name']),
pin.get('name'),
pin=pinnum,
unit_of_measurement=pin.get(
'unit_of_measurement'),
corr_factor=pin.get('correction_factor',
None),
decimal_places=pin.get('decimal_places',
None)))
2015-09-05 11:09:55 +00:00
add_devices(dev)
2015-10-18 16:05:25 +00:00
# pylint: disable=too-many-instance-attributes, too-many-arguments
2015-09-05 11:09:55 +00:00
class ArestSensor(Entity):
2015-10-18 16:05:25 +00:00
""" Implements an aREST sensor for exposed variables. """
2015-09-05 11:09:55 +00:00
2015-10-18 16:05:25 +00:00
def __init__(self, arest, resource, location, name, variable=None,
pin=None, unit_of_measurement=None, corr_factor=None,
decimal_places=None):
2015-10-09 06:50:04 +00:00
self.arest = arest
2015-10-18 16:05:25 +00:00
self._resource = resource
self._name = '{} {}'.format(location.title(), name.title()) \
or DEVICE_DEFAULT_NAME
2015-09-05 11:09:55 +00:00
self._variable = variable
2015-10-18 16:05:25 +00:00
self._pin = pin
2015-09-05 11:09:55 +00:00
self._state = 'n/a'
self._unit_of_measurement = unit_of_measurement
2015-10-18 16:05:25 +00:00
self._corr_factor = corr_factor
self._decimal_places = decimal_places
2015-09-05 11:09:55 +00:00
self.update()
2015-10-18 16:05:25 +00:00
if self._pin is not None:
request = requests.get('{}/mode/{}/i'.format
(self._resource, self._pin), timeout=10)
if request.status_code is not 200:
_LOGGER.error("Can't set mode. Is device offline?")
2015-09-05 11:09:55 +00:00
@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-09 06:50:04 +00:00
values = self.arest.data
if 'error' in values:
2015-10-09 06:50:04 +00:00
return values['error']
2015-10-18 16:05:25 +00:00
elif 'value' in values:
if self._corr_factor is not None \
and self._decimal_places is not None:
return round((float(values['value']) *
float(self._corr_factor)), self._decimal_places)
elif self._corr_factor is not None \
and self._decimal_places is None:
return round(float(values['value']) * float(self._corr_factor))
else:
return values['value']
2015-09-05 11:09:55 +00:00
else:
2015-10-09 06:50:04 +00:00
return values.get(self._variable, 'n/a')
def update(self):
""" Gets the latest data from aREST API. """
self.arest.update()
2015-09-05 11:09:55 +00:00
# pylint: disable=too-few-public-methods
class ArestData(object):
2015-10-18 16:05:25 +00:00
""" Class for handling the data retrieval for variables. """
2015-09-05 11:09:55 +00:00
2015-10-18 16:05:25 +00:00
def __init__(self, resource, pin=None):
self._resource = resource
self._pin = pin
2015-10-09 06:50:04 +00:00
self.data = {}
2015-09-05 11:09:55 +00:00
@Throttle(MIN_TIME_BETWEEN_UPDATES)
2015-09-05 11:09:55 +00:00
def update(self):
""" Gets the latest data from aREST device. """
2015-09-05 11:09:55 +00:00
try:
2015-10-18 16:05:25 +00:00
if self._pin is None:
response = requests.get(self._resource, timeout=10)
self.data = response.json()['variables']
else:
try:
if str(self._pin[0]) == 'A':
response = requests.get('{}/analog/{}'.format(
self._resource, self._pin[1:]), timeout=10)
self.data = {'value': response.json()['return_value']}
else:
_LOGGER.error("Wrong pin naming. "
"Please check your configuration file.")
except TypeError:
response = requests.get('{}/digital/{}'.format(
self._resource, self._pin), timeout=10)
self.data = {'value': response.json()['return_value']}
2015-10-09 06:50:04 +00:00
except requests.exceptions.ConnectionError:
2015-10-18 16:05:25 +00:00
_LOGGER.error("No route to device %s. Is device offline?",
self._resource)
2015-10-09 06:50:04 +00:00
self.data = {'error': 'error fetching'}