diff --git a/Version.toml b/Version.toml index f398acf..a01d904 100644 --- a/Version.toml +++ b/Version.toml @@ -1,8 +1,8 @@ [version] major = 1 minor = 5 -patch = 4 +patch = 5 [build] date = "2026-09-27" -time = "21:55:47" +time = "22:09:12" diff --git a/app/auto/controller.py b/app/auto/controller.py index 2528df9..b829ff3 100644 --- a/app/auto/controller.py +++ b/app/auto/controller.py @@ -154,18 +154,59 @@ class AutoController: if self._schedule.override_active: self._state = "suspended" self._reason = "manual_override" - # AUTO больше не может считать, - # что знает реальное состояние speed/heater: - # пользователь мог изменить их вручную. + + # AUTO скоростью больше не управляет. self._target_speed = None self._auto_speed = None - self._target_heater = None + # AUTO-регулятор температуры также + # больше не используется. self._auto_heater = None - self._target_temperature = None - self._temperature = None - self._temperature_source = None + override = self._schedule.override_settings + + # -------------------------------------------------- + # Температура, установленная пользователем, + # становится целью ручного регулятора. + # -------------------------------------------------- + + if override.target_temp is not None: + self.set_manual_target_temperature( + override.target_temp + ) + + # Если пользователь меняет температуру, + # считаем, что термостат ему нужен. + # + # Явный heater=off ниже имеет приоритет. + if override.heater is None: + self.set_manual_heater_enabled( + True + ) + + # -------------------------------------------------- + # Явная команда heater ON/OFF имеет + # максимальный приоритет. + # -------------------------------------------------- + + if override.heater is not None: + self.set_manual_heater_enabled( + override.heater + ) + + # -------------------------------------------------- + # Если override касается температуры/heater, + # применяем тот же регулятор, что и в PAUSE: + # + # Qingping -> основной + # Tion thermostat -> fallback + # -------------------------------------------------- + + if ( + self._manual_heater_enabled is not None + or self._manual_target_temperature is not None + ): + await self._process_manual_heater() self._last_error = None @@ -173,10 +214,20 @@ class AutoController: return + # -------------------------------------------------- + # Override закончился. + # Его ручную температурную сессию забываем. + # -------------------------------------------------- + + if ( + self._manual_heater_enabled is not None + or self._manual_target_temperature is not None + ): + self.clear_manual_heater_control() + # ---------------------------------------------- # AUTO сейчас не активен # ---------------------------------------------- - if ( not resolution.enabled or not resolution.auto_active diff --git a/tests/test_manual_override_heater.py b/tests/test_manual_override_heater.py new file mode 100644 index 0000000..afe0cba --- /dev/null +++ b/tests/test_manual_override_heater.py @@ -0,0 +1,326 @@ +import asyncio +import inspect +from types import SimpleNamespace + +from app.auto.controller import AutoController +from app.my_dataclasses import MAX_TARGET_TEMP + + +class FakeTionController: + def __init__(self) -> None: + # Имитируем состояние до ручного изменения: + # AUTO ранее разрешил нагрев. + self.heater = True + self.target_temp = MAX_TARGET_TEMP + + def heater_on(self) -> None: + self.heater = True + + def heater_off(self) -> None: + self.heater = False + + def set_target_temperature( + self, + temperature: int, + ) -> None: + self.target_temp = temperature + + +class FakeTionState: + def __init__(self) -> None: + self.heater = True + self.in_temp = 18 + + +class FakeTionService: + def __init__(self) -> None: + self.online = True + self.state = FakeTionState() + + self.controller = FakeTionController() + + async def execute(self, operation): + result = operation(self.controller) + + if inspect.isawaitable(result): + await result + + +class FakeQingpingState: + def __init__(self) -> None: + self.temperature = 25.8 + self.co2 = 900 + + +class FakeQingpingService: + def __init__(self) -> None: + self.online = True + self.state = FakeQingpingState() + + +class FakeTemperaturePolicy: + def heater_required( + self, + temperature, + target_temp, + heater_on, + ) -> bool: + return temperature < target_temp + + +class FakeSchedule: + def __init__(self) -> None: + self.paused = False + self.override_active = True + + # Пользователь во время AUTO + # изменил только температуру: + # + # AUTO target = 25 + # manual override target = 23 + self.override_settings = SimpleNamespace( + target_temp=23, + heater=None, + ) + + def resolve(self, now=None): + # _process() вызывает resolve() ещё до + # проверки override_active. + # + # Для самого override содержимое resolution + # использоваться не должно. + return SimpleNamespace( + enabled=True, + auto_active=True, + auto_fallback_speed=2, + auto_target_temp=25, + ) + + +def print_state( + title: str, + controller: AutoController, + tion: FakeTionService, + qingping: FakeQingpingService, +) -> None: + print() + print(title) + + print( + { + "controller_state": controller._state, + "reason": controller._reason, + + "qingping_online": qingping.online, + "qingping_temp": ( + qingping.state.temperature + ), + + "manual_enabled": ( + controller.manual_heater_enabled + ), + "manual_target": ( + controller.manual_target_temperature + ), + "manual_heating": ( + controller._manual_heating + ), + + "temperature": controller._temperature, + "temperature_source": ( + controller._temperature_source + ), + + "tion_in_temp": tion.state.in_temp, + "tion_heater": tion.controller.heater, + "tion_target": ( + tion.controller.target_temp + ), + } + ) + + +async def main() -> None: + schedule = FakeSchedule() + tion = FakeTionService() + qingping = FakeQingpingService() + + controller = AutoController( + schedule_service=schedule, + qingping_service=qingping, + tion_service=tion, + temperature_policy=FakeTemperaturePolicy(), + ) + + # ================================================== + # 1. Регрессионный тест найденного бага. + # + # Было: + # + # AUTO target = 25 + # Qingping = 25.8 + # Tion heater = ON + # + # Пользователь вручную ставит 23. + # + # Несмотря на то, что встроенный датчик Tion + # показывает только 18°C, главным должен остаться + # Qingping: + # + # 25.8 > 23 + # -> heater OFF. + # ================================================== + + await controller._process() + + print_state( + "1. Override target 23, Qingping 25.8:", + controller, + tion, + qingping, + ) + + assert controller._state == "suspended" + assert controller._reason == "manual_override" + + assert ( + controller.manual_target_temperature + == 23 + ) + + assert ( + controller.manual_heater_enabled + is True + ) + + assert ( + controller._temperature_source + == "qingping" + ) + + assert controller._temperature == 25.8 + + assert controller._manual_heating is False + + # КЛЮЧЕВАЯ ПРОВЕРКА БАГА: + assert tion.controller.heater is False + + # Внешний регулятор активен, + # поэтому физическая уставка Tion остаётся MAX. + assert ( + tion.controller.target_temp + == MAX_TARGET_TEMP + ) + + # ================================================== + # 2. Qingping пропадает во время того же override. + # + # Должны: + # + # target Tion -> 23 + # heater -> ON + # + # И дальше встроенный термостат Tion решает, + # нужен ли фактический нагрев. + # ================================================== + + qingping.online = False + qingping.state.temperature = None + + await controller._process() + + print_state( + "2. Same override, Qingping OFFLINE:", + controller, + tion, + qingping, + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + assert controller._manual_heating is None + + assert tion.controller.target_temp == 23 + assert tion.controller.heater is True + + assert ( + controller._temperature_source + == "tion" + ) + + assert controller._temperature == 18 + + # ================================================== + # 3. Qingping восстанавливается. + # + # Комната = 22°C, цель override = 23°C. + # + # Внешний регулятор автоматически должен + # снова забрать управление: + # + # target Tion -> MAX + # heater -> ON + # source -> Qingping + # ================================================== + + qingping.online = True + qingping.state.temperature = 22.0 + + await controller._process() + + print_state( + "3. Qingping recovered, room 22:", + controller, + tion, + qingping, + ) + + assert ( + controller._temperature_source + == "qingping" + ) + + assert controller._temperature == 22.0 + assert controller._manual_heating is True + + assert tion.controller.heater is True + + assert ( + tion.controller.target_temp + == MAX_TARGET_TEMP + ) + + # ================================================== + # 4. Температура снова выше ручной цели. + # + # Проверяем, что heater снова отключается. + # ================================================== + + qingping.state.temperature = 24.0 + + await controller._process() + + print_state( + "4. Qingping 24, override target 23:", + controller, + tion, + qingping, + ) + + assert controller._manual_heating is False + assert tion.controller.heater is False + + assert ( + tion.controller.target_temp + == MAX_TARGET_TEMP + ) + + print() + print("TEST PASSED") + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file