fix: v1.5.2 изменил логику нагрева, теперь нагрев включается по датчику qingping а не тион. Если он недоступен то по тиону.

This commit is contained in:
2026-09-27 21:28:31 +03:00
parent cea2637ec8
commit 328182e1b4
8 changed files with 1469 additions and 31 deletions
+248
View File
@@ -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()
+366
View File
@@ -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())
@@ -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()
+107
View File
@@ -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()
+128
View File
@@ -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()