core/homeassistant/helpers/template.py

635 lines
20 KiB
Python
Raw Normal View History

"""Template helper methods for rendering strings with Home Assistant data."""
2016-11-11 06:57:44 +00:00
from datetime import datetime
2015-12-11 05:38:35 +00:00
import json
import logging
import math
import random
import re
2016-02-19 05:27:50 +00:00
import jinja2
from jinja2 import contextfilter
from jinja2.sandbox import ImmutableSandboxedEnvironment
2016-02-19 05:27:50 +00:00
from homeassistant.const import (
ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_UNIT_OF_MEASUREMENT, MATCH_ALL,
STATE_UNKNOWN)
from homeassistant.core import State, valid_entity_id
from homeassistant.exceptions import TemplateError
2016-02-21 19:13:40 +00:00
from homeassistant.helpers import location as loc_helper
from homeassistant.loader import bind_hass, get_component
from homeassistant.util import convert
from homeassistant.util import dt as dt_util
from homeassistant.util import location as loc_util
from homeassistant.util.async_ import run_callback_threadsafe
_LOGGER = logging.getLogger(__name__)
_SENTINEL = object()
2016-07-23 02:47:43 +00:00
DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S"
2015-12-10 00:20:09 +00:00
_RE_NONE_ENTITIES = re.compile(r"distance\(|closest\(", re.I | re.M)
_RE_GET_ENTITIES = re.compile(
r"(?:(?:states\.|(?:is_state|is_state_attr|state_attr|states)"
r"\((?:[\ \'\"]?))([\w]+\.[\w]+)|([\w]+))", re.I | re.M
)
2015-12-10 00:20:09 +00:00
2015-12-11 05:38:35 +00:00
@bind_hass
def attach(hass, obj):
"""Recursively attach hass to all template instances in list and dict."""
if isinstance(obj, list):
for child in obj:
attach(hass, child)
elif isinstance(obj, dict):
for child in obj.values():
attach(hass, child)
elif isinstance(obj, Template):
obj.hass = hass
2015-12-11 05:38:35 +00:00
2016-05-12 05:44:44 +00:00
def render_complex(value, variables=None):
"""Recursive template creator helper function."""
if isinstance(value, list):
return [render_complex(item, variables)
for item in value]
elif isinstance(value, dict):
return {key: render_complex(item, variables)
for key, item in value.items()}
return value.async_render(variables)
def extract_entities(template, variables=None):
"""Extract all entities for state_changed listener from template string."""
if template is None or _RE_NONE_ENTITIES.search(template):
return MATCH_ALL
extraction = _RE_GET_ENTITIES.findall(template)
extraction_final = []
for result in extraction:
if result[0] == 'trigger.entity_id' and 'trigger' in variables and \
'entity_id' in variables['trigger']:
extraction_final.append(variables['trigger']['entity_id'])
elif result[0]:
extraction_final.append(result[0])
if variables and result[1] in variables and \
isinstance(variables[result[1]], str) and \
valid_entity_id(variables[result[1]]):
extraction_final.append(variables[result[1]])
if extraction_final:
return list(set(extraction_final))
return MATCH_ALL
class Template(object):
"""Class to hold a template and manage caching and rendering."""
def __init__(self, template, hass=None):
"""Instantiate a template."""
if not isinstance(template, str):
raise TypeError('Expected template to be a string')
self.template = template
self._compiled_code = None
self._compiled = None
self.hass = hass
def ensure_valid(self):
"""Return if template is valid."""
if self._compiled_code is not None:
return
try:
self._compiled_code = ENV.compile(self.template)
except jinja2.exceptions.TemplateSyntaxError as err:
raise TemplateError(err)
def extract_entities(self, variables=None):
"""Extract all entities for state_changed listener."""
return extract_entities(self.template, variables)
def render(self, variables=None, **kwargs):
"""Render given template."""
if variables is not None:
kwargs.update(variables)
return run_callback_threadsafe(
self.hass.loop, self.async_render, kwargs).result()
def async_render(self, variables=None, **kwargs):
"""Render given template.
This method must be run in the event loop.
"""
if self._compiled is None:
self._ensure_compiled()
if variables is not None:
kwargs.update(variables)
try:
return self._compiled.render(kwargs).strip()
except jinja2.TemplateError as err:
raise TemplateError(err)
def render_with_possible_json_value(self, value, error_value=_SENTINEL):
"""Render template with value exposed.
If valid JSON will expose value_json too.
"""
return run_callback_threadsafe(
self.hass.loop, self.async_render_with_possible_json_value, value,
error_value).result()
# pylint: disable=invalid-name
def async_render_with_possible_json_value(self, value,
error_value=_SENTINEL):
"""Render template with value exposed.
If valid JSON will expose value_json too.
This method must be run in the event loop.
"""
if self._compiled is None:
self._ensure_compiled()
variables = {
'value': value
}
try:
variables['value_json'] = json.loads(value)
except ValueError:
pass
try:
return self._compiled.render(variables).strip()
except jinja2.TemplateError as ex:
_LOGGER.error("Error parsing value: %s (value: %s, template: %s)",
ex, value, self.template)
return value if error_value is _SENTINEL else error_value
def _ensure_compiled(self):
"""Bind a template to a specific hass instance."""
self.ensure_valid()
assert self.hass is not None, 'hass variable not set on template'
template_methods = TemplateMethods(self.hass)
global_vars = ENV.make_globals({
'closest': template_methods.closest,
'distance': template_methods.distance,
'is_state': self.hass.states.is_state,
'is_state_attr': template_methods.is_state_attr,
'state_attr': template_methods.state_attr,
'states': AllStates(self.hass),
})
self._compiled = jinja2.Template.from_code(
ENV, self._compiled_code, global_vars, None)
return self._compiled
2015-12-10 00:20:09 +00:00
def __eq__(self, other):
"""Compare template with another."""
return (self.__class__ == other.__class__ and
self.template == other.template and
self.hass == other.hass)
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."""
return iter(
_wrap_state(state) for state in
sorted(self._hass.states.async_all(),
key=lambda state: state.entity_id))
2015-12-10 00:20:09 +00:00
def __len__(self):
"""Return number of states."""
return len(self._hass.states.async_entity_ids())
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."""
return _wrap_state(
self._hass.states.get('{}.{}'.format(self._domain, name)))
2015-12-10 00:20:09 +00:00
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(
(_wrap_state(state) for state in self._hass.states.async_all()
2015-12-10 00:20:09 +00:00
if state.domain == self._domain),
key=lambda state: state.entity_id))
def __len__(self):
"""Return number of states."""
return len(self._hass.states.async_entity_ids(self._domain))
class TemplateState(State):
"""Class to represent a state object in a template."""
# Inheritance is done so functions that check against State keep working
# pylint: disable=super-init-not-called
def __init__(self, state):
"""Initialize template state."""
self._state = state
@property
def state_with_unit(self):
"""Return the state concatenated with the unit if available."""
state = object.__getattribute__(self, '_state')
unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if unit is None:
return state.state
return "{} {}".format(state.state, unit)
def __getattribute__(self, name):
"""Return an attribute of the state."""
if name in TemplateState.__dict__:
return object.__getattribute__(self, name)
return getattr(object.__getattribute__(self, '_state'), name)
def __repr__(self):
"""Representation of Template State."""
rep = object.__getattribute__(self, '_state').__repr__()
return '<template ' + rep[1:]
def _wrap_state(state):
"""Wrap a state."""
return None if state is None else TemplateState(state)
class TemplateMethods(object):
"""Class to expose helpers to templates."""
2016-02-21 05:58:53 +00:00
def __init__(self, hass):
"""Initialize the 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])
2016-02-21 19:13:40 +00:00
return None
elif not loc_helper.has_location(point_state):
_LOGGER.warning(
"Closest:State does not contain valid location: %s",
2016-02-21 19:13:40 +00:00
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",
2016-02-21 19:13:40 +00:00
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
group = get_component('group')
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 _wrap_state(loc_helper.closest(latitude, longitude, states))
2016-02-21 19:13:40 +00:00
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",
2016-02-21 05:58:53 +00:00
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",
2016-02-21 05:58:53 +00:00
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)
2016-02-21 05:58:53 +00:00
return None
locations.append((latitude, longitude))
if len(locations) == 1:
return self._hass.config.distance(*locations[0])
Add unit system support Add unit symbol constants Initial unit system object Import more constants Pydoc for unit system file Import constants for configuration validation Unit system validation method Typing for constants Inches are valid lengths too Typings Change base class to dict - needed for remote api call serialization Validation Use dictionary keys Defined unit systems Update location util to use metric instead of us fahrenheit Update constant imports Import defined unit systems Update configuration to use unit system Update schema to use unit system Update constants Add imports to core for unit system and distance Type for config Default unit system Convert distance from HASS instance Update temperature conversion to use unit system Update temperature conversion Set unit system based on configuration Set info unit system Return unit system dictionary with config dictionary Auto discover unit system Update location test for use metric Update forecast unit system Update mold indicator unit system Update thermostat unit system Update thermostat demo test Unit tests around unit system Update test common hass configuration Update configuration unit tests There should always be a unit system! Update core unit tests Constants typing Linting issues Remove unused import Update fitbit sensor to use application unit system Update google travel time to use application unit system Update configuration example Update dht sensor Update DHT temperature conversion to use the utility function Update swagger config Update my sensors metric flag Update hvac component temperature conversion HVAC conversion for temperature Pull unit from sensor type map Pull unit from sensor type map Update the temper sensor unit Update yWeather sensor unit Update hvac demo unit test Set unit test config unit system to metric Use hass unit system length for default in proximity Use the name of the system instead of temperature Use constants from const Unused import Forecasted temperature Fix calculation in case furthest distance is greater than 1000000 units Remove unneeded constants Set default length to km or miles Use constants Linting doesn't like importing just for typing Fix reference Test is expecting meters - set config to meters Use constant Use constant PyDoc for unit test Should be not in Rename to units Change unit system to be an object - not a dictionary Return tuple in conversion Move convert to temperature util Temperature conversion is now in unit system Update imports Rename to units Units is now an object Use temperature util conversion Unit system is now an object Validate and convert unit system config Return the scalar value in template distance Test is expecting meters Update unit tests around unit system Distance util returns tuple Fix location info test Set units Update unit tests Convert distance DOH Pull out the scalar from the vector Linting I really hate python linting Linting again BLARG Unit test documentation Unit test around is metric flag Break ternary statement into if/else blocks Don't use dictionary - use members is metric flag Rename constants Use is metric flag Move constants to CONST file Move to const file Raise error if unit is not expected Typing No need to return unit since only performing conversion if it can work Use constants Line wrapping Raise error if invalid value Remove subscripts from conversion as they are no longer returned as tuples No longer tuples No longer tuples Check for numeric type Fix string format to use correct variable Typing Assert errors raised Remove subscript Only convert temperature if we know the unit If no unit of measurement set - default to HASS config Convert only if we know the unit Remove subscription Fix not in clause Linting fixes Wants a boolean Clearer if-block Check if the key is in the config first Missed a couple expecting tuples Backwards compatibility No like-y ternary! Error handling around state setting Pretty unit system configuration validation More tuple crap Use is metric flag Error handling around min/max temp Explode if no unit Pull unit from config Celsius has a decimal Unused import Check if it's a temperature before we try to convert it to a temperature Linting says too many statements - combine lat/long in a fairly reasonable manner Backwards compatibility unit test Better doc
2016-07-31 20:24:49 +00:00
return self._hass.config.units.length(
loc_util.distance(*locations[0] + locations[1]), 'm')
2016-02-21 19:13:40 +00:00
def is_state_attr(self, entity_id, name, value):
"""Test if a state is a specific attribute."""
state_attr = self.state_attr(entity_id, name)
return state_attr is not None and state_attr == value
def state_attr(self, entity_id, name):
"""Get a specific attribute from a state."""
state_obj = self._hass.states.get(entity_id)
if state_obj is not None:
return state_obj.attributes.get(name)
return None
2016-02-21 19:13:40 +00:00
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
def forgiving_round(value, precision=0):
"""Round accepted strings."""
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):
# 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."""
try:
return float(value) * amount
2016-02-21 19:12:37 +00:00
except (ValueError, TypeError):
# If value can't be converted to float
return value
2015-12-13 06:19:37 +00:00
def logarithm(value, base=math.e):
"""Filter to get logarithm of the value with a specific base."""
try:
return math.log(float(value), float(base))
except (ValueError, TypeError):
return value
def sine(value):
"""Filter to get sine of the value."""
try:
return math.sin(float(value))
except (ValueError, TypeError):
return value
def cosine(value):
"""Filter to get cosine of the value."""
try:
return math.cos(float(value))
except (ValueError, TypeError):
return value
def tangent(value):
"""Filter to get tangent of the value."""
try:
return math.tan(float(value))
except (ValueError, TypeError):
return value
def square_root(value):
"""Filter to get square root of the value."""
try:
return math.sqrt(float(value))
except (ValueError, TypeError):
return value
def timestamp_custom(value, date_format=DATE_STR_FORMAT, local=True):
"""Filter to convert given timestamp to format."""
try:
date = dt_util.utc_from_timestamp(value)
if local:
date = dt_util.as_local(date)
return date.strftime(date_format)
except (ValueError, TypeError):
# If timestamp can't be converted
return value
2016-07-23 02:47:43 +00:00
def timestamp_local(value):
"""Filter to convert given timestamp to local date/time."""
try:
return dt_util.as_local(
dt_util.utc_from_timestamp(value)).strftime(DATE_STR_FORMAT)
except (ValueError, TypeError):
# If timestamp can't be converted
return value
def timestamp_utc(value):
"""Filter to convert given timestamp to UTC date/time."""
2016-07-23 02:47:43 +00:00
try:
return dt_util.utc_from_timestamp(value).strftime(DATE_STR_FORMAT)
except (ValueError, TypeError):
# If timestamp can't be converted
return value
def forgiving_as_timestamp(value):
"""Try to convert value to timestamp."""
try:
return dt_util.as_timestamp(value)
except (ValueError, TypeError):
return None
2016-11-11 06:57:44 +00:00
def strptime(string, fmt):
"""Parse a time string to datetime."""
try:
return datetime.strptime(string, fmt)
except (ValueError, AttributeError):
return string
def fail_when_undefined(value):
"""Filter to force a failure when the value is undefined."""
if isinstance(value, jinja2.Undefined):
value()
return value
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
def regex_match(value, find='', ignorecase=False):
"""Match value using regex."""
if not isinstance(value, str):
value = str(value)
flags = re.I if ignorecase else 0
return bool(re.match(find, value, flags))
def regex_replace(value='', find='', replace='', ignorecase=False):
"""Replace using regex."""
if not isinstance(value, str):
value = str(value)
flags = re.I if ignorecase else 0
regex = re.compile(find, flags)
return regex.sub(replace, value)
def regex_search(value, find='', ignorecase=False):
"""Search using regex."""
if not isinstance(value, str):
value = str(value)
flags = re.I if ignorecase else 0
return bool(re.search(find, value, flags))
def regex_findall_index(value, find='', index=0, ignorecase=False):
"""Find all matches using regex and then pick specific match index."""
if not isinstance(value, str):
value = str(value)
flags = re.I if ignorecase else 0
return re.findall(find, value, flags)[index]
@contextfilter
def random_every_time(context, values):
"""Choose a random value.
Unlike Jinja's random filter,
this is context-dependent to avoid caching the chosen value.
"""
return random.choice(values)
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)
2016-11-19 05:47:59 +00:00
ENV = TemplateEnvironment()
ENV.filters['round'] = forgiving_round
ENV.filters['multiply'] = multiply
ENV.filters['log'] = logarithm
ENV.filters['sin'] = sine
ENV.filters['cos'] = cosine
ENV.filters['tan'] = tangent
ENV.filters['sqrt'] = square_root
ENV.filters['timestamp_custom'] = timestamp_custom
2016-07-23 02:47:43 +00:00
ENV.filters['timestamp_local'] = timestamp_local
ENV.filters['timestamp_utc'] = timestamp_utc
ENV.filters['is_defined'] = fail_when_undefined
2017-02-07 08:25:47 +00:00
ENV.filters['max'] = max
ENV.filters['min'] = min
ENV.filters['random'] = random_every_time
ENV.filters['regex_match'] = regex_match
ENV.filters['regex_replace'] = regex_replace
ENV.filters['regex_search'] = regex_search
ENV.filters['regex_findall_index'] = regex_findall_index
ENV.globals['log'] = logarithm
ENV.globals['sin'] = sine
ENV.globals['cos'] = cosine
ENV.globals['tan'] = tangent
ENV.globals['sqrt'] = square_root
ENV.globals['pi'] = math.pi
ENV.globals['tau'] = math.pi * 2
ENV.globals['e'] = math.e
ENV.globals['float'] = forgiving_float
ENV.globals['now'] = dt_util.now
ENV.globals['utcnow'] = dt_util.utcnow
ENV.globals['as_timestamp'] = forgiving_as_timestamp
ENV.globals['relative_time'] = dt_util.get_age
2016-11-11 06:57:44 +00:00
ENV.globals['strptime'] = strptime