Cache zoneinfo for smart devices (#1156)

This commit is contained in:
Steven B.
2024-10-08 12:21:01 +01:00
committed by GitHub
parent 9641edcbc0
commit 7c1686d3ae
3 changed files with 45 additions and 32 deletions

View File

@@ -2,11 +2,10 @@
from __future__ import annotations
import asyncio
import logging
from datetime import datetime, tzinfo
from zoneinfo import ZoneInfo
from ..cachedzoneinfo import CachedZoneInfo
_LOGGER = logging.getLogger(__name__)
@@ -17,10 +16,10 @@ async def get_timezone(index: int) -> tzinfo:
_LOGGER.error(
"Unexpected index %s not configured as a timezone, defaulting to UTC", index
)
return await _CachedZoneInfo.get_cached_zone_info("Etc/UTC")
return await CachedZoneInfo.get_cached_zone_info("Etc/UTC")
name = TIMEZONE_INDEX[index]
return await _CachedZoneInfo.get_cached_zone_info(name)
return await CachedZoneInfo.get_cached_zone_info(name)
async def get_timezone_index(name: str) -> int:
@@ -30,7 +29,7 @@ async def get_timezone_index(name: str) -> int:
return rev[name]
# Try to find a supported timezone matching dst true/false
zone = await _CachedZoneInfo.get_cached_zone_info(name)
zone = await CachedZoneInfo.get_cached_zone_info(name)
now = datetime.now()
winter = datetime(now.year, 1, 1, 12)
summer = datetime(now.year, 7, 1, 12)
@@ -43,27 +42,6 @@ async def get_timezone_index(name: str) -> int:
raise ValueError("Device does not support timezone %s", name)
class _CachedZoneInfo(ZoneInfo):
"""Cache zone info objects."""
_cache: dict[str, ZoneInfo] = {}
@classmethod
async def get_cached_zone_info(cls, time_zone_str: str) -> ZoneInfo:
"""Get a cached zone info object."""
if cached := cls._cache.get(time_zone_str):
return cached
loop = asyncio.get_running_loop()
zinfo = await loop.run_in_executor(None, _get_zone_info, time_zone_str)
cls._cache[time_zone_str] = zinfo
return zinfo
def _get_zone_info(time_zone_str: str) -> ZoneInfo:
"""Get a time zone object for the given time zone string."""
return ZoneInfo(time_zone_str)
TIMEZONE_INDEX = {
0: "Etc/GMT+12",
1: "Pacific/Samoa",