mirror of
https://github.com/home-assistant/core.git
synced 2025-11-10 11:29:46 +00:00
Add closest template helper
This commit is contained in:
27
homeassistant/helpers/location.py
Normal file
27
homeassistant/helpers/location.py
Normal file
@@ -0,0 +1,27 @@
|
||||
"""Location helpers for Home Assistant."""
|
||||
|
||||
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE
|
||||
from homeassistant.core import State
|
||||
from homeassistant.util import location as loc_util
|
||||
|
||||
|
||||
def has_location(state):
|
||||
"""Test if state contains a valid location."""
|
||||
return (isinstance(state, State) and
|
||||
isinstance(state.attributes.get(ATTR_LATITUDE), float) and
|
||||
isinstance(state.attributes.get(ATTR_LONGITUDE), float))
|
||||
|
||||
|
||||
def closest(latitude, longitude, states):
|
||||
"""Return closest state to point."""
|
||||
with_location = [state for state in states if has_location(state)]
|
||||
|
||||
if not with_location:
|
||||
return None
|
||||
|
||||
return min(
|
||||
with_location,
|
||||
key=lambda state: loc_util.distance(
|
||||
latitude, longitude, state.attributes.get(ATTR_LATITUDE),
|
||||
state.attributes.get(ATTR_LONGITUDE))
|
||||
)
|
||||
Reference in New Issue
Block a user