Added resolve_state to template distance function (#17290)

_resolve_state was already used in the "closest" function, to allow for states and entity ids
This commit is contained in:
Markus Nigbur 2018-10-10 11:49:24 +02:00 committed by Paulus Schoutsen
parent 419725e1a9
commit 670c75e844
2 changed files with 44 additions and 11 deletions

View File

@ -367,18 +367,9 @@ class TemplateMethods:
while to_process:
value = to_process.pop(0)
point_state = self._resolve_state(value)
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:
if point_state is None:
# We expect this and next value to be lat&lng
if not to_process:
_LOGGER.warning(
@ -395,6 +386,22 @@ class TemplateMethods:
"longitude: %s, %s", value, value_2)
return None
else:
if not loc_helper.has_location(point_state):
_LOGGER.warning(
"distance: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)
if latitude is None or longitude is None:
_LOGGER.warning(
"Distance:State does not contains a location: %s",
value)
return None
locations.append((latitude, longitude))
if len(locations) == 1:

View File

@ -682,6 +682,32 @@ class TestHelpersTemplate(unittest.TestCase):
'None',
tpl.render())
def test_distance_function_with_2_entity_ids(self):
"""Test distance function with 2 entity ids."""
self.hass.states.set('test.object', 'happy', {
'latitude': 32.87336,
'longitude': -117.22943,
})
self.hass.states.set('test.object_2', 'happy', {
'latitude': self.hass.config.latitude,
'longitude': self.hass.config.longitude,
})
tpl = template.Template(
'{{ distance("test.object", "test.object_2") | round }}',
self.hass)
self.assertEqual('187', tpl.render())
def test_distance_function_with_1_entity_1_coord(self):
"""Test distance function with 1 entity_id and 1 coord."""
self.hass.states.set('test.object', 'happy', {
'latitude': self.hass.config.latitude,
'longitude': self.hass.config.longitude,
})
tpl = template.Template(
'{{ distance("test.object", "32.87336", "-117.22943") | round }}',
self.hass)
self.assertEqual('187', tpl.render())
def test_closest_function_home_vs_domain(self):
"""Test closest function home vs domain."""
self.hass.states.set('test_domain.object', 'happy', {