hass-core/homeassistant/util/template.py

180 lines
5.4 KiB
Python
Raw Normal View History

2015-12-09 16:20:09 -08:00
"""
homeassistant.util.template
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Template utility methods for rendering strings with HA data.
"""
# pylint: disable=too-few-public-methods
2015-12-10 21:38:35 -08:00
import json
import logging
2016-02-18 21:27:50 -08:00
import jinja2
from jinja2.sandbox import ImmutableSandboxedEnvironment
2016-02-18 21:27:50 -08:00
2016-02-20 21:58:53 -08:00
from homeassistant.const import STATE_UNKNOWN, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.core import State
from homeassistant.exceptions import TemplateError
2016-02-20 21:58:53 -08:00
from homeassistant.util import convert, dt as dt_util, location
_LOGGER = logging.getLogger(__name__)
_SENTINEL = object()
2015-12-09 16:20:09 -08:00
def render_with_possible_json_value(hass, template, value,
error_value=_SENTINEL):
2015-12-10 21:38:35 -08:00
""" Renders template with value exposed.
If valid JSON will expose value_json too. """
variables = {
'value': value
}
try:
variables['value_json'] = json.loads(value)
except ValueError:
pass
try:
return render(hass, template, variables)
except TemplateError:
_LOGGER.exception('Error parsing value')
return value if error_value is _SENTINEL else error_value
2015-12-10 21:38:35 -08:00
def render(hass, template, variables=None, **kwargs):
2015-12-09 16:20:09 -08:00
""" Render given template. """
if variables is not None:
kwargs.update(variables)
2016-02-20 21:58:53 -08:00
location_helper = LocationHelpers(hass)
utcnow = dt_util.utcnow()
2016-02-20 21:58:53 -08:00
try:
return ENV.from_string(template, {
2016-02-20 21:58:53 -08:00
'distance': location_helper.distance,
'is_state': hass.states.is_state,
'is_state_attr': hass.states.is_state_attr,
2016-02-20 21:58:53 -08:00
'states': AllStates(hass),
'now': dt_util.as_local(utcnow),
'utcnow': utcnow,
2015-12-12 22:19:12 -08:00
}).render(kwargs).strip()
except jinja2.TemplateError as err:
raise TemplateError(err)
2015-12-09 16:20:09 -08:00
class AllStates(object):
""" Class to expose all HA states as attributes. """
def __init__(self, hass):
self._hass = hass
def __getattr__(self, name):
return DomainStates(self._hass, name)
def __iter__(self):
return iter(sorted(self._hass.states.all(),
key=lambda state: state.entity_id))
2015-12-12 22:19:37 -08:00
def __call__(self, entity_id):
state = self._hass.states.get(entity_id)
return STATE_UNKNOWN if state is None else state.state
2015-12-09 16:20:09 -08:00
class DomainStates(object):
""" Class to expose a specific HA domain as attributes. """
def __init__(self, hass, domain):
self._hass = hass
self._domain = domain
def __getattr__(self, name):
return self._hass.states.get('{}.{}'.format(self._domain, name))
def __iter__(self):
return iter(sorted(
(state for state in self._hass.states.all()
if state.domain == self._domain),
key=lambda state: state.entity_id))
2016-02-20 21:58:53 -08:00
class LocationHelpers(object):
"""Class to expose distance helpers to templates."""
def __init__(self, hass):
"""Initialize distance helpers."""
self._hass = hass
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])
return location.distance(*locations[0] + locations[1])
def forgiving_round(value, precision=0):
2016-02-20 21:59:16 -08:00
"""Rounding filter that accepts strings."""
try:
2015-12-11 18:45:53 -08:00
value = round(float(value), precision)
return int(value) if precision == 0 else value
2016-02-20 21:59:16 -08:00
except (ValueError, TypeError):
# If value can't be converted to float
return value
def multiply(value, amount):
2016-02-20 21:59:16 -08:00
"""Filter to convert value to float and multiply it."""
try:
return float(value) * amount
except ValueError:
# If value can't be converted to float
return value
2015-12-12 22:19:37 -08:00
class TemplateEnvironment(ImmutableSandboxedEnvironment):
2016-02-20 21:59:16 -08:00
"""Home Assistant template environment."""
2015-12-12 22:19:37 -08:00
def is_safe_callable(self, obj):
2016-02-20 21:59:16 -08:00
"""Test if callback is safe."""
2015-12-12 22:19:37 -08:00
return isinstance(obj, AllStates) or super().is_safe_callable(obj)
ENV = TemplateEnvironment()
ENV.filters['round'] = forgiving_round
ENV.filters['multiply'] = multiply