core/homeassistant/components/arest/sensor.py

219 lines
6.6 KiB
Python
Raw Normal View History

"""Support for an exposed aREST RESTful API of a device."""
2016-02-19 05:27:50 +00:00
from datetime import timedelta
import logging
2015-11-29 21:49:05 +00:00
2015-10-09 06:50:04 +00:00
import requests
import voluptuous as vol
2015-09-05 11:09:55 +00:00
from homeassistant.components.sensor import PLATFORM_SCHEMA
2016-02-19 05:27:50 +00:00
from homeassistant.const import (
2019-07-31 19:25:30 +00:00
CONF_MONITORED_VARIABLES,
CONF_NAME,
CONF_RESOURCE,
CONF_UNIT_OF_MEASUREMENT,
CONF_VALUE_TEMPLATE,
2019-07-31 19:25:30 +00:00
)
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
2015-11-29 21:49:05 +00:00
from homeassistant.helpers.entity import Entity
2016-02-23 20:06:50 +00:00
from homeassistant.util import Throttle
2015-09-05 11:09:55 +00:00
_LOGGER = logging.getLogger(__name__)
2015-10-17 22:41:12 +00:00
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=30)
2019-07-31 19:25:30 +00:00
CONF_FUNCTIONS = "functions"
CONF_PINS = "pins"
DEFAULT_NAME = "aREST sensor"
PIN_VARIABLE_SCHEMA = vol.Schema(
{
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_RESOURCE): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PINS, default={}): vol.Schema(
{cv.string: PIN_VARIABLE_SCHEMA}
),
vol.Optional(CONF_MONITORED_VARIABLES, default={}): vol.Schema(
{cv.string: PIN_VARIABLE_SCHEMA}
),
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the aREST sensor."""
2015-10-09 06:50:04 +00:00
resource = config.get(CONF_RESOURCE)
var_conf = config.get(CONF_MONITORED_VARIABLES)
pins = config.get(CONF_PINS)
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:
2019-07-31 19:25:30 +00:00
_LOGGER.error(
"Missing resource or schema in configuration. Add http:// to your URL"
2019-07-31 19:25:30 +00:00
)
2015-09-05 11:09:55 +00:00
return False
2015-10-09 06:50:04 +00:00
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device at %s", 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
2015-12-15 21:16:52 +00:00
def make_renderer(value_template):
2016-03-08 15:46:34 +00:00
"""Create a renderer based on variable_template value."""
2015-12-15 21:16:52 +00:00
if value_template is None:
return lambda value: value
value_template.hass = hass
def _render(value):
try:
2019-07-31 19:25:30 +00:00
return value_template.async_render({"value": value})
except TemplateError:
_LOGGER.exception("Error parsing value")
return value
return _render
2015-12-15 21:16:52 +00:00
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, var_data in var_conf.items():
2019-07-31 19:25:30 +00:00
if variable not in response["variables"]:
_LOGGER.error("Variable: %s does not exist", variable)
2015-10-27 22:51:16 +00:00
continue
renderer = make_renderer(var_data.get(CONF_VALUE_TEMPLATE))
2019-07-31 19:25:30 +00:00
dev.append(
ArestSensor(
arest,
resource,
config.get(CONF_NAME, response[CONF_NAME]),
var_data.get(CONF_NAME, variable),
variable=variable,
unit_of_measurement=var_data.get(CONF_UNIT_OF_MEASUREMENT),
renderer=renderer,
)
)
2015-10-27 22:51:16 +00:00
if pins is not None:
for pinnum, pin in pins.items():
2015-12-15 21:16:52 +00:00
renderer = make_renderer(pin.get(CONF_VALUE_TEMPLATE))
2019-07-31 19:25:30 +00:00
dev.append(
ArestSensor(
ArestData(resource, pinnum),
resource,
config.get(CONF_NAME, response[CONF_NAME]),
pin.get(CONF_NAME),
pin=pinnum,
unit_of_measurement=pin.get(CONF_UNIT_OF_MEASUREMENT),
renderer=renderer,
)
)
2015-09-05 11:09:55 +00:00
add_entities(dev, True)
2015-09-05 11:09:55 +00:00
class ArestSensor(Entity):
2016-03-08 15:46:34 +00:00
"""Implementation of an aREST sensor for exposed variables."""
2015-09-05 11:09:55 +00:00
2019-07-31 19:25:30 +00:00
def __init__(
self,
arest,
resource,
location,
name,
variable=None,
pin=None,
unit_of_measurement=None,
renderer=None,
):
2016-03-08 15:46:34 +00:00
"""Initialize the sensor."""
2015-10-09 06:50:04 +00:00
self.arest = arest
2015-10-18 16:05:25 +00:00
self._resource = resource
self._name = f"{location.title()} {name.title()}"
2015-09-05 11:09:55 +00:00
self._variable = variable
2015-10-18 16:05:25 +00:00
self._pin = pin
self._state = None
2015-09-05 11:09:55 +00:00
self._unit_of_measurement = unit_of_measurement
2015-12-15 21:16:52 +00:00
self._renderer = renderer
2015-09-05 11:09:55 +00:00
2015-10-18 16:05:25 +00:00
if self._pin is not None:
request = requests.get(f"{self._resource}/mode/{self._pin}/i", timeout=10)
if request.status_code != 200:
_LOGGER.error("Can't set mode of %s", self._resource)
2015-10-18 16:05:25 +00:00
2015-09-05 11:09:55 +00:00
@property
def name(self):
2016-03-08 15:46:34 +00:00
"""Return the name of the sensor."""
2015-09-05 11:09:55 +00:00
return self._name
@property
def unit_of_measurement(self):
2016-03-08 15:46:34 +00:00
"""Return the unit the value is expressed in."""
2015-09-05 11:09:55 +00:00
return self._unit_of_measurement
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the sensor."""
2015-10-09 06:50:04 +00:00
values = self.arest.data
2019-07-31 19:25:30 +00:00
if "error" in values:
return values["error"]
2015-12-15 21:16:52 +00:00
2019-07-31 19:25:30 +00:00
value = self._renderer(values.get("value", values.get(self._variable, None)))
2015-12-15 21:16:52 +00:00
return value
2015-10-09 06:50:04 +00:00
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from aREST API."""
2015-10-09 06:50:04 +00:00
self.arest.update()
2015-09-05 11:09:55 +00:00
2016-10-04 07:51:45 +00:00
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self.arest.available
2015-09-05 11:09:55 +00:00
class ArestData:
2016-03-08 15:46:34 +00:00
"""The 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):
2016-03-08 15:46:34 +00:00
"""Initialize the data object."""
2015-10-18 16:05:25 +00:00
self._resource = resource
self._pin = pin
2015-10-09 06:50:04 +00:00
self.data = {}
2016-10-04 07:51:45 +00:00
self.available = True
2015-09-05 11:09:55 +00:00
@Throttle(MIN_TIME_BETWEEN_UPDATES)
2015-09-05 11:09:55 +00:00
def update(self):
2016-03-08 15:46:34 +00:00
"""Get 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)
2019-07-31 19:25:30 +00:00
self.data = response.json()["variables"]
2015-10-18 16:05:25 +00:00
else:
try:
2019-07-31 19:25:30 +00:00
if str(self._pin[0]) == "A":
response = requests.get(
f"{self._resource,}/analog/{self._pin[1:]}", timeout=10
2019-07-31 19:25:30 +00:00
)
self.data = {"value": response.json()["return_value"]}
2015-10-18 16:05:25 +00:00
except TypeError:
2019-07-31 19:25:30 +00:00
response = requests.get(
f"{self._resource}/digital/{self._pin}", timeout=10
2019-07-31 19:25:30 +00:00
)
self.data = {"value": response.json()["return_value"]}
2016-10-04 07:51:45 +00:00
self.available = True
2015-10-09 06:50:04 +00:00
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to device %s", self._resource)
2016-10-04 07:51:45 +00:00
self.available = False