Skip to content

Commit

Permalink
Use UTC datetimes internally (#136)
Browse files Browse the repository at this point in the history
Python datetime object comparisons and math don't work as expected
when the objects are aware and have the same tzinfo attribute.
Basically, the fold attribute is ignored in this case, which can lead to
wrong results. Avoid this problem by using aware times in UTC internally.
Only use local time zone for user visible attributes.
  • Loading branch information
pnbruckner authored Nov 20, 2024
1 parent d4d62d7 commit 59550e6
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 84 deletions.
2 changes: 2 additions & 0 deletions custom_components/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"""Sun2 integration."""
# Exists to satisfy mypy.
30 changes: 18 additions & 12 deletions custom_components/sun2/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
)
from homeassistant.core import CoreState, callback
from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.util import dt as dt_util

from .const import ATTR_NEXT_CHANGE, LOGGER, MAX_ERR_BIN, ONE_DAY, ONE_SEC, SUNSET_ELEV
from .helpers import (
Expand Down Expand Up @@ -112,13 +111,17 @@ def _get_nxt_dttm(self, cur_dttm: datetime) -> datetime | None:
# since current time might be anywhere from before today's solar
# midnight (if it is this morning) to after tomorrow's solar midnight
# (if it is this evening.)
date = cur_dttm.date()
evt_dttm1 = cast(datetime, self._astral_event(date, "solar_midnight"))
evt_dttm2 = cast(datetime, self._astral_event(date, "solar_noon"))
evt_dttm3 = cast(datetime, self._astral_event(date + ONE_DAY, "solar_midnight"))
evt_dttm4 = cast(datetime, self._astral_event(date + ONE_DAY, "solar_noon"))
date = self._as_tz(cur_dttm).date()
evt_dttm1 = cast(datetime, self._astral_event(date, "solar_midnight", False))
evt_dttm2 = cast(datetime, self._astral_event(date, "solar_noon", False))
evt_dttm3 = cast(
datetime, self._astral_event(date + ONE_DAY, "solar_midnight", False)
)
evt_dttm4 = cast(
datetime, self._astral_event(date + ONE_DAY, "solar_noon", False)
)
evt_dttm5 = cast(
datetime, self._astral_event(date + 2 * ONE_DAY, "solar_midnight")
datetime, self._astral_event(date + 2 * ONE_DAY, "solar_midnight", False)
)

# See if segment we're looking for falls between any of these events.
Expand Down Expand Up @@ -176,7 +179,7 @@ def _get_nxt_dttm(self, cur_dttm: datetime) -> datetime | None:
"%s: Sun elevation will not reach %f again until %s",
self.name,
self._threshold,
nxt_dttm.date(),
self._as_tz(nxt_dttm).date(),
)
return nxt_dttm

Expand All @@ -185,9 +188,12 @@ def _get_nxt_dttm(self, cur_dttm: datetime) -> datetime | None:
evt_dttm1 = evt_dttm3
evt_dttm2 = evt_dttm4
evt_dttm3 = evt_dttm5
evt_dttm4 = cast(datetime, self._astral_event(date + ONE_DAY, "solar_noon"))
evt_dttm4 = cast(
datetime, self._astral_event(date + ONE_DAY, "solar_noon", False)
)
evt_dttm5 = cast(
datetime, self._astral_event(date + 2 * ONE_DAY, "solar_midnight")
datetime,
self._astral_event(date + 2 * ONE_DAY, "solar_midnight", False),
)

# Didn't find one.
Expand All @@ -205,7 +211,7 @@ def _update(self, cur_dttm: datetime) -> None:
nxt_dttm = self._get_nxt_dttm(cur_dttm)

@callback
def schedule_update(now: datetime) -> None:
def schedule_update(_now: datetime) -> None:
"""Schedule state update."""
self._unsub_update = None
self.async_schedule_update_ha_state(True)
Expand All @@ -214,7 +220,7 @@ def schedule_update(now: datetime) -> None:
self._unsub_update = async_track_point_in_utc_time(
self.hass, schedule_update, nxt_dttm
)
nxt_dttm = dt_util.as_local(nxt_dttm)
nxt_dttm = self._as_tz(nxt_dttm)
elif self.hass.state == CoreState.running:
LOGGER.error(
"%s: Sun elevation never reaches %f at this location",
Expand Down
10 changes: 5 additions & 5 deletions custom_components/sun2/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
_COERCE_NUM = vol.Any(vol.Coerce(int), vol.Coerce(float))

PACKAGE_MERGE_HINT = "list"
SUN_DIRECTIONS = [dir.lower() for dir in SunDirection.__members__]
SUN_DIRECTIONS = [sd.lower() for sd in SunDirection.__members__]
SUN2_LOCATION_BASE_SCHEMA = vol.Schema(
{
vol.Inclusive(CONF_LATITUDE, "location"): cv.latitude,
Expand Down Expand Up @@ -157,19 +157,19 @@ def obs_elv_from_options(
if obs_elv_option := options.get(CONF_OBS_ELV):
east_obs_elv, west_obs_elv = obs_elv_option

if isinstance(east_obs_elv, Num) and isinstance(west_obs_elv, Num): # type: ignore[misc, arg-type]
if isinstance(east_obs_elv, Num) and isinstance(west_obs_elv, Num):
assert east_obs_elv == west_obs_elv
return cast(Num, east_obs_elv)

obs_elv: ConfigType = {}
if isinstance(east_obs_elv, Num): # type: ignore[misc, arg-type]
if isinstance(east_obs_elv, Num):
obs_elv[CONF_ABOVE_GROUND] = east_obs_elv
else:
obs_elv[CONF_SUNRISE_OBSTRUCTION] = {
CONF_DISTANCE: east_obs_elv[1],
CONF_RELATIVE_HEIGHT: east_obs_elv[0],
}
if isinstance(west_obs_elv, Num): # type: ignore[misc, arg-type]
if isinstance(west_obs_elv, Num):
obs_elv[CONF_ABOVE_GROUND] = west_obs_elv
else:
obs_elv[CONF_SUNSET_OBSTRUCTION] = {
Expand Down Expand Up @@ -230,7 +230,7 @@ def options_from_obs_elv(
)
east_obs_elv = west_obs_elv = hass.config.elevation

elif isinstance(obs := loc_config[CONF_OBS_ELV], Num): # type: ignore[misc, arg-type]
elif isinstance(obs := loc_config[CONF_OBS_ELV], Num):
east_obs_elv = west_obs_elv = obs

else:
Expand Down
10 changes: 5 additions & 5 deletions custom_components/sun2/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,8 @@ async def async_step_observer_elevation(

if obs_elv := self.options.get(CONF_OBS_ELV):
suggested_values = {
CONF_SUNRISE_OBSTRUCTION: not isinstance(obs_elv[0], Num), # type: ignore[misc, arg-type]
CONF_SUNSET_OBSTRUCTION: not isinstance(obs_elv[1], Num), # type: ignore[misc, arg-type]
CONF_SUNRISE_OBSTRUCTION: not isinstance(obs_elv[0], Num),
CONF_SUNSET_OBSTRUCTION: not isinstance(obs_elv[1], Num),
}
else:
suggested_values = {
Expand Down Expand Up @@ -297,7 +297,7 @@ async def async_step_obs_elv_values(
self.options[CONF_ELEVATION] = above_ground
return await self.async_step_entities_menu()

schema: dict[str, Any] = {}
schema: dict[vol.Schemable, Any] = {}
if get_above_ground:
schema[vol.Required(CONF_ABOVE_GROUND)] = _POSITIVE_METERS_SELECTOR
if self._sunrise_obstruction:
Expand All @@ -312,11 +312,11 @@ async def async_step_obs_elv_values(
sunrise_distance = sunset_distance = 1000
sunrise_relative_height = sunset_relative_height = 1000
if obs_elv := self.options.get(CONF_OBS_ELV):
if isinstance(obs_elv[0], Num): # type: ignore[misc, arg-type]
if isinstance(obs_elv[0], Num):
above_ground = obs_elv[0]
else:
sunrise_relative_height, sunrise_distance = obs_elv[0]
if isinstance(obs_elv[1], Num): # type: ignore[misc, arg-type]
if isinstance(obs_elv[1], Num):
# If both directions use above_ground, they should be the same.
# Assume this is true and don't bother checking here.
above_ground = obs_elv[1]
Expand Down
26 changes: 18 additions & 8 deletions custom_components/sun2/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, field
from datetime import date, datetime, time, timedelta, tzinfo
from functools import cached_property, lru_cache
from functools import ( # pylint: disable=hass-deprecated-import
cached_property,
lru_cache,
)
import logging
from math import copysign, fabs
from typing import Any, Self, cast, overload
Expand All @@ -27,7 +30,7 @@
try:
from homeassistant.core_config import Config
except ImportError:
from homeassistant.core import Config
from homeassistant.core import Config # type: ignore[no-redef]

from homeassistant.helpers.device_registry import DeviceEntryType

Expand Down Expand Up @@ -194,9 +197,9 @@ def _obs_elv_2_astral(
Also, astral only accepts a tuple, not a list, which is what stored in the
config entry (since it's from a JSON file), so convert to a tuple.
"""
if isinstance(obs_elv, Num): # type: ignore[misc, arg-type]
return float(cast(Num, obs_elv))
height, distance = cast(list[Num], obs_elv)
if isinstance(obs_elv, Num):
return float(obs_elv)
height, distance = obs_elv
return -copysign(1, float(height)) * float(distance), fabs(float(height))

@classmethod
Expand Down Expand Up @@ -349,9 +352,13 @@ def __init__(self, sun2_entity_params: Sun2EntityParams) -> None:
self._astral_data = sun2_entity_params.astral_data
self.async_on_remove(self._cancel_update)

def _as_tz(self, dttm: datetime) -> datetime:
"""Return datetime in location's time zone."""
return dttm.astimezone(self._astral_data.loc_data.tzi)

async def async_update(self) -> None:
"""Update state."""
self._update(dt_util.now(self._astral_data.loc_data.tzi))
self._update(dt_util.utcnow())

async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
Expand Down Expand Up @@ -390,6 +397,7 @@ def _astral_event(
self,
date_or_dttm: date | datetime,
event: str | None = None,
local: bool = True,
/,
**kwargs: Any,
) -> Any:
Expand All @@ -402,11 +410,11 @@ def _astral_event(

try:
if event in ("solar_midnight", "solar_noon"):
return getattr(loc, event.split("_")[1])(date_or_dttm)
return getattr(loc, event.split("_")[1])(date_or_dttm, local)

if event == "time_at_elevation":
return loc.time_at_elevation(
kwargs["elevation"], date_or_dttm, kwargs["direction"]
kwargs["elevation"], date_or_dttm, kwargs["direction"], local
)

if event in ("sunrise", "dawn"):
Expand All @@ -415,6 +423,8 @@ def _astral_event(
kwargs = {"observer_elevation": self._astral_data.obs_elvs.west}
else:
kwargs = {}
if event not in ("solar_azimuth", "solar_elevation"):
kwargs["local"] = local
return getattr(loc, event)(date_or_dttm, **kwargs)

except (TypeError, ValueError):
Expand Down
4 changes: 2 additions & 2 deletions custom_components/sun2/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"codeowners": ["@pnbruckner"],
"config_flow": true,
"dependencies": [],
"documentation": "https://github.com/pnbruckner/ha-sun2/blob/3.3.4/README.md",
"documentation": "https://github.com/pnbruckner/ha-sun2/blob/3.3.5b0/README.md",
"iot_class": "calculated",
"issue_tracker": "https://github.com/pnbruckner/ha-sun2/issues",
"requirements": [],
"version": "3.3.4"
"version": "3.3.5b0"
}
Loading

0 comments on commit 59550e6

Please sign in to comment.