Add closest template helper

This commit is contained in:
Paulus Schoutsen committed 2016-02-21 11:13:40 -08:00
1 parent 9f5f13644a
commit c3bb6d32aa
4 files changed
+360 -7

No files matched your search

+79 -6
View File
@@ -10,10 +10,12 @@ import logging
import jinja2
from jinja2.sandbox import ImmutableSandboxedEnvironment
from homeassistant.components import group
from homeassistant.const import STATE_UNKNOWN, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.core import State
from homeassistant.exceptions import TemplateError
from homeassistant.util import convert, dt as dt_util, location
from homeassistant.helpers import location as loc_helper
from homeassistant.util import convert, dt as dt_util, location as loc_util
_LOGGER = logging.getLogger(__name__)
_SENTINEL = object()
@@ -43,16 +45,17 @@ def render(hass, template, variables=None, **kwargs):
if variables is not None:
kwargs.update(variables)
location_helper = LocationHelpers(hass)
location_methods = LocationMethods(hass)
utcnow = dt_util.utcnow()
try:
return ENV.from_string(template, {
'distance': location_helper.distance,
'closest': location_methods.closest,
'distance': location_methods.distance,
'is_state': hass.states.is_state,
'is_state_attr': hass.states.is_state_attr,
'states': AllStates(hass),
'now': dt_util.as_local(utcnow),
'states': AllStates(hass),
'utcnow': utcnow,
}).render(kwargs).strip()
except jinja2.TemplateError as err:
@@ -93,13 +96,75 @@ class DomainStates(object):
key=lambda state: state.entity_id))
class LocationHelpers(object):
class LocationMethods(object):
"""Class to expose distance helpers to templates."""
def __init__(self, hass):
"""Initialize distance helpers."""
self._hass = hass
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):
entity_id = entities.entity_id
else:
entity_id = str(entities)
states = [self._hass.states.get(entity_id) for entity_id
in group.expand_entity_ids(self._hass, [entity_id])]
return loc_helper.closest(latitude, longitude, states)
def distance(self, *args):
"""Calculate distance.
@@ -145,7 +210,15 @@ class LocationHelpers(object):
if len(locations) == 1:
return self._hass.config.distance(*locations[0])
return location.distance(*locations[0] + locations[1])
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
def forgiving_round(value, precision=0):