2016-03-07 22:39:52 +00:00
|
|
|
"""Template helper methods for rendering strings with HA data."""
|
2015-12-10 00:20:09 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
2015-12-11 05:38:35 +00:00
|
|
|
import json
|
2015-12-12 03:07:03 +00:00
|
|
|
import logging
|
2016-02-19 05:27:50 +00:00
|
|
|
|
2015-12-12 03:07:03 +00:00
|
|
|
import jinja2
|
2015-12-11 05:16:05 +00:00
|
|
|
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
2016-02-19 05:27:50 +00:00
|
|
|
|
2016-02-21 19:13:40 +00:00
|
|
|
from homeassistant.components import group
|
2016-02-21 05:58:53 +00:00
|
|
|
from homeassistant.const import STATE_UNKNOWN, ATTR_LATITUDE, ATTR_LONGITUDE
|
|
|
|
from homeassistant.core import State
|
2015-12-12 03:07:03 +00:00
|
|
|
from homeassistant.exceptions import TemplateError
|
2016-02-21 19:13:40 +00:00
|
|
|
from homeassistant.helpers import location as loc_helper
|
|
|
|
from homeassistant.util import convert, dt as dt_util, location as loc_util
|
2015-12-12 03:07:03 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2015-12-12 18:35:15 +00:00
|
|
|
_SENTINEL = object()
|
2015-12-10 00:20:09 +00:00
|
|
|
|
|
|
|
|
2015-12-12 18:35:15 +00:00
|
|
|
def render_with_possible_json_value(hass, template, value,
|
|
|
|
error_value=_SENTINEL):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Render template with value exposed.
|
|
|
|
|
2016-02-23 20:06:50 +00:00
|
|
|
If valid JSON will expose value_json too.
|
|
|
|
"""
|
2015-12-11 05:38:35 +00:00
|
|
|
variables = {
|
|
|
|
'value': value
|
|
|
|
}
|
|
|
|
try:
|
|
|
|
variables['value_json'] = json.loads(value)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
2015-12-12 03:07:03 +00:00
|
|
|
try:
|
|
|
|
return render(hass, template, variables)
|
|
|
|
except TemplateError:
|
|
|
|
_LOGGER.exception('Error parsing value')
|
2015-12-12 18:35:15 +00:00
|
|
|
return value if error_value is _SENTINEL else error_value
|
2015-12-11 05:38:35 +00:00
|
|
|
|
|
|
|
|
2015-12-11 05:16:05 +00:00
|
|
|
def render(hass, template, variables=None, **kwargs):
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Render given template."""
|
2015-12-11 05:16:05 +00:00
|
|
|
if variables is not None:
|
|
|
|
kwargs.update(variables)
|
|
|
|
|
2016-02-21 19:13:40 +00:00
|
|
|
location_methods = LocationMethods(hass)
|
2016-02-21 17:32:43 +00:00
|
|
|
utcnow = dt_util.utcnow()
|
2016-02-21 05:58:53 +00:00
|
|
|
|
2015-12-12 03:07:03 +00:00
|
|
|
try:
|
|
|
|
return ENV.from_string(template, {
|
2016-02-21 19:13:40 +00:00
|
|
|
'closest': location_methods.closest,
|
|
|
|
'distance': location_methods.distance,
|
2016-02-24 18:41:49 +00:00
|
|
|
'float': forgiving_float,
|
2015-12-31 20:58:18 +00:00
|
|
|
'is_state': hass.states.is_state,
|
2016-02-21 04:58:01 +00:00
|
|
|
'is_state_attr': hass.states.is_state_attr,
|
2016-02-21 17:32:43 +00:00
|
|
|
'now': dt_util.as_local(utcnow),
|
2016-02-21 19:13:40 +00:00
|
|
|
'states': AllStates(hass),
|
2016-02-21 17:32:43 +00:00
|
|
|
'utcnow': utcnow,
|
2015-12-13 06:19:12 +00:00
|
|
|
}).render(kwargs).strip()
|
2015-12-12 03:07:03 +00:00
|
|
|
except jinja2.TemplateError as err:
|
|
|
|
raise TemplateError(err)
|
2015-12-10 00:20:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AllStates(object):
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Class to expose all HA states as attributes."""
|
2016-03-07 22:39:52 +00:00
|
|
|
|
2015-12-10 00:20:09 +00:00
|
|
|
def __init__(self, hass):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Initialize all states."""
|
2015-12-10 00:20:09 +00:00
|
|
|
self._hass = hass
|
|
|
|
|
|
|
|
def __getattr__(self, name):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Return the domain state."""
|
2015-12-10 00:20:09 +00:00
|
|
|
return DomainStates(self._hass, name)
|
|
|
|
|
|
|
|
def __iter__(self):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Return all states."""
|
2015-12-10 00:20:09 +00:00
|
|
|
return iter(sorted(self._hass.states.all(),
|
|
|
|
key=lambda state: state.entity_id))
|
|
|
|
|
2015-12-13 06:19:37 +00:00
|
|
|
def __call__(self, entity_id):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Return the states."""
|
2015-12-13 06:19:37 +00:00
|
|
|
state = self._hass.states.get(entity_id)
|
|
|
|
return STATE_UNKNOWN if state is None else state.state
|
|
|
|
|
2015-12-10 00:20:09 +00:00
|
|
|
|
|
|
|
class DomainStates(object):
|
2016-02-23 20:06:50 +00:00
|
|
|
"""Class to expose a specific HA domain as attributes."""
|
2015-12-10 00:20:09 +00:00
|
|
|
|
|
|
|
def __init__(self, hass, domain):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Initialize the domain states."""
|
2015-12-10 00:20:09 +00:00
|
|
|
self._hass = hass
|
|
|
|
self._domain = domain
|
|
|
|
|
|
|
|
def __getattr__(self, name):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Return the states."""
|
2015-12-10 00:20:09 +00:00
|
|
|
return self._hass.states.get('{}.{}'.format(self._domain, name))
|
|
|
|
|
|
|
|
def __iter__(self):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Return the iteration over all the states."""
|
2015-12-10 00:20:09 +00:00
|
|
|
return iter(sorted(
|
|
|
|
(state for state in self._hass.states.all()
|
|
|
|
if state.domain == self._domain),
|
|
|
|
key=lambda state: state.entity_id))
|
2015-12-11 05:16:05 +00:00
|
|
|
|
|
|
|
|
2016-02-21 19:13:40 +00:00
|
|
|
class LocationMethods(object):
|
2016-02-21 05:58:53 +00:00
|
|
|
"""Class to expose distance helpers to templates."""
|
|
|
|
|
|
|
|
def __init__(self, hass):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""Initialize the distance helpers."""
|
2016-02-21 05:58:53 +00:00
|
|
|
self._hass = hass
|
|
|
|
|
2016-02-21 19:13:40 +00:00
|
|
|
def closest(self, *args):
|
|
|
|
"""Find closest entity.
|
|
|
|
|
|
|
|
Closest to home:
|
|
|
|
closest(states)
|
|
|
|
closest(states.device_tracker)
|
|
|
|
closest('group.children')
|
|
|
|
closest(states.group.children)
|
|
|
|
|
|
|
|
Closest to a point:
|
|
|
|
closest(23.456, 23.456, 'group.children')
|
|
|
|
closest('zone.school', 'group.children')
|
|
|
|
closest(states.zone.school, 'group.children')
|
|
|
|
"""
|
|
|
|
if len(args) == 1:
|
|
|
|
latitude = self._hass.config.latitude
|
|
|
|
longitude = self._hass.config.longitude
|
|
|
|
entities = args[0]
|
|
|
|
|
|
|
|
elif len(args) == 2:
|
|
|
|
point_state = self._resolve_state(args[0])
|
|
|
|
|
|
|
|
if point_state is None:
|
|
|
|
_LOGGER.warning('Closest:Unable to find state %s', args[0])
|
|
|
|
return None
|
|
|
|
elif not loc_helper.has_location(point_state):
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Closest:State does not contain valid location: %s',
|
|
|
|
point_state)
|
|
|
|
return None
|
|
|
|
|
|
|
|
latitude = point_state.attributes.get(ATTR_LATITUDE)
|
|
|
|
longitude = point_state.attributes.get(ATTR_LONGITUDE)
|
|
|
|
|
|
|
|
entities = args[1]
|
|
|
|
|
|
|
|
else:
|
|
|
|
latitude = convert(args[0], float)
|
|
|
|
longitude = convert(args[1], float)
|
|
|
|
|
|
|
|
if latitude is None or longitude is None:
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Closest:Received invalid coordinates: %s, %s',
|
|
|
|
args[0], args[1])
|
|
|
|
return None
|
|
|
|
|
|
|
|
entities = args[2]
|
|
|
|
|
|
|
|
if isinstance(entities, (AllStates, DomainStates)):
|
|
|
|
states = list(entities)
|
|
|
|
else:
|
|
|
|
if isinstance(entities, State):
|
2016-02-21 21:09:49 +00:00
|
|
|
gr_entity_id = entities.entity_id
|
2016-02-21 19:13:40 +00:00
|
|
|
else:
|
2016-02-21 21:09:49 +00:00
|
|
|
gr_entity_id = str(entities)
|
2016-02-21 19:13:40 +00:00
|
|
|
|
|
|
|
states = [self._hass.states.get(entity_id) for entity_id
|
2016-02-21 21:09:49 +00:00
|
|
|
in group.expand_entity_ids(self._hass, [gr_entity_id])]
|
2016-02-21 19:13:40 +00:00
|
|
|
|
|
|
|
return loc_helper.closest(latitude, longitude, states)
|
|
|
|
|
2016-02-21 05:58:53 +00:00
|
|
|
def distance(self, *args):
|
|
|
|
"""Calculate distance.
|
|
|
|
|
|
|
|
Will calculate distance from home to a point or between points.
|
|
|
|
Points can be passed in using state objects or lat/lng coordinates.
|
|
|
|
"""
|
|
|
|
locations = []
|
|
|
|
|
|
|
|
to_process = list(args)
|
|
|
|
|
|
|
|
while to_process:
|
|
|
|
value = to_process.pop(0)
|
|
|
|
|
|
|
|
if isinstance(value, State):
|
|
|
|
latitude = value.attributes.get(ATTR_LATITUDE)
|
|
|
|
longitude = value.attributes.get(ATTR_LONGITUDE)
|
|
|
|
|
|
|
|
if latitude is None or longitude is None:
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Distance:State does not contains a location: %s',
|
|
|
|
value)
|
|
|
|
return None
|
|
|
|
|
|
|
|
else:
|
|
|
|
# We expect this and next value to be lat&lng
|
|
|
|
if not to_process:
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Distance:Expected latitude and longitude, got %s',
|
|
|
|
value)
|
|
|
|
return None
|
|
|
|
|
|
|
|
value_2 = to_process.pop(0)
|
|
|
|
latitude = convert(value, float)
|
|
|
|
longitude = convert(value_2, float)
|
|
|
|
|
|
|
|
if latitude is None or longitude is None:
|
|
|
|
_LOGGER.warning('Distance:Unable to process latitude and '
|
|
|
|
'longitude: %s, %s', value, value_2)
|
|
|
|
return None
|
|
|
|
|
|
|
|
locations.append((latitude, longitude))
|
|
|
|
|
|
|
|
if len(locations) == 1:
|
|
|
|
return self._hass.config.distance(*locations[0])
|
|
|
|
|
2016-02-21 19:13:40 +00:00
|
|
|
return loc_util.distance(*locations[0] + locations[1])
|
|
|
|
|
|
|
|
def _resolve_state(self, entity_id_or_state):
|
|
|
|
"""Return state or entity_id if given."""
|
|
|
|
if isinstance(entity_id_or_state, State):
|
|
|
|
return entity_id_or_state
|
|
|
|
elif isinstance(entity_id_or_state, str):
|
|
|
|
return self._hass.states.get(entity_id_or_state)
|
|
|
|
return None
|
2016-02-21 05:58:53 +00:00
|
|
|
|
|
|
|
|
2015-12-11 05:16:05 +00:00
|
|
|
def forgiving_round(value, precision=0):
|
2016-02-21 05:59:16 +00:00
|
|
|
"""Rounding filter that accepts strings."""
|
2015-12-11 05:16:05 +00:00
|
|
|
try:
|
2015-12-12 02:45:53 +00:00
|
|
|
value = round(float(value), precision)
|
|
|
|
return int(value) if precision == 0 else value
|
2016-02-21 05:59:16 +00:00
|
|
|
except (ValueError, TypeError):
|
2015-12-11 05:16:05 +00:00
|
|
|
# If value can't be converted to float
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
def multiply(value, amount):
|
2016-02-21 05:59:16 +00:00
|
|
|
"""Filter to convert value to float and multiply it."""
|
2015-12-11 05:16:05 +00:00
|
|
|
try:
|
|
|
|
return float(value) * amount
|
2016-02-21 19:12:37 +00:00
|
|
|
except (ValueError, TypeError):
|
2015-12-11 05:16:05 +00:00
|
|
|
# If value can't be converted to float
|
|
|
|
return value
|
|
|
|
|
2015-12-13 06:19:37 +00:00
|
|
|
|
2016-02-24 18:41:49 +00:00
|
|
|
def forgiving_float(value):
|
|
|
|
"""Try to convert value to a float."""
|
|
|
|
try:
|
|
|
|
return float(value)
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
2015-12-13 06:19:37 +00:00
|
|
|
class TemplateEnvironment(ImmutableSandboxedEnvironment):
|
2016-03-07 22:39:52 +00:00
|
|
|
"""The Home Assistant template environment."""
|
2016-03-09 10:15:04 +00:00
|
|
|
|
2015-12-13 06:19:37 +00:00
|
|
|
def is_safe_callable(self, obj):
|
2016-02-21 05:59:16 +00:00
|
|
|
"""Test if callback is safe."""
|
2015-12-13 06:19:37 +00:00
|
|
|
return isinstance(obj, AllStates) or super().is_safe_callable(obj)
|
|
|
|
|
|
|
|
ENV = TemplateEnvironment()
|
2015-12-11 05:16:05 +00:00
|
|
|
ENV.filters['round'] = forgiving_round
|
|
|
|
ENV.filters['multiply'] = multiply
|