From 328182e1b4b6bd4217ae69c2ff38b23f586c43a2 Mon Sep 17 00:00:00 2001 From: Fedorov Dmitriy Date: Sun, 27 Sep 2026 21:28:31 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20v1.5.2=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D1=83=20=D0=BD?= =?UTF-8?q?=D0=B0=D0=B3=D1=80=D0=B5=D0=B2=D0=B0,=20=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D1=8C=20=D0=BD=D0=B0=D0=B3=D1=80=D0=B5=D0=B2=20?= =?UTF-8?q?=D0=B2=D0=BA=D0=BB=D1=8E=D1=87=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D0=B4=D0=B0=D1=82=D1=87=D0=B8=D0=BA=D1=83=20qin?= =?UTF-8?q?gping=20=D0=B0=20=D0=BD=D0=B5=20=D1=82=D0=B8=D0=BE=D0=BD.=20?= =?UTF-8?q?=D0=95=D1=81=D0=BB=D0=B8=20=D0=BE=D0=BD=20=D0=BD=D0=B5=D0=B4?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=B5=D0=BD=20=D1=82=D0=BE=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=82=D0=B8=D0=BE=D0=BD=D1=83.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Version.toml | 4 +- app/api.py | 161 ++++++-- app/auto/controller.py | 207 ++++++++++- tests/test_manual_heater_lifecycle.py | 248 +++++++++++++ tests/test_manual_heater_regulation.py | 366 +++++++++++++++++++ tests/test_manual_heater_regulation_model.py | 279 ++++++++++++++ tests/test_manual_heater_state.py | 107 ++++++ tests/test_manual_status_api.py | 128 +++++++ 8 files changed, 1469 insertions(+), 31 deletions(-) create mode 100644 tests/test_manual_heater_lifecycle.py create mode 100644 tests/test_manual_heater_regulation.py create mode 100644 tests/test_manual_heater_regulation_model.py create mode 100644 tests/test_manual_heater_state.py create mode 100644 tests/test_manual_status_api.py diff --git a/Version.toml b/Version.toml index 94f0dee..0b19839 100644 --- a/Version.toml +++ b/Version.toml @@ -1,8 +1,8 @@ [version] major = 1 minor = 5 -patch = 1 +patch = 2 [build] date = "2026-09-27" -time = "20:06:04" +time = "21:27:10" diff --git a/app/api.py b/app/api.py index 4bc4051..b965af7 100644 --- a/app/api.py +++ b/app/api.py @@ -327,6 +327,42 @@ def get_status() -> dict: state = service.state + tion_status = ( + state.to_dict() + if state is not None + else None + ) + + # -------------------------------------------------- + # В ручном режиме UI должен видеть желание + # пользователя, а не техническое состояние + # внешнего регулятора. + # -------------------------------------------------- + + if ( + tion_status is not None + and schedule_service is not None + and schedule_service.paused + and auto_controller is not None + ): + if ( + auto_controller.manual_heater_enabled + is not None + ): + tion_status["heater"] = ( + auto_controller + .manual_heater_enabled + ) + + if ( + auto_controller.manual_target_temperature + is not None + ): + tion_status["target_temp"] = ( + auto_controller + .manual_target_temperature + ) + return { "online": service.online, "running": service.running, @@ -339,11 +375,8 @@ def get_status() -> dict: "last_error": service.last_error, - "tion": ( - state.to_dict() - if state is not None - else None - ), + "tion": tion_status, + "auto": get_auto_status(), "qingping": qingping_service.status(), @@ -396,6 +429,17 @@ def get_effective_speed() -> int: def get_effective_temperature() -> int: + if ( + schedule_service is not None + and schedule_service.paused + and auto_controller is not None + and auto_controller.manual_target_temperature is not None + ): + return ( + auto_controller + .manual_target_temperature + ) + if ( schedule_service is not None and schedule_service.override_active @@ -756,10 +800,18 @@ async def set_heater(state: Literal["on", "off"]): operation = lambda tion: tion.heater_off() - return await execute_command( - operation, - ScheduledSettings(heater=enabled), - ) + await execute_command(operation, ScheduledSettings(heater=enabled)) + + if ( + schedule_service is not None + and schedule_service.paused + and auto_controller is not None + ): + auto_controller.set_manual_heater_enabled( + enabled + ) + + return get_status() # ---------------------------------------------------------------------- # Target temperature increase / decrease @@ -775,39 +827,51 @@ async def increase_temperature(): if new_temperature == current_temperature: return get_status() - return await execute_command( + await execute_command( lambda tion: tion.set_target_temperature( new_temperature ), - ScheduledSettings( target_temp=new_temperature, ), ) + if ( + schedule_service is not None + and schedule_service.paused + and auto_controller is not None + ): + auto_controller.set_manual_target_temperature(new_temperature) -@app.post("/api/tion/temperature/decrease") -async def decrease_temperature(): + return get_status() - current_temperature = get_effective_temperature() - new_temperature = max(current_temperature - 1, MIN_TARGET_TEMP) - - if new_temperature == current_temperature: - return get_status() - - return await execute_command( +@app.post("/api/tion/temperature/{temperature}") +async def set_temperature( + temperature: int, +): + await execute_command( lambda tion: tion.set_target_temperature( - new_temperature + temperature ), - ScheduledSettings( - target_temp=new_temperature, + target_temp=temperature, ), ) + if ( + schedule_service is not None + and schedule_service.paused + and auto_controller is not None + ): + auto_controller.set_manual_target_temperature( + temperature + ) + + return get_status() + # ---------------------------------------------------------------------- # Target temperature # ---------------------------------------------------------------------- @@ -1018,8 +1082,56 @@ async def pause_schedule(): detail="Schedule service unavailable", ) + state = service.state + + manual_target = None + + if state is not None: + manual_target = state.target_temp + + resolution = schedule_service.resolve() + + # Если выходим в manual прямо из AUTO, + # физическая уставка Tion могла быть 30°C. + # Пользователю нужна настоящая AUTO-цель. + if ( + resolution.auto_active + and resolution.auto_target_temp + is not None + ): + manual_target = ( + resolution.auto_target_temp + ) + + # Temporary override имеет ещё больший + # приоритет. + if ( + schedule_service.override_active + and schedule_service + .override_settings + .target_temp is not None + ): + manual_target = ( + schedule_service + .override_settings + .target_temp + ) + await schedule_service.pause() + if ( + auto_controller is not None + and state is not None + ): + auto_controller.set_manual_heater_enabled( + state.heater + ) + + if manual_target is not None: + auto_controller.set_manual_target_temperature( + manual_target + ) + return { "ok": True, "schedule": get_schedule_status(), @@ -1039,6 +1151,9 @@ async def resume_schedule(): await schedule_service.resume() + if auto_controller is not None: + auto_controller.clear_manual_heater_control() + return { "ok": True, "schedule": get_schedule_status(), diff --git a/app/auto/controller.py b/app/auto/controller.py index 1990342..2528df9 100644 --- a/app/auto/controller.py +++ b/app/auto/controller.py @@ -46,6 +46,20 @@ class AutoController: self._temperature: float | int | None = None self._temperature_source: str | None = None + # -------------------------------------------------- + # Ручное управление обогревом. + # + # Эти значения описывают желание пользователя, + # а не текущее физическое состояние Tion. + # -------------------------------------------------- + + self._manual_heater_enabled: bool | None = None + self._manual_target_temperature: int | None = None + + # Фактическое решение нашего внешнего + # температурного регулятора. + self._manual_heating: bool | None = None + self._last_error: str | None = None @@ -118,17 +132,16 @@ class AutoController: self._target_speed = None self._auto_speed = None - self._target_heater = None self._auto_heater = None - self._target_temperature = None - self._temperature = None self._temperature_source = None + await self._process_manual_heater() + self._last_error = None - self._release_elica_assist() + await self._release_elica_assist() return @@ -156,7 +169,7 @@ class AutoController: self._last_error = None - self._release_elica_assist() + await self._release_elica_assist() return @@ -185,7 +198,7 @@ class AutoController: self._last_error = None - self._release_elica_assist() + await self._release_elica_assist() return @@ -386,6 +399,144 @@ class AutoController: self._auto_heater = heater_required + async def _process_manual_heater( + self, + ) -> None: + """ + Управление обогревом в полном ручном режиме. + + Приоритет: + 1. Qingping -> внешний регулятор. + 2. Qingping недоступен -> штатный + термостат Tion. + """ + + enabled = self._manual_heater_enabled + target_temp = ( + self._manual_target_temperature + ) + + # -------------------------------------------------- + # Пользователь явно выключил обогрев. + # -------------------------------------------------- + + if enabled is False: + await self._set_heater(False) + + self._manual_heating = False + + return + + # Состояние ручного управления ещё + # не инициализировано. + if enabled is None: + self._manual_heating = None + return + + # -------------------------------------------------- + # Heater разрешён, но нет пользовательской цели. + # + # Греть без уставки нельзя. + # -------------------------------------------------- + + if target_temp is None: + await self._set_heater(False) + + self._manual_heating = False + + return + + qingping_state = self._qingping.state + + qingping_temperature = getattr( + qingping_state, + "temperature", + None, + ) + + # -------------------------------------------------- + # Qingping недоступен. + # + # Возвращаем управление встроенному + # термостату Tion: + # + # target = пользовательская температура + # heater = ON + # + # Дальше Tion сам решает, когда реально греть. + # -------------------------------------------------- + + if ( + not self._qingping.online + or qingping_temperature is None + or self._temperature_policy is None + ): + await self._set_target_temperature( + target_temp + ) + + await self._set_heater(True) + + self._manual_heating = None + + # Это только диагностическое значение. + # Решение по нему мы НЕ принимаем. + tion_state = self._tion.state + + if ( + self._tion.online + and tion_state is not None + and tion_state.in_temp is not None + ): + self._temperature = ( + tion_state.in_temp + ) + self._temperature_source = "tion" + else: + self._temperature = None + self._temperature_source = None + + return + + # -------------------------------------------------- + # Qingping доступен. + # + # Именно его температура становится основной. + # -------------------------------------------------- + + self._temperature = qingping_temperature + self._temperature_source = "qingping" + + heater_required = ( + self._temperature_policy + .heater_required( + temperature=qingping_temperature, + target_temp=target_temp, + heater_on=( + self._manual_heating + is True + ), + ) + ) + + # -------------------------------------------------- + # Пока управляем по комнатному датчику, + # внутренний термостат Tion не должен + # выключить нагрев раньше нас. + # + # Поэтому физическая уставка всегда MAX. + # -------------------------------------------------- + + await self._set_target_temperature( + MAX_TARGET_TEMP + ) + + await self._set_heater( + heater_required + ) + + self._manual_heating = heater_required + def _get_temperature(self) -> tuple[float | int | None, str | None]: @@ -787,6 +938,44 @@ class AutoController: self._target_temperature = temperature + def set_manual_heater_enabled(self, enabled: bool) -> None: + """ + Запоминает, хочет ли пользователь использовать + обогрев в ручном режиме. + + Саму команду Tion этот метод пока не отправляет. + """ + self._manual_heater_enabled = enabled + + self._target_heater = None + + if not enabled: + self._manual_heating = False + + def set_manual_target_temperature(self, temperature: int) -> None: + """ + Запоминает желаемую температуру помещения + для ручного режима. + """ + self._manual_target_temperature = temperature + self._target_temperature = None + + def clear_manual_heater_control(self) -> None: + """ + Забываем состояние ручного температурного + регулятора при возврате к расписанию. + """ + self._manual_heater_enabled = None + self._manual_target_temperature = None + self._manual_heating = None + + @property + def manual_heater_enabled(self) -> bool | None: + return self._manual_heater_enabled + + @property + def manual_target_temperature(self) -> int | None: + return self._manual_target_temperature def status(self) -> dict: return { @@ -808,6 +997,12 @@ class AutoController: else None ), + "manual_heater": { + "enabled": self._manual_heater_enabled, + "target_temp": self._manual_target_temperature, + "heating": self._manual_heating, + }, + "last_error": self._last_error, } diff --git a/tests/test_manual_heater_lifecycle.py b/tests/test_manual_heater_lifecycle.py new file mode 100644 index 0000000..1301162 --- /dev/null +++ b/tests/test_manual_heater_lifecycle.py @@ -0,0 +1,248 @@ +from app.auto.controller import AutoController + + +def print_state( + title: str, + controller: AutoController, +) -> None: + print() + print(title) + print( + { + "enabled": ( + controller.manual_heater_enabled + ), + "target_temp": ( + controller.manual_target_temperature + ), + "heating": ( + controller._manual_heating + ), + } + ) + + +def main() -> None: + controller = object.__new__( + AutoController + ) + + controller._manual_heater_enabled = None + controller._manual_target_temperature = None + controller._manual_heating = None + + # ================================================== + # 1. Исходное состояние. + # ================================================== + + print_state( + "1. Initial:", + controller, + ) + + assert ( + controller.manual_heater_enabled + is None + ) + + assert ( + controller.manual_target_temperature + is None + ) + + assert controller._manual_heating is None + + # ================================================== + # 2. Пользователь входит в ручной режим. + # + # Представим, что на момент перехода: + # heater был выключен, + # пользовательская температура = 23. + # ================================================== + + controller.set_manual_heater_enabled( + False + ) + + controller.set_manual_target_temperature( + 23 + ) + + print_state( + "2. Enter manual mode:", + controller, + ) + + assert ( + controller.manual_heater_enabled + is False + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + # ================================================== + # 3. Пользователь включает обогрев. + # ================================================== + + controller.set_manual_heater_enabled( + True + ) + + print_state( + "3. Heater ON:", + controller, + ) + + assert ( + controller.manual_heater_enabled + is True + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + # Пока реальный регулятор Qingping ещё + # не реализован, heating остаётся None. + assert controller._manual_heating is False + + # ================================================== + # 4. Пользователь увеличивает температуру. + # + # 23 -> 24. + # ================================================== + + controller.set_manual_target_temperature( + 24 + ) + + print_state( + "4. Temperature 23 -> 24:", + controller, + ) + + assert ( + controller.manual_target_temperature + == 24 + ) + + assert ( + controller.manual_heater_enabled + is True + ) + + # ================================================== + # 5. Пользователь уменьшает температуру. + # + # 24 -> 23. + # ================================================== + + controller.set_manual_target_temperature( + 23 + ) + + print_state( + "5. Temperature 24 -> 23:", + controller, + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + assert ( + controller.manual_heater_enabled + is True + ) + + # ================================================== + # 6. Пользователь выключает обогрев. + # ================================================== + + controller.set_manual_heater_enabled( + False + ) + + print_state( + "6. Heater OFF:", + controller, + ) + + assert ( + controller.manual_heater_enabled + is False + ) + + # Уставка пользователя должна сохраниться. + assert ( + controller.manual_target_temperature + == 23 + ) + + # При явном выключении heater мы уже + # установили manual_heating=False. + assert controller._manual_heating is False + + # ================================================== + # 7. Пользователь снова включает heater. + # + # Проверяем, что сохранённая температура 23 + # не потерялась. + # ================================================== + + controller.set_manual_heater_enabled( + True + ) + + print_state( + "7. Heater ON again:", + controller, + ) + + assert ( + controller.manual_heater_enabled + is True + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + # ================================================== + # 8. Resume расписания. + # + # API при resume вызывает + # clear_manual_heater_control(). + # ================================================== + + controller.clear_manual_heater_control() + + print_state( + "8. Resume schedule:", + controller, + ) + + assert ( + controller.manual_heater_enabled + is None + ) + + assert ( + controller.manual_target_temperature + is None + ) + + assert controller._manual_heating is None + + print() + print("TEST PASSED") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests/test_manual_heater_regulation.py b/tests/test_manual_heater_regulation.py new file mode 100644 index 0000000..7764c1d --- /dev/null +++ b/tests/test_manual_heater_regulation.py @@ -0,0 +1,366 @@ +import asyncio +import inspect + +from app.auto.controller import AutoController +from app.my_dataclasses import MAX_TARGET_TEMP + + +class FakeTionController: + def __init__(self) -> None: + self.heater = False + self.target_temp = 23 + + 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.in_temp = 22 + + +class FakeTionService: + def __init__(self) -> None: + self.online = True + self.state = FakeTionState() + + self.controller = FakeTionController() + + self.commands: list[str] = [] + + async def execute(self, operation): + result = operation(self.controller) + + if inspect.isawaitable(result): + await result + + self.commands.append( + ( + f"heater={self.controller.heater}, " + f"target={self.controller.target_temp}" + ) + ) + + +class FakeQingpingState: + def __init__(self) -> None: + self.temperature = 21.0 + + +class FakeQingpingService: + def __init__(self) -> None: + self.online = True + self.state = FakeQingpingState() + + +class FakeTemperaturePolicy: + """ + Для этого теста нас интересует именно + интеграция Manual Heater с источниками + температуры и Tion. + + Поэтому policy делаем простой и + детерминированной. + """ + + def heater_required( + self, + temperature, + target_temp, + heater_on, + ) -> bool: + return temperature < target_temp + + +def print_state( + title: str, + controller: AutoController, + tion: FakeTionService, +) -> None: + print() + print(title) + + print( + { + "manual_enabled": ( + controller.manual_heater_enabled + ), + "user_target": ( + controller.manual_target_temperature + ), + "manual_heating": ( + controller._manual_heating + ), + "temperature": ( + controller._temperature + ), + "temperature_source": ( + controller._temperature_source + ), + "tion_heater": ( + tion.controller.heater + ), + "tion_target": ( + tion.controller.target_temp + ), + } + ) + + +async def main() -> None: + tion = FakeTionService() + qingping = FakeQingpingService() + + controller = AutoController( + schedule_service=object(), + qingping_service=qingping, + tion_service=tion, + temperature_policy=( + FakeTemperaturePolicy() + ), + ) + + controller.set_manual_heater_enabled( + True + ) + + controller.set_manual_target_temperature( + 23 + ) + + # ================================================== + # 1. Qingping доступен. + # Комната холоднее цели. + # + # 21 < 23 + # + # Ожидаем: + # - управление по Qingping; + # - heater ON; + # - физическая уставка Tion = MAX; + # - manual_heating=True. + # ================================================== + + qingping.online = True + qingping.state.temperature = 21.0 + + await controller._process_manual_heater() + + print_state( + "1. Qingping OK, room 21°C:", + controller, + tion, + ) + + assert ( + controller._temperature_source + == "qingping" + ) + + assert controller._temperature == 21.0 + + assert controller._manual_heating is True + + assert tion.controller.heater is True + + assert ( + tion.controller.target_temp + == MAX_TARGET_TEMP + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + # ================================================== + # 2. Температура достигла цели. + # + # 23 >= 23 + # + # Ожидаем: + # - heater OFF; + # - внешний регулятор остаётся активным; + # - физическая уставка Tion остаётся MAX. + # ================================================== + + qingping.state.temperature = 23.0 + + await controller._process_manual_heater() + + print_state( + "2. Room reached 23°C:", + controller, + tion, + ) + + assert ( + controller._temperature_source + == "qingping" + ) + + assert controller._temperature == 23.0 + + assert controller._manual_heating is False + + assert tion.controller.heater is False + + assert ( + tion.controller.target_temp + == MAX_TARGET_TEMP + ) + + # ================================================== + # 3. Qingping пропал. + # + # Ожидаем: + # - внешний регулятор отключается; + # - manual_heating=None; + # - Tion получает пользовательские 23°C; + # - heater разрешается; + # - дальше решение принимает встроенный + # термостат Tion. + # ================================================== + + qingping.online = False + + tion.state.in_temp = 22 + + await controller._process_manual_heater() + + print_state( + "3. Qingping OFFLINE:", + controller, + tion, + ) + + assert controller._manual_heating is None + + assert tion.controller.heater is True + + assert tion.controller.target_temp == 23 + + assert controller._temperature == 22 + + assert ( + controller._temperature_source + == "tion" + ) + + # ================================================== + # 4. Qingping снова появился. + # + # Комната 22°C при цели 23°C. + # + # Ожидаем автоматический возврат + # внешнего регулирования. + # ================================================== + + qingping.online = True + qingping.state.temperature = 22.0 + + await controller._process_manual_heater() + + print_state( + "4. Qingping recovered, room 22°C:", + controller, + tion, + ) + + 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 + ) + + # ================================================== + # 5. После восстановления снова достигаем цели. + # ================================================== + + qingping.state.temperature = 23.0 + + await controller._process_manual_heater() + + print_state( + "5. Target reached after recovery:", + controller, + tion, + ) + + assert controller._manual_heating is False + + assert tion.controller.heater is False + + assert ( + tion.controller.target_temp + == MAX_TARGET_TEMP + ) + + # ================================================== + # 6. Пользователь выключает heater. + # + # Даже при холодной комнате нагрев должен + # остаться выключенным. + # ================================================== + + qingping.state.temperature = 18.0 + + controller.set_manual_heater_enabled( + False + ) + + await controller._process_manual_heater() + + print_state( + "6. User heater OFF:", + controller, + tion, + ) + + assert ( + controller.manual_heater_enabled + is False + ) + + assert controller._manual_heating is False + + assert tion.controller.heater is False + + # Пользовательская температура при этом + # должна сохраниться. + assert ( + controller.manual_target_temperature + == 23 + ) + + print() + print("Commands sent to fake Tion:") + + for command in tion.commands: + print(" ", command) + + print() + print("TEST PASSED") + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/tests/test_manual_heater_regulation_model.py b/tests/test_manual_heater_regulation_model.py new file mode 100644 index 0000000..2a5b299 --- /dev/null +++ b/tests/test_manual_heater_regulation_model.py @@ -0,0 +1,279 @@ +class FakeTion: + """ + Модель Tion. + + target_temp: + реальная температура, отправленная в Tion. + + heater: + разрешён ли нагреватель физически. + """ + + def __init__(self) -> None: + self.heater = False + self.target_temp = 23 + + def set_heater( + self, + enabled: bool, + ) -> None: + self.heater = enabled + + def set_target_temperature( + self, + temperature: int, + ) -> None: + self.target_temp = temperature + + +class ManualHeaterModel: + """ + Эталонная модель будущего ручного + температурного регулятора. + + user_target: + температура, которую задал пользователь. + + heating: + решение внешнего регулятора: + True -> сейчас хотим греть; + False -> сейчас не хотим греть; + None -> внешний регулятор не работает, + управление отдано Tion. + """ + + def __init__( + self, + tion: FakeTion, + user_target: int, + ) -> None: + self.tion = tion + self.user_target = user_target + self.heating: bool | None = None + + def update( + self, + qingping_available: bool, + room_temperature: float | None, + ) -> None: + # ---------------------------------------------- + # Qingping недоступен. + # + # Возвращаем штатное управление Tion: + # + # heater = ON + # target = пользовательская температура. + # + # Дальше встроенный термостат Tion сам + # решает, когда реально нагревать. + # ---------------------------------------------- + + if ( + not qingping_available + or room_temperature is None + ): + self.heating = None + + self.tion.set_target_temperature( + self.user_target + ) + + self.tion.set_heater( + True + ) + + return + + # ---------------------------------------------- + # Qingping доступен. + # + # Чтобы внутренний термостат Tion + # не выключил нагрев раньше комнатного + # датчика, ставим техническую уставку 30°C. + # ---------------------------------------------- + + self.tion.set_target_temperature( + 30 + ) + + # Комната холоднее цели. + if room_temperature < self.user_target: + self.heating = True + + self.tion.set_heater( + True + ) + + return + + # Температура достигнута. + self.heating = False + + self.tion.set_heater( + False + ) + + +def print_state( + title: str, + model: ManualHeaterModel, +) -> None: + print() + print(title) + + print( + { + "user_target": model.user_target, + "manual_heating": model.heating, + "tion_heater": model.tion.heater, + "tion_target": model.tion.target_temp, + } + ) + + +def main() -> None: + tion = FakeTion() + + model = ManualHeaterModel( + tion=tion, + user_target=23, + ) + + # ================================================== + # 1. Qingping доступен. + # В комнате холодно: 21°C при цели 23°C. + # + # Ожидаем: + # - внешний регулятор активен; + # - heater ON; + # - техническая уставка Tion = 30°C. + # ================================================== + + model.update( + qingping_available=True, + room_temperature=21.0, + ) + + print_state( + "1. Qingping available, room 21°C:", + model, + ) + + assert model.heating is True + assert tion.heater is True + assert tion.target_temp == 30 + + # Пользовательская цель не должна + # измениться. + assert model.user_target == 23 + + # ================================================== + # 2. Температура комнаты достигла цели. + # + # 23°C при цели 23°C. + # + # Ожидаем: + # - нагрев выключается; + # - Tion остаётся с технической уставкой 30, + # потому что управление всё ещё внешнее. + # ================================================== + + model.update( + qingping_available=True, + room_temperature=23.0, + ) + + print_state( + "2. Room reached target 23°C:", + model, + ) + + assert model.heating is False + assert tion.heater is False + assert tion.target_temp == 30 + assert model.user_target == 23 + + # ================================================== + # 3. Qingping пропал. + # + # Ожидаем немедленный fallback: + # + # - внешний регулятор прекращает принимать + # решения; + # - heater разрешаем; + # - возвращаем физическую уставку Tion = 23; + # - дальше работает встроенный термостат Tion. + # ================================================== + + model.update( + qingping_available=False, + room_temperature=None, + ) + + print_state( + "3. Qingping unavailable:", + model, + ) + + assert model.heating is None + + assert tion.heater is True + + assert ( + tion.target_temp + == model.user_target + == 23 + ) + + # ================================================== + # 4. Qingping снова появился. + # + # В комнате снова холоднее цели. + # + # Ожидаем возврат внешнего управления: + # + # target Tion 23 -> 30 + # heater ON + # heating True + # ================================================== + + model.update( + qingping_available=True, + room_temperature=22.0, + ) + + print_state( + "4. Qingping recovered, room 22°C:", + model, + ) + + assert model.heating is True + assert tion.heater is True + assert tion.target_temp == 30 + assert model.user_target == 23 + + # ================================================== + # 5. После восстановления снова достигаем цели. + # ================================================== + + model.update( + qingping_available=True, + room_temperature=23.0, + ) + + print_state( + "5. Target reached after recovery:", + model, + ) + + assert model.heating is False + assert tion.heater is False + assert tion.target_temp == 30 + assert model.user_target == 23 + + print() + print("TEST PASSED") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests/test_manual_heater_state.py b/tests/test_manual_heater_state.py new file mode 100644 index 0000000..e49b5d6 --- /dev/null +++ b/tests/test_manual_heater_state.py @@ -0,0 +1,107 @@ +from app.auto.controller import AutoController + + +def main() -> None: + controller = object.__new__( + AutoController + ) + + controller._manual_heater_enabled = None + controller._manual_target_temperature = None + controller._manual_heating = None + + print("Initial:") + print( + { + "enabled": controller._manual_heater_enabled, + "target_temp": controller._manual_target_temperature, + "heating": controller._manual_heating, + } + ) + + controller.set_manual_heater_enabled( + True + ) + + controller.set_manual_target_temperature( + 23 + ) + + print("After enable + target 23:") + print( + { + "enabled": controller.manual_heater_enabled, + "target_temp": controller.manual_target_temperature, + "heating": controller._manual_heating, + } + ) + + assert ( + controller.manual_heater_enabled + is True + ) + + assert ( + controller.manual_target_temperature + == 23 + ) + + assert ( + controller._manual_heating + is None + ) + + controller.set_manual_heater_enabled( + False + ) + + print("After heater OFF:") + print( + { + "enabled": controller.manual_heater_enabled, + "target_temp": controller.manual_target_temperature, + "heating": controller._manual_heating, + } + ) + + assert ( + controller.manual_heater_enabled + is False + ) + + assert ( + controller._manual_heating + is False + ) + + controller.clear_manual_heater_control() + + print("After clear:") + print( + { + "enabled": controller.manual_heater_enabled, + "target_temp": controller.manual_target_temperature, + "heating": controller._manual_heating, + } + ) + + assert ( + controller.manual_heater_enabled + is None + ) + + assert ( + controller.manual_target_temperature + is None + ) + + assert ( + controller._manual_heating + is None + ) + + print("TEST PASSED") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests/test_manual_status_api.py b/tests/test_manual_status_api.py new file mode 100644 index 0000000..2a89132 --- /dev/null +++ b/tests/test_manual_status_api.py @@ -0,0 +1,128 @@ +from unittest.mock import MagicMock, patch + +import app.api as api + + +class FakeTionState: + def __init__( + self, + heater: bool, + target_temp: int, + ): + self.heater = heater + self.target_temp = target_temp + + def to_dict(self) -> dict: + return { + "power": True, + "heater": self.heater, + "heating": True, + "mode": "outside", + "out_temp": 10, + "in_temp": 21, + "target_temp": self.target_temp, + "fan_speed": 3, + } + + +def main() -> None: + # -------------------------------------------------- + # Физическое состояние Tion: + # heater ON + # target = 30°C + # + # Но пользователь в ручном режиме хочет 23°C. + # -------------------------------------------------- + + tion_state = FakeTionState( + heater=True, + target_temp=30, + ) + + fake_service = MagicMock() + fake_service.state = tion_state + fake_service.online = True + fake_service.running = True + fake_service.last_seen = None + fake_service.last_error = None + + fake_schedule = MagicMock() + fake_schedule.paused = True + fake_schedule.override_active = False + + fake_auto = MagicMock() + + fake_auto.manual_heater_enabled = True + fake_auto.manual_target_temperature = 23 + + fake_auto.status.return_value = { + "manual_heater": { + "enabled": True, + "target_temp": 23, + "heating": None, + } + } + + print("Physical Tion:") + print(tion_state.to_dict()) + + with ( + patch.object( + api, + "service", + fake_service, + ), + patch.object( + api, + "schedule_service", + fake_schedule, + ), + patch.object( + api, + "auto_controller", + fake_auto, + ), + ): + status = api.get_status() + + print() + print("Public API Tion:") + print(status["tion"]) + + print() + print("Auto:") + print(status["auto"]) + + # -------------------------------------------------- + # Главная проверка. + # -------------------------------------------------- + + assert tion_state.target_temp == 30 + + assert ( + status["tion"]["target_temp"] + == 23 + ) + + assert ( + status["tion"]["heater"] + is True + ) + + print() + print( + "Physical target:", + tion_state.target_temp, + ) + + print( + "Public target:", + status["tion"]["target_temp"], + ) + + print() + print("TEST PASSED") + + +if __name__ == "__main__": + main() \ No newline at end of file