Fix TOD incorrectly determining the state between sunrise and sunset (#65884)

* Fix TOD component incorrectly determining the state between sunrise and sunset (#30199)

* TOD fix

* Comment added

* Review

* Review

* Review

* Update time after day fix workaround for compatibility with
current version.
Only apply fix when using times and not when using sun events.
Add unit test for behaviour.

Co-authored-by: Nikolay Vasilchuk <Anonym.tsk@gmail.com>
pull/66081/head
Tiernan 2022-02-08 23:26:36 +10:00 committed by GitHub
parent dcab9a19d6
commit 2df5060d80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 0 deletions

View File

@ -161,6 +161,21 @@ class TodSensor(BinarySensorEntity):
self._time_before = before_event_date
# We are calculating the _time_after value assuming that it will happen today
# But that is not always true, e.g. after 23:00, before 12:00 and now is 10:00
# If _time_before and _time_after are ahead of nowutc:
# _time_before is set to 12:00 next day
# _time_after is set to 23:00 today
# nowutc is set to 10:00 today
if (
not is_sun_event(self._after)
and self._time_after > nowutc
and self._time_before > nowutc + timedelta(days=1)
):
# remove one day from _time_before and _time_after
self._time_after -= timedelta(days=1)
self._time_before -= timedelta(days=1)
# Add offset to utc boundaries according to the configuration
self._time_after += self._after_offset
self._time_before += self._before_offset

View File

@ -163,6 +163,25 @@ async def test_midnight_turnover_before_midnight_outside_period(hass):
assert state.state == STATE_OFF
async def test_after_happens_tomorrow(hass):
"""Test when both before and after are in the future, and after is later than before."""
test_time = datetime(2019, 1, 10, 10, 00, 0, tzinfo=dt_util.UTC)
config = {
"binary_sensor": [
{"platform": "tod", "name": "Night", "after": "23:00", "before": "12:00"}
]
}
with patch(
"homeassistant.components.tod.binary_sensor.dt_util.utcnow",
return_value=test_time,
):
await async_setup_component(hass, "binary_sensor", config)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.night")
assert state.state == STATE_ON
async def test_midnight_turnover_after_midnight_outside_period(hass):
"""Test midnight turnover setting before midnight inside period ."""
test_time = datetime(2019, 1, 10, 20, 0, 0, tzinfo=dt_util.UTC)