core/homeassistant/helpers/location.py

44 lines
1.1 KiB
Python
Raw Normal View History

2016-02-21 19:13:40 +00:00
"""Location helpers for Home Assistant."""
from typing import Optional, Sequence
2016-02-21 19:13:40 +00:00
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: State) -> bool:
"""Test if state contains a valid location.
Async friendly.
"""
# type ignore: https://github.com/python/mypy/issues/7207
2019-07-31 19:25:30 +00:00
return (
2019-07-31 20:08:31 +00:00
isinstance(state, State) # type: ignore
and isinstance(state.attributes.get(ATTR_LATITUDE), float)
2019-07-31 19:25:30 +00:00
and isinstance(state.attributes.get(ATTR_LONGITUDE), float)
)
2016-02-21 19:13:40 +00:00
2019-07-31 19:25:30 +00:00
def closest(
latitude: float, longitude: float, states: Sequence[State]
) -> Optional[State]:
"""Return closest state to point.
Async friendly.
"""
2016-02-21 19:13:40 +00:00
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(
state.attributes.get(ATTR_LATITUDE),
state.attributes.get(ATTR_LONGITUDE),
2019-07-31 19:25:30 +00:00
latitude,
longitude,
),
2016-02-21 19:13:40 +00:00
)