From 36beab5f17d2f9f81bc5ab7c71e0b779e2eafea2 Mon Sep 17 00:00:00 2001 From: Sean Breckenridge Date: Wed, 15 Feb 2023 22:28:07 -0800 Subject: [PATCH] via_home: add accuracy, cache history --- my/config.py | 1 + my/location/fallback/via_home.py | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/my/config.py b/my/config.py index 52af04d..1b20c95 100644 --- a/my/config.py +++ b/my/config.py @@ -73,6 +73,7 @@ class location: # todo ugh, need to think about it... mypy wants the type here to be general, otherwise it can't deduce # and we can't import the types from the module itself, otherwise would be circular. common module? home: Union[LatLon, Sequence[Tuple[DateIsh, LatLon]]] = (1.0, -1.0) + home_accuracy = 1000.0 class via_ip: accuracy: float diff --git a/my/location/fallback/via_home.py b/my/location/fallback/via_home.py index 6de8bea..1ce7ab1 100644 --- a/my/location/fallback/via_home.py +++ b/my/location/fallback/via_home.py @@ -5,7 +5,7 @@ Simple location provider, serving as a fallback when more detailed data isn't av from dataclasses import dataclass from datetime import datetime, time, timezone from functools import lru_cache -from typing import Sequence, Tuple, Union, cast +from typing import Sequence, Tuple, Union, cast, List from my.config import location as user_config @@ -21,6 +21,12 @@ class Config(user_config): LatLon, # the location ]] ] + + # default ~1km accuracy + # this is called 'home_accuracy' since it lives on the base location.config object, + # to differentiate it from accuracy for other providers + home_accuracy: float = 1000 + # TODO could make current Optional and somehow determine from system settings? @property def _history(self) -> Sequence[Tuple[datetime, LatLon]]: @@ -73,17 +79,22 @@ def get_location(dt: datetime) -> LatLon: return hist[-1][1] +# TODO: in python3.9, use functools.cached_property instead? +@lru_cache(maxsize=None) +def homes_cached() -> List[Tuple[datetime, LatLon]]: + return list(config._history) + + def estimate_location(dt: Union[datetime, int, float]) -> FallbackLocation: from my.location.fallback.common import _datetime_timestamp d: float = _datetime_timestamp(dt) - # TODO: cache this? - hist = list(reversed(config._history)) + hist = list(reversed(homes_cached())) for pdt, (lat, lon) in hist: if d >= pdt.timestamp(): - # TODO: add accuracy? return FallbackLocation( lat=lat, lon=lon, + accuracy=config.home_accuracy, dt=datetime.fromtimestamp(d, timezone.utc), datasource='via_home') else: @@ -92,5 +103,6 @@ def estimate_location(dt: Union[datetime, int, float]) -> FallbackLocation: return FallbackLocation( lat=lat, lon=lon, + accuracy=config.home_accuracy, dt=datetime.fromtimestamp(d, timezone.utc), datasource='via_home')