14 Commits
Author SHA1 Message Date
Dmitriy 4bd656753f Merge branch 'release' into dev_fedorov 2026-09-29 23:40:13 +03:00
Dmitriy 4786f4e749 fix : v1.5.9 еще внес правки по отображению температуры. 2026-09-29 23:40:00 +03:00
Dmitriy 0cdfe9e98c work : исправил время сборки 2026-09-29 23:39:15 +03:00
Dmitriy 4c1f80ee3c work : еще вес правки по отображению температуры. 2026-09-29 23:18:15 +03:00
Dmitriy 982790d043 Merge branch 'release' into dev_fedorov 2026-09-29 23:04:18 +03:00
Dmitriy 8e0ee11095 fix : v1.5.8 исправил отображение температуры на странице. Отображалась температура на выходе из бризера, т.е. в комнате. 2026-09-29 23:04:06 +03:00
Dmitriy 74813879cf work : исправил отображение температуры на странице. Отображалась температура на выходе из бризера, т.е. в комнате. 2026-09-29 23:03:22 +03:00
Dmitriy 3341583dc6 Merge branch 'release' into dev_fedorov 2026-09-29 22:55:52 +03:00
Dmitriy 5fc2149755 fix: v1.5.7 исправил архитектуру управления температурой. Теперь отдельный контроллер отвечает за нагрев для всех режимов авто ручной или временный ручной. Раньше в каждом режиме была своя логика. 2026-09-29 22:55:36 +03:00
Dmitriy 5318d3e79a work: изменил версию 2026-09-29 22:49:58 +03:00
Dmitriy 2a7d2a0b8b work: исправил архитектуру управления температурой. Теперь отдельный контроллер отвечает за нагрев для всех режимов авто ручной или временный ручной. Раньше в каждом режиме была своя логика. 2026-09-29 22:49:31 +03:00
Dmitriy ba8151305a Merge branch 'release' into dev_fedorov 2026-09-27 22:17:09 +03:00
Dmitriy 075690a98b fix: v1.5.6 поправил баг отображения температуры 30 град при переходе между режимами. в api.py были не верные отступы. 2026-09-27 22:16:58 +03:00
Dmitriy 6cb14e42f1 work: поправил баг отображения температуры 30 град при переходе между режимами. в api.py были не верные отступы. 2026-09-27 22:16:22 +03:00
45 changed files with 1639 additions and 2775 deletions
+3 -3
View File
@@ -1,8 +1,8 @@
[version] [version]
major = 1 major = 1
minor = 5 minor = 5
patch = 5 patch = 9
[build] [build]
date = "2026-09-27" date = "2026-09-29"
time = "22:09:12" time = "23:38:58"
+201 -186
View File
@@ -33,7 +33,7 @@ from app.my_dataclasses import (
from app.auto import ( from app.auto import (
AutoController, AutoController,
Co2SpeedPolicy, Co2SpeedPolicy,
load_auto_config, load_auto_config_components,
) )
from app.auto.temperature_policy import TemperaturePolicy from app.auto.temperature_policy import TemperaturePolicy
@@ -138,10 +138,19 @@ async def lifespan(app: FastAPI):
schedule_load_error = None schedule_load_error = None
try: try:
auto_config = load_auto_config(AUTO_CONFIG_FILE) auto_config = load_auto_config_components(AUTO_CONFIG_FILE)
elica_assist = ElicaAutoAssistState(auto_config.elica_assist) auto_interval = auto_config.check_interval
auto_errors = dict(auto_config.errors)
# --------------------------------------------------
# CO2 policy
# --------------------------------------------------
auto_policy = None
if auto_config.co2 is not None:
try:
auto_policy = Co2SpeedPolicy( auto_policy = Co2SpeedPolicy(
base_speed=( base_speed=(
auto_config.co2.base_speed auto_config.co2.base_speed
@@ -154,26 +163,93 @@ async def lifespan(app: FastAPI):
), ),
) )
except Exception as exc:
auto_errors["co2_policy"] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Temperature policy
# --------------------------------------------------
temperature_policy = None
if (
auto_config.temperature
is not None
):
try:
temperature_policy = TemperaturePolicy(auto_config.temperature) temperature_policy = TemperaturePolicy(auto_config.temperature)
auto_interval = (auto_config.check_interval)
auto_load_error = None
except Exception as exc: except Exception as exc:
auto_policy = None auto_errors[
temperature_policy = None "temperature_policy"
] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Elica Assist
# --------------------------------------------------
elica_assist = None elica_assist = None
# Безопасный встроенный интервал нужен, if (
# потому что auto.yaml сейчас недоступен. auto_config.elica_assist
is not None
):
try:
elica_assist = ElicaAutoAssistState(auto_config.elica_assist)
except Exception as exc:
auto_errors[
"elica_assist"
] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Общая диагностика
# --------------------------------------------------
if auto_errors:
auto_load_error = "; ".join(
(
f"{name}: {error}"
)
for name, error
in auto_errors.items()
)
else:
auto_load_error = None
except Exception as exc:
# Здесь остаются только ошибки,
# из-за которых невозможно разобрать
# auto.yaml вообще.
auto_policy = None
temperature_policy = None
elica_assist = None
auto_interval = 5.0 auto_interval = 5.0
auto_load_error = ( auto_load_error = (
f"{type(exc).__name__}: {exc}" f"{type(exc).__name__}: {exc}"
) )
# --------------------------------------------------
# AutoController создаётся даже если, например,
# CO2 policy не загрузилась.
#
# policy=None даст fallback скорости,
# но TemperaturePolicy при этом может работать.
# --------------------------------------------------
auto_controller = AutoController( auto_controller = AutoController(
schedule_service=schedule_service, schedule_service=schedule_service,
qingping_service=qingping_service, qingping_service=qingping_service,
@@ -341,52 +417,24 @@ def get_status() -> dict:
if ( if (
tion_status is not None tion_status is not None
and schedule_service is not None
and schedule_service.paused
and auto_controller is not None and auto_controller is not None
): ):
temperature_config = (auto_controller.effective_temperature_config())
if ( if (
auto_controller.manual_heater_enabled temperature_config.heater_enabled
is not None is not None
): ):
tion_status["heater"] = ( tion_status["heater"] = (
auto_controller temperature_config.heater_enabled
.manual_heater_enabled
) )
if ( if (
auto_controller.manual_target_temperature temperature_config.target_temp
is not None is not None
): ):
tion_status["target_temp"] = ( tion_status["target_temp"] = (
auto_controller temperature_config.target_temp
.manual_target_temperature
)
elif tion_status is not None:
schedule = schedule_service
if schedule is not None:
# Ручной override имеет приоритет над AUTO.
if (
schedule.override_active
and schedule.override_settings.target_temp
is not None
):
tion_status["target_temp"] = (
schedule.override_settings.target_temp
)
else:
resolution = schedule.resolve()
if (
resolution.enabled
and resolution.auto_active
and resolution.auto_target_temp
is not None
):
tion_status["target_temp"] = (
resolution.auto_target_temp
) )
@@ -457,27 +505,15 @@ def get_effective_speed() -> int:
def get_effective_temperature() -> int: def get_effective_temperature() -> int:
if ( if auto_controller is not None:
schedule_service is not None
and schedule_service.paused config = (
and auto_controller is not None
and auto_controller.manual_target_temperature is not None
):
return (
auto_controller auto_controller
.manual_target_temperature .effective_temperature_config()
) )
if ( if config.target_temp is not None:
schedule_service is not None return config.target_temp
and schedule_service.override_active
and schedule_service.override_settings.target_temp is not None
):
return (
schedule_service
.override_settings
.target_temp
)
state = service.state state = service.state
@@ -529,6 +565,60 @@ async def execute_command(operation, override: ScheduledSettings | None = None):
return get_status() return get_status()
async def execute_temperature_command(
operation,
settings: ScheduledSettings,
):
try:
if (
auto_controller is not None
and schedule_service is not None
and schedule_service.running
and schedule_service.config.enabled
):
# ------------------------------------------
# PAUSE = полноценный ручной режим.
# ------------------------------------------
if schedule_service.paused:
if settings.heater is not None:
auto_controller.set_manual_heater_enabled(settings.heater)
if settings.target_temp is not None:
auto_controller.set_manual_target_temperature(settings.target_temp)
# ------------------------------------------
# SET / AUTO = temporary override.
# ------------------------------------------
else:
await schedule_service.apply_override(settings)
# Не ждём следующего 5-секундного цикла.
await auto_controller.reconcile_temperature()
else:
# Fallback, если расписание/AutoController
# вообще не работают.
await service.execute(operation)
except Exception as exc:
raise HTTPException(
status_code=503,
detail={
"message": "Tion unavailable",
"error": (
f"{type(exc).__name__}: {exc}"
),
},
) from exc
return get_status()
def occurrence_to_dict(occurrence) -> dict | None: def occurrence_to_dict(occurrence) -> dict | None:
@@ -676,7 +766,6 @@ def get_auto_status() -> dict:
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Status # Status
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/status") @app.get("/api/status")
async def status(): async def status():
return get_status() return get_status()
@@ -685,7 +774,6 @@ async def status():
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Elica / exhaust # Elica / exhaust
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/elica/status") @app.get("/api/elica/status")
async def elica_status(): async def elica_status():
return get_elica_status() return get_elica_status()
@@ -734,7 +822,6 @@ async def set_external_fan(state: Literal["on", "off"]):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Power # Power
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/power/{state}") @app.post("/api/tion/power/{state}")
async def set_power(state: Literal["on", "off"]): async def set_power(state: Literal["on", "off"]):
@@ -754,7 +841,6 @@ async def set_power(state: Literal["on", "off"]):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Fan speed increase / decrease # Fan speed increase / decrease
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/speed/increase") @app.post("/api/tion/speed/increase")
async def increase_speed(): async def increase_speed():
@@ -816,96 +902,32 @@ async def set_speed(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Heater # Heater
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/heater/{state}") @app.post("/api/tion/heater/{state}")
async def set_heater(state: Literal["on", "off"]): async def set_heater(
state: Literal["on", "off"],
):
enabled = state == "on" enabled = state == "on"
if enabled: operation = (
operation = lambda tion: tion.heater_on() (lambda tion: tion.heater_on())
else: if enabled
operation = lambda tion: tion.heater_off() else
(lambda tion: tion.heater_off())
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() return await execute_temperature_command(
operation,
# ----------------------------------------------------------------------
# Target temperature increase / decrease
# ----------------------------------------------------------------------
@app.post("/api/tion/temperature/increase")
async def increase_temperature():
current_temperature = get_effective_temperature()
new_temperature = min(current_temperature + 1, MAX_TARGET_TEMP)
if new_temperature == current_temperature:
return get_status()
await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings( ScheduledSettings(
target_temp=new_temperature, heater=enabled,
), ),
) )
if (
schedule_service is not None
and schedule_service.paused
and auto_controller is not None
):
auto_controller.set_manual_target_temperature(new_temperature)
return get_status()
@app.post("/api/tion/temperature/{temperature}")
async def set_temperature(
temperature: int,
):
await execute_command(
lambda tion:
tion.set_target_temperature(
temperature
),
ScheduledSettings(
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 # Target temperature
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/temperature/{temperature}") @app.post("/api/tion/temperature/{temperature}")
async def set_temperature( async def set_temperature(
temperature: Annotated[ temperature: Annotated[
int, int,
@@ -913,19 +935,24 @@ async def set_temperature(
ge=MIN_TARGET_TEMP, ge=MIN_TARGET_TEMP,
le=MAX_TARGET_TEMP, le=MAX_TARGET_TEMP,
), ),
],): ],
):
return await execute_command( return await execute_temperature_command(
lambda tion: lambda tion:
tion.set_target_temperature(temperature), tion.set_target_temperature(
ScheduledSettings(target_temp=temperature), temperature
),
ScheduledSettings(
target_temp=temperature,
),
) )
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Air mode # Air mode
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/mode/{mode}") @app.post("/api/tion/mode/{mode}")
async def set_mode( async def set_mode(
mode: str, mode: str,
@@ -957,7 +984,6 @@ async def set_mode(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Sound # Sound
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/sound/{value}") @app.post("/api/tion/sound/{value}")
async def set_sound( async def set_sound(
value: Literal["on", "off"], value: Literal["on", "off"],
@@ -980,7 +1006,6 @@ async def set_sound(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Light # Light
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/light/{value}") @app.post("/api/tion/light/{value}")
async def set_light( async def set_light(
value: Literal["on", "off"], value: Literal["on", "off"],
@@ -1002,7 +1027,6 @@ async def set_light(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Переход в auto # Переход в auto
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/schedule/config") @app.get("/api/schedule/config")
async def get_schedule_config(): async def get_schedule_config():
try: try:
@@ -1092,6 +1116,9 @@ async def clear_schedule_override():
await schedule_service.clear_override() await schedule_service.clear_override()
if auto_controller is not None:
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -1110,56 +1137,42 @@ async def pause_schedule():
detail="Schedule service unavailable", detail="Schedule service unavailable",
) )
state = service.state # ВАЖНО:
# получаем логические настройки ДО pause(),
# потому что там ещё действует SET/AUTO/override.
temperature_config = None
manual_target = None if auto_controller is not None:
temperature_config = (
if state is not None: auto_controller
manual_target = state.target_temp .effective_temperature_config()
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() await schedule_service.pause()
if ( if (
auto_controller is not None auto_controller is not None
and state is not None and temperature_config is not None
):
if (
temperature_config.heater_enabled
is not None
): ):
auto_controller.set_manual_heater_enabled( auto_controller.set_manual_heater_enabled(
state.heater temperature_config.heater_enabled
) )
if manual_target is not None: if (
temperature_config.target_temp
is not None
):
auto_controller.set_manual_target_temperature( auto_controller.set_manual_target_temperature(
manual_target temperature_config.target_temp
) )
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -1182,6 +1195,8 @@ async def resume_schedule():
if auto_controller is not None: if auto_controller is not None:
auto_controller.clear_manual_heater_control() auto_controller.clear_manual_heater_control()
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
+4
View File
@@ -1,7 +1,9 @@
from .config import ( from .config import (
AutoConfig, AutoConfig,
AutoConfigComponents,
Co2Config, Co2Config,
load_auto_config, load_auto_config,
load_auto_config_components,
) )
from .co2_policy import ( from .co2_policy import (
@@ -19,4 +21,6 @@ __all__ = [
"load_auto_config", "load_auto_config",
"Co2SpeedPolicy", "Co2SpeedPolicy",
"AutoController", "AutoController",
"AutoConfigComponents",
"load_auto_config_components",
] ]
+210 -112
View File
@@ -57,6 +57,20 @@ class AutoConfig:
elica_assist: ElicaAssistConfig elica_assist: ElicaAssistConfig
@dataclass(
frozen=True,
slots=True,
)
class AutoConfigComponents:
version: int
check_interval: float
co2: Co2Config | None
temperature: TemperatureConfig | None
elica_assist: ElicaAssistConfig | None
errors: dict[str, str]
def _require_dict(name: str, value: Any) -> dict: def _require_dict(name: str, value: Any) -> dict:
if not isinstance(value, dict): if not isinstance(value, dict):
@@ -262,111 +276,32 @@ def _parse_co2(value: Any) -> Co2Config:
thresholds=thresholds, thresholds=thresholds,
) )
def _parse_temperature(value: Any) -> TemperatureConfig:
def load_auto_config(path: str | Path) -> AutoConfig:
path = Path(path)
with path.open(
"r",
encoding="utf-8",
) as file:
raw = yaml.safe_load(file)
data = _require_dict( data = _require_dict(
"AUTO config",
raw,
)
unknown = set(data) - {
"version",
"check_interval",
"co2",
"temperature", "temperature",
"elica_assist", value,
}
if unknown:
raise ValueError(
f"Unknown AUTO config fields: "
f"{sorted(unknown)}"
) )
version = data.get("version") unknown = (
set(data)
if version != 1:
raise ValueError(
f"Unsupported AUTO config "
f"version: {version!r}"
)
check_interval = data.get(
"check_interval"
)
if (
type(check_interval) not in {
int,
float,
}
):
raise ValueError(
"check_interval must be a number"
)
if check_interval <= 0:
raise ValueError(
"check_interval must be > 0"
)
# --------------------------------------------------
# CO2
# --------------------------------------------------
if "co2" not in data:
raise ValueError(
"co2 config is required"
)
co2 = _parse_co2(
data["co2"]
)
# --------------------------------------------------
# Temperature
# --------------------------------------------------
if "temperature" not in data:
raise ValueError(
"temperature config is required"
)
temperature_data = _require_dict(
"temperature",
data["temperature"],
)
unknown_temperature = (
set(temperature_data)
- { - {
"hysteresis", "hysteresis",
} }
) )
if unknown_temperature: if unknown:
raise ValueError( raise ValueError(
f"Unknown temperature config fields: " f"Unknown temperature config fields: "
f"{sorted(unknown_temperature)}" f"{sorted(unknown)}"
) )
temperature_hysteresis = ( hysteresis = data.get(
temperature_data.get(
"hysteresis" "hysteresis"
) )
)
if ( if (
type(temperature_hysteresis) type(hysteresis)
not in { not in {
int, int,
float, float,
@@ -377,45 +312,40 @@ def load_auto_config(path: str | Path) -> AutoConfig:
"must be a number" "must be a number"
) )
temperature_hysteresis = float( hysteresis = float(hysteresis)
temperature_hysteresis
)
if temperature_hysteresis < 0: if hysteresis < 0:
raise ValueError( raise ValueError(
"temperature.hysteresis " "temperature.hysteresis "
"must be >= 0" "must be >= 0"
) )
temperature = TemperatureConfig( return TemperatureConfig(
hysteresis=temperature_hysteresis, hysteresis=hysteresis,
) )
def _parse_elica_assist(value: Any) -> ElicaAssistConfig:
# -------------------------------------------------- data = _require_dict(
# Elica Auto Assist
# --------------------------------------------------
if "elica_assist" not in data:
raise ValueError("elica_assist config is required")
elica_data = _require_dict(
"elica_assist", "elica_assist",
data["elica_assist"], value,
) )
unknown_elica = ( unknown = (
set(elica_data) set(data)
- { - {
"enabled", "enabled",
"speed_map", "speed_map",
} }
) )
if unknown_elica: if unknown:
raise ValueError(f"Unknown elica_assist config fields: {sorted(unknown_elica)}") raise ValueError(
"Unknown elica_assist config fields: "
f"{sorted(unknown)}"
)
enabled = elica_data.get("enabled") enabled = data.get("enabled")
if type(enabled) is not bool: if type(enabled) is not bool:
raise ValueError( raise ValueError(
@@ -423,19 +353,25 @@ def load_auto_config(path: str | Path) -> AutoConfig:
"must be a boolean" "must be a boolean"
) )
speed_map_data = elica_data.get("speed_map") speed_map_data = data.get(
"speed_map"
)
if not isinstance( if not isinstance(
speed_map_data, speed_map_data,
dict, dict,
): ):
raise ValueError("elica_assist.speed_map must be an object") raise ValueError(
"elica_assist.speed_map "
"must be an object"
)
speed_map = [] speed_map = []
for tion_speed, elica_speed in ( for tion_speed, elica_speed in (
speed_map_data.items() speed_map_data.items()
): ):
if type(tion_speed) is not int: if type(tion_speed) is not int:
raise ValueError( raise ValueError(
"elica_assist.speed_map keys " "elica_assist.speed_map keys "
@@ -478,21 +414,183 @@ def load_auto_config(path: str | Path) -> AutoConfig:
speed_map.sort() speed_map.sort()
elica_assist = ElicaAssistConfig( return ElicaAssistConfig(
enabled=enabled, enabled=enabled,
speed_map=tuple(speed_map), speed_map=tuple(speed_map),
) )
def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
path = Path(path)
with path.open(
"r",
encoding="utf-8",
) as file:
raw = yaml.safe_load(file)
data = _require_dict(
"AUTO config",
raw,
)
unknown = set(data) - {
"version",
"check_interval",
"co2",
"temperature",
"elica_assist",
}
if unknown:
raise ValueError(
f"Unknown AUTO config fields: "
f"{sorted(unknown)}"
)
version = data.get("version")
if version != 1:
raise ValueError(
f"Unsupported AUTO config "
f"version: {version!r}"
)
check_interval = data.get(
"check_interval"
)
if (
type(check_interval)
not in {int,float,}
):
raise ValueError(
"check_interval must be a number"
)
if check_interval <= 0:
raise ValueError(
"check_interval must be > 0"
)
return (data, version, float(check_interval))
def load_auto_config(
path: str | Path,
) -> AutoConfig:
(
data,
version,
check_interval,
) = _load_auto_root(path)
# -------------------------------------------------- # --------------------------------------------------
# Result # CO2
# -------------------------------------------------- # --------------------------------------------------
if "co2" not in data:
raise ValueError("co2 config is required")
co2 = _parse_co2(data["co2"])
# --------------------------------------------------
# Temperature
# --------------------------------------------------
if "temperature" not in data:
raise ValueError("temperature config is required")
temperature = _parse_temperature(data["temperature"])
# --------------------------------------------------
# Elica Auto Assist
# --------------------------------------------------
if "elica_assist" not in data:
raise ValueError("elica_assist config is required")
elica_assist = _parse_elica_assist(data["elica_assist"])
return AutoConfig( return AutoConfig(
version=version, version=version,
check_interval=float(check_interval), check_interval=check_interval,
co2=co2, co2=co2,
temperature=temperature, temperature=temperature,
elica_assist=elica_assist, elica_assist=elica_assist,
) )
def load_auto_config_components(path: str | Path) -> AutoConfigComponents:
( data,
version,
check_interval,
) = _load_auto_root(path)
errors: dict[str, str] = {}
# --------------------------------------------------
# CO2
# --------------------------------------------------
co2 = None
if "co2" not in data:
errors["co2"] = "ValueError: co2 config is required"
else:
try:
co2 = _parse_co2(data["co2"])
except Exception as exc:
errors["co2"] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Temperature
# --------------------------------------------------
temperature = None
if "temperature" not in data:
errors["temperature"] = "ValueError: temperature config is required"
else:
try:
temperature = _parse_temperature(data["temperature"])
except Exception as exc:
errors["temperature"] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Elica Assist
# --------------------------------------------------
elica_assist = None
if "elica_assist" not in data:
errors["elica_assist"] = "ValueError: elica_assist config is required"
else:
try:
elica_assist = _parse_elica_assist(data["elica_assist"])
except Exception as exc:
errors["elica_assist"] = (
f"{type(exc).__name__}: {exc}"
)
return AutoConfigComponents(
version=version,
check_interval=check_interval,
co2=co2,
temperature=temperature,
elica_assist=elica_assist,
errors=errors,
)
+269 -353
View File
@@ -1,4 +1,5 @@
import asyncio import asyncio
from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from app.auto.co2_policy import Co2SpeedPolicy from app.auto.co2_policy import Co2SpeedPolicy
from app.auto.temperature_policy import TemperaturePolicy from app.auto.temperature_policy import TemperaturePolicy
@@ -8,6 +9,12 @@ from app.auto.elica_assist import (
ElicaAutoAssistState, ElicaAutoAssistState,
) )
@dataclass(frozen=True, slots=True)
class EffectiveTemperatureConfig:
heater_enabled: bool | None
target_temp: int | None
class AutoController: class AutoController:
def __init__( def __init__(
@@ -46,6 +53,11 @@ class AutoController:
self._temperature: float | int | None = None self._temperature: float | int | None = None
self._temperature_source: str | None = None self._temperature_source: str | None = None
# Последнее решение единого внешнего
# температурного регулятора.
self._temperature_heating: bool | None = None
# -------------------------------------------------- # --------------------------------------------------
# Ручное управление обогревом. # Ручное управление обогревом.
# #
@@ -103,19 +115,45 @@ class AutoController:
await asyncio.sleep( self._interval ) await asyncio.sleep( self._interval )
async def _process(self) -> None: async def _process(self) -> None:
now = datetime.now() now = datetime.now()
resolution = self._schedule.resolve(now) resolution = self._schedule.resolve(now)
# ---------------------------------------------- # Ручная температурная конфигурация нужна
# Расписание поставлено на паузу. # только во время PAUSE.
if (
not getattr(
self._schedule,
"paused",
False,
)
and (
self._manual_heater_enabled is not None
or self._manual_target_temperature is not None
)
):
self.clear_manual_heater_control()
# --------------------------------------------------
# Температурный контур работает ВСЕГДА:
# #
# Это полноценный ручной режим: # SET
# AUTO вообще не имеет права управлять Tion. # AUTO
# ---------------------------------------------- # PAUSE
# temporary override
# --------------------------------------------------
temperature_config = (
self._get_effective_temperature_config(resolution)
)
await self._process_temperature(temperature_config)
# --------------------------------------------------
# PAUSE
# --------------------------------------------------
if getattr( if getattr(
self._schedule, self._schedule,
@@ -125,19 +163,13 @@ class AutoController:
self._state = "suspended" self._state = "suspended"
self._reason = "schedule_paused" self._reason = "schedule_paused"
# После перехода в ручной режим пользователь
# может изменить эти параметры напрямую.
# Поэтому старые значения AUTO больше
# нельзя считать достоверными.
self._target_speed = None self._target_speed = None
self._auto_speed = None self._auto_speed = None
self._auto_heater = None self._auto_heater = None
self._manual_heating = (
self._temperature = None self._temperature_heating
self._temperature_source = None )
await self._process_manual_heater()
self._last_error = None self._last_error = None
@@ -145,69 +177,28 @@ class AutoController:
return return
# ---------------------------------------------- # В режимах расписания результат относится
# Активен ручной override. # к общему температурному контуру.
self._manual_heating = None
self._auto_heater = (
self._temperature_heating
)
# --------------------------------------------------
# Temporary override.
# #
# Пока пользователь вручную управляет Tion, # Температура уже обработана выше.
# AUTO вообще не вмешивается. # AUTO скоростью во время override
# ---------------------------------------------- # по-прежнему не управляет.
# --------------------------------------------------
if self._schedule.override_active: if self._schedule.override_active:
self._state = "suspended" self._state = "suspended"
self._reason = "manual_override" self._reason = "manual_override"
# AUTO скоростью больше не управляет.
self._target_speed = None self._target_speed = None
self._auto_speed = None self._auto_speed = None
# AUTO-регулятор температуры также
# больше не используется.
self._auto_heater = 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 self._last_error = None
await self._release_elica_assist() await self._release_elica_assist()
@@ -215,68 +206,56 @@ class AutoController:
return return
# -------------------------------------------------- # --------------------------------------------------
# Override закончился. # Не AUTO.
# Его ручную температурную сессию забываем. #
# Температура уже обработана выше.
# Здесь просто нечего делать с AUTO-скоростью.
# -------------------------------------------------- # --------------------------------------------------
if (
self._manual_heater_enabled is not None
or self._manual_target_temperature is not None
):
self.clear_manual_heater_control()
# ----------------------------------------------
# AUTO сейчас не активен
# ----------------------------------------------
if ( if (
not resolution.enabled not resolution.enabled
or not resolution.auto_active or not resolution.auto_active
): ):
self._state = "inactive" self._state = "inactive"
self._reason = None self._reason = None
# Управление возвращается ScheduleService.
# После этого AUTO уже не знает фактическое
# состояние speed/heater, поэтому забываем его.
self._target_speed = None self._target_speed = None
self._auto_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
self._last_error = None self._last_error = None
await self._release_elica_assist() await self._release_elica_assist()
return return
fallback_speed = resolution.auto_fallback_speed # --------------------------------------------------
# Ниже остаётся только AUTO-управление скоростью.
# --------------------------------------------------
fallback_speed = (resolution.auto_fallback_speed)
if fallback_speed is None: if fallback_speed is None:
raise RuntimeError( raise RuntimeError(
"AUTO is active but " "AUTO is active but "
"fallback speed is missing" "fallback speed is missing"
) )
# ----------------------------------------------
# CO2 policy недоступна. # CO2 policy недоступна.
#
# Например, auto.yaml не загрузился.
# AUTO работает в аварийном fallback-only режиме.
# ----------------------------------------------
if self._policy is None: if self._policy is None:
self._state = "fallback" self._state = "fallback"
self._reason = "auto_policy_unavailable" self._reason = (
"auto_policy_unavailable"
)
self._auto_speed = None self._auto_speed = None
await self._set_speed(fallback_speed) await self._set_speed(
fallback_speed
)
await self._update_elica_assist(fallback_speed) await self._update_elica_assist(
fallback_speed
if self._temperature_policy is not None: )
await self._process_heater(resolution)
self._last_error = None self._last_error = None
@@ -284,10 +263,7 @@ class AutoController:
qingping_state = self._qingping.state qingping_state = self._qingping.state
# ---------------------------------------------- # Qingping исправен.
# Qingping исправен
# ----------------------------------------------
if ( if (
self._qingping.online self._qingping.online
and qingping_state.co2 is not None and qingping_state.co2 is not None
@@ -302,27 +278,23 @@ class AutoController:
self._state = "active" self._state = "active"
self._reason = None self._reason = None
await self._set_speed(target_speed) await self._set_speed(
target_speed
)
await self._update_elica_assist(target_speed) await self._update_elica_assist(
target_speed
)
self._auto_speed = target_speed self._auto_speed = target_speed
if self._temperature_policy is not None:
await self._process_heater(resolution)
self._last_error = None self._last_error = None
return return
# ---------------------------------------------- # Qingping недоступен для CO2.
# AUTO не может работать.
# Переходим на fallback.
# ----------------------------------------------
if not self._qingping.online: if not self._qingping.online:
reason = "qingping_offline" reason = "qingping_offline"
else: else:
reason = "co2_missing" reason = "co2_missing"
@@ -331,169 +303,142 @@ class AutoController:
self._auto_speed = None self._auto_speed = None
await self._set_speed(fallback_speed) await self._set_speed(
fallback_speed
)
await self._update_elica_assist(fallback_speed) await self._update_elica_assist(
fallback_speed
if self._temperature_policy is not None:
await self._process_heater(
resolution
) )
self._last_error = None self._last_error = None
def _get_effective_temperature_config(
async def _process_heater(self, resolution) -> None:
# --------------------------------------------------
# Берём целевую температуру из накопленных
# настроек расписания.
#
# Например:
#
# SET target_temp=20
# AUTO
#
# Во время AUTO target_temp остаётся 20.
# --------------------------------------------------
target_temp = resolution.auto_target_temp
# --------------------------------------------------
# Получаем фактическую температуру.
#
# _get_temperature() сам выбирает:
#
# 1. Qingping
# 2. Tion как резерв
# 3. None, если оба источника недоступны
# --------------------------------------------------
temperature, source = self._get_temperature()
self._temperature = temperature
self._temperature_source = source
# --------------------------------------------------
# Нет температурной policy.
#
# AUTO не умеет безопасно принять решение
# о нагреве → выключаем heater.
# --------------------------------------------------
if self._temperature_policy is None:
await self._set_heater(False)
self._auto_heater = False
return
# --------------------------------------------------
# Нет целевой температуры.
#
# Непонятно, до какой температуры греть.
# Поэтому heater OFF.
# --------------------------------------------------
if target_temp is None:
await self._set_heater(False)
self._auto_heater = False
return
# --------------------------------------------------
# Нет достоверной фактической температуры.
#
# Ни Qingping, ни резервный датчик Tion
# использовать нельзя.
#
# Heater OFF.
# --------------------------------------------------
if temperature is None:
await self._set_heater(False)
self._auto_heater = False
return
# --------------------------------------------------
# Есть всё необходимое:
#
# - фактическая температура;
# - target_temp;
# - TemperaturePolicy.
#
# Policy решает, нужно ли сейчас греть.
# --------------------------------------------------
heater_required = (
self._temperature_policy
.heater_required(
temperature=temperature,
target_temp=target_temp,
heater_on=(
self._auto_heater
is True
),
)
)
if heater_required:
# Наш внешний регулятор решил, что нужно греть.
#
# Сначала поднимаем внутреннюю уставку Tion
# до максимума, чтобы встроенный термостат
# не заблокировал нагрев по своему in_temp.
await self._set_target_temperature(MAX_TARGET_TEMP)
# После этого разрешаем нагреватель.
await self._set_heater(True)
else:
# Целевая температура по внешнему датчику
# достигнута — нагрев запрещаем.
await self._set_heater(False)
self._auto_heater = heater_required
async def _process_manual_heater(
self, self,
) -> None: resolution,
""" ) -> EffectiveTemperatureConfig:
Управление обогревом в полном ручном режиме.
Приоритет: # --------------------------------------------------
1. Qingping -> внешний регулятор. # PAUSE.
2. Qingping недоступен -> штатный #
термостат Tion. # Источник настроек — ручное состояние.
""" # --------------------------------------------------
enabled = self._manual_heater_enabled if getattr(
self._schedule,
"paused",
False,
):
return EffectiveTemperatureConfig(
heater_enabled=(
self._manual_heater_enabled
),
target_temp=( target_temp=(
self._manual_target_temperature self._manual_target_temperature
),
) )
# -------------------------------------------------- # --------------------------------------------------
# Пользователь явно выключил обогрев. # Базовая конфигурация всегда приходит
# из накопленных SET-настроек.
# --------------------------------------------------
heater_enabled = (
resolution
.scheduled_settings
.heater
)
target_temp = (
resolution
.scheduled_settings
.target_temp
)
# --------------------------------------------------
# AUTO может иметь собственную температуру.
#
# Если её нет — остаётся температура
# накопленного SET.
# --------------------------------------------------
if (
resolution.auto_active
and resolution.auto_target_temp
is not None
):
target_temp = (
resolution.auto_target_temp
)
# --------------------------------------------------
# Temporary override — это НАЛОЖЕНИЕ
# поверх текущей конфигурации.
#
# target_temp не включает heater автоматически.
# --------------------------------------------------
if self._schedule.override_active:
override = (
self._schedule.override_settings
)
if override.heater is not None:
heater_enabled = (
override.heater
)
if override.target_temp is not None:
target_temp = (
override.target_temp
)
return EffectiveTemperatureConfig(
heater_enabled=heater_enabled,
target_temp=target_temp,
)
async def _process_temperature(
self,
config: EffectiveTemperatureConfig,
) -> None:
enabled = config.heater_enabled
target_temp = config.target_temp
# --------------------------------------------------
# heater=false имеет абсолютный приоритет.
# -------------------------------------------------- # --------------------------------------------------
if enabled is False: if enabled is False:
await self._set_heater(False) await self._set_heater(False)
self._manual_heating = False self._temperature_heating = False
return return
# Состояние ручного управления ещё
# не инициализировано.
if enabled is None:
self._manual_heating = None
return
# -------------------------------------------------- # --------------------------------------------------
# Heater разрешён, но нет пользовательской цели. # Heater вообще не определён.
# #
# Греть без уставки нельзя. # Ничего физически не меняем.
# --------------------------------------------------
if enabled is None:
self._temperature_heating = None
return
# --------------------------------------------------
# Heater разрешён, но цели нет.
#
# Безопасное состояние — OFF.
# -------------------------------------------------- # --------------------------------------------------
if target_temp is None: if target_temp is None:
await self._set_heater(False) await self._set_heater(False)
self._manual_heating = False self._temperature_heating = False
return return
@@ -506,32 +451,73 @@ class AutoController:
) )
# -------------------------------------------------- # --------------------------------------------------
# Qingping недоступен. # Qingping доступен и TemperaturePolicy работает.
# #
# Возвращаем управление встроенному # Решение принимаем ТОЛЬКО по Qingping.
# термостату Tion:
#
# target = пользовательская температура
# heater = ON
#
# Дальше Tion сам решает, когда реально греть.
# -------------------------------------------------- # --------------------------------------------------
if ( if (
not self._qingping.online self._qingping.online
or qingping_temperature is None and qingping_temperature is not None
or self._temperature_policy is None and self._temperature_policy is not None
): ):
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._temperature_heating
is True
),
)
)
# Встроенный термостат Tion
# не должен мешать внешнему регулятору.
await self._set_target_temperature(
MAX_TARGET_TEMP
)
await self._set_heater(
heater_required
)
self._temperature_heating = (
heater_required
)
return
# --------------------------------------------------
# Qingping недоступен либо отсутствует
# TemperaturePolicy.
#
# Никаких решений по Tion.in_temp!
#
# Возвращаем управление штатному
# термостату Tion.
# --------------------------------------------------
await self._set_target_temperature( await self._set_target_temperature(
target_temp target_temp
) )
await self._set_heater(True) await self._set_heater(True)
self._manual_heating = None self._temperature_heating = None
# Это только диагностическое значение. # Tion.in_temp здесь только для диагностики.
# Решение по нему мы НЕ принимаем.
tion_state = self._tion.state tion_state = self._tion.state
if ( if (
@@ -542,100 +528,16 @@ class AutoController:
self._temperature = ( self._temperature = (
tion_state.in_temp tion_state.in_temp
) )
self._temperature_source = "tion" self._temperature_source = "tion"
else: else:
self._temperature = None self._temperature = None
self._temperature_source = 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]:
# --------------------------------------------------
# Основной источник — Qingping.
#
# Используем температуру Qingping только если
# сам поток данных датчика сейчас считается online.
# --------------------------------------------------
qingping_state = self._qingping.state
if (
self._qingping.online
and qingping_state.temperature is not None
):
return (
qingping_state.temperature,
"qingping",
)
# --------------------------------------------------
# Qingping недоступен или температура отсутствует.
#
# Пробуем резервный датчик температуры Tion.
#
# Важно проверять tion.online:
# TionService может хранить последнее состояние,
# даже если связь с устройством уже потеряна.
# --------------------------------------------------
tion_state = self._tion.state
if (
self._tion.online
and tion_state is not None
and tion_state.in_temp is not None
):
return (
tion_state.in_temp,
"tion",
)
# --------------------------------------------------
# Достоверной температуры нет вообще.
# --------------------------------------------------
return None, None
async def _update_elica_assist( async def _update_elica_assist(
self, self,
@@ -1028,6 +930,20 @@ class AutoController:
def manual_target_temperature(self) -> int | None: def manual_target_temperature(self) -> int | None:
return self._manual_target_temperature return self._manual_target_temperature
def effective_temperature_config(self,) -> EffectiveTemperatureConfig:
resolution = self._schedule.resolve()
return self._get_effective_temperature_config(resolution)
async def reconcile_temperature(self) -> None:
"""
Немедленно применить текущую логическую
температурную конфигурацию.
"""
config = self.effective_temperature_config()
await self._process_temperature(config)
def status(self) -> dict: def status(self) -> dict:
return { return {
"state": self._state, "state": self._state,
-24
View File
@@ -561,15 +561,9 @@ class ScheduleService:
if resolution.auto_active: if resolution.auto_active:
# В режиме AUTO скорость принадлежит # В режиме AUTO скорость принадлежит
# AutoController. # AutoController.
#
# Остальные параметры расписания
# (power, heater, temperature, mode...)
# должны продолжать работать.
settings = replace( settings = replace(
settings, settings,
speed=None, speed=None,
heater=None,
target_temp=None,
) )
await self._apply_settings(settings) await self._apply_settings(settings)
@@ -598,24 +592,6 @@ class ScheduleService:
tion.set_air_mode(settings.mode) tion.set_air_mode(settings.mode)
) )
if settings.target_temp is not None:
await self._tion.execute(
lambda tion:
tion.set_target_temperature(
settings.target_temp
)
)
if settings.heater is not None:
if settings.heater:
await self._tion.execute(
lambda tion: tion.heater_on()
)
else:
await self._tion.execute(
lambda tion: tion.heater_off()
)
if settings.speed is not None: if settings.speed is not None:
await self._tion.execute( await self._tion.execute(
lambda tion: lambda tion:
+134
View File
@@ -0,0 +1,134 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from app.auto.config import (
load_auto_config_components,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
from app.auto.elica_assist import (
ElicaAutoAssistState,
)
BROKEN_CO2_CONFIG = """
version: 1
check_interval: 5.0
co2:
base_speed: 2
hysteresis: 100
thresholds:
- ppm: 700
speed: 2
- ppm: 1000
speed: 3
temperature:
hysteresis: 0.5
elica_assist:
enabled: false
speed_map:
4: 1
5: 2
6: 3
"""
def main():
with TemporaryDirectory() as directory:
path = (
Path(directory)
/ "auto.yaml"
)
path.write_text(
BROKEN_CO2_CONFIG,
encoding="utf-8",
)
config = (
load_auto_config_components(
path
)
)
# ----------------------------------------------
# CO2 должен быть отключён.
# ----------------------------------------------
assert config.co2 is None
assert "co2" in config.errors
assert (
"First threshold speed must be "
"greater than base_speed"
in config.errors["co2"]
)
# ----------------------------------------------
# Temperature должна остаться рабочей.
# ----------------------------------------------
assert config.temperature is not None
assert (
config.temperature.hysteresis
== 0.5
)
temperature_policy = (
TemperaturePolicy(
config.temperature
)
)
assert (
temperature_policy.heater_required(
temperature=20,
target_temp=24,
heater_on=False,
)
is True
)
# ----------------------------------------------
# Elica Assist тоже не должна пострадать.
# ----------------------------------------------
assert (
config.elica_assist
is not None
)
elica_assist = (
ElicaAutoAssistState(
config.elica_assist
)
)
assert elica_assist is not None
# Ошибка должна быть только в CO2.
assert set(config.errors) == {
"co2",
}
print(
"AUTO CONFIG ISOLATION TEST PASSED"
)
if __name__ == "__main__":
main()
-304
View File
@@ -1,304 +0,0 @@
import asyncio
from types import SimpleNamespace
from app.auto.config import (
TemperatureConfig,
)
from app.auto.controller import (
AutoController,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
class FakeQingpingService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
temperature=19.4,
)
class FakeTionController:
def __init__(self):
self.calls = []
async def heater_on(self):
self.calls.append(
("heater_on", None)
)
async def heater_off(self):
self.calls.append(
("heater_off", None)
)
class FakeTionService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=18,
)
self.controller = (
FakeTionController()
)
async def execute(
self,
operation,
):
return await operation(
self.controller
)
def make_resolution(
target_temp=20.0,
):
return SimpleNamespace(
scheduled_settings=(
SimpleNamespace(
target_temp=target_temp,
)
)
)
def make_controller():
qingping = (
FakeQingpingService()
)
tion = FakeTionService()
policy = TemperaturePolicy(
TemperatureConfig(
hysteresis=0.5,
)
)
controller = AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
temperature_policy=policy,
)
return (
controller,
qingping,
tion,
)
async def test_qingping_heating():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
# 19.4 < 19.5
# Heater должен включиться.
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_on", None)
]
assert (
controller._auto_heater
is True
)
assert (
controller._temperature
== 19.4
)
assert (
controller._temperature_source
== "qingping"
)
tion.controller.calls.clear()
# ----------------------------------------------
# 19.8
#
# Heater уже ON.
# До 20 градусов ещё не дошли.
# Продолжаем греть.
#
# Новую команду отправлять не нужно.
# ----------------------------------------------
qingping.state.temperature = 19.8
await controller._process_heater(
resolution
)
assert tion.controller.calls == []
assert (
controller._auto_heater
is True
)
# ----------------------------------------------
# 20.0
#
# Цель достигнута.
# ----------------------------------------------
qingping.state.temperature = 20.0
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
async def test_tion_temperature_fallback():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
# Qingping отключился.
qingping.online = False
# Используем Tion.
tion.state.in_temp = 19
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_on", None)
]
assert (
controller._temperature
== 19
)
assert (
controller._temperature_source
== "tion"
)
assert (
controller._auto_heater
is True
)
async def test_no_temperature():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
qingping.online = False
tion.online = False
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._temperature
is None
)
assert (
controller._temperature_source
is None
)
assert (
controller._auto_heater
is False
)
async def test_target_temperature_missing():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution(
target_temp=None
)
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
async def main():
await test_qingping_heating()
await test_tion_temperature_fallback()
await test_no_temperature()
await test_target_temperature_missing()
print()
print("=" * 70)
print(
"ALL AUTO HEATER PROCESS "
"TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
@@ -1,138 +0,0 @@
import asyncio
from types import SimpleNamespace
from app.auto.config import (
TemperatureConfig,
)
from app.auto.controller import (
AutoController,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
class FakeQingpingService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
temperature=19.5,
)
class FakeTionController:
def __init__(self):
self.calls = []
async def heater_on(self):
self.calls.append(
("heater_on", None)
)
async def heater_off(self):
self.calls.append(
("heater_off", None)
)
class FakeTionService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=19,
)
self.controller = (
FakeTionController()
)
async def execute(
self,
operation,
):
return await operation(
self.controller
)
async def test_auto_uses_auto_target_temperature():
qingping = FakeQingpingService()
tion = FakeTionService()
policy = TemperaturePolicy(
TemperatureConfig(
hysteresis=0.5,
)
)
controller = AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
temperature_policy=policy,
)
resolution = SimpleNamespace(
# Последний SET хотел 23°C.
scheduled_settings=SimpleNamespace(
target_temp=23,
),
# Но текущий AUTO явно хочет 20°C.
auto_target_temp=20,
)
await controller._process_heater(
resolution
)
# При 19.5°C и target=20°C:
#
# heater был OFF,
# нижняя граница = 19.5°C.
#
# Поэтому heater должен остаться OFF.
#
# Если бы контроллер ошибочно использовал
# SET target_temp=23, он бы включил heater.
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
assert (
controller._temperature
== 19.5
)
assert (
controller._temperature_source
== "qingping"
)
async def main():
await test_auto_uses_auto_target_temperature()
print()
print("=" * 70)
print(
"ALL AUTO HEATER TARGET "
"TEMPERATURE TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
-169
View File
@@ -1,169 +0,0 @@
from types import SimpleNamespace
from app.auto.controller import AutoController
class FakeQingpingService:
def __init__(
self,
online: bool,
temperature,
):
self.online = online
self.state = SimpleNamespace(
temperature=temperature,
)
class FakeTionService:
def __init__(
self,
online: bool,
in_temp,
):
self.online = online
self.state = SimpleNamespace(
in_temp=in_temp,
)
def make_controller(
*,
qingping_online: bool,
qingping_temperature,
tion_online: bool,
tion_temperature,
):
qingping = FakeQingpingService(
online=qingping_online,
temperature=qingping_temperature,
)
tion = FakeTionService(
online=tion_online,
in_temp=tion_temperature,
)
return AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
)
def test_qingping_priority():
controller = make_controller(
qingping_online=True,
qingping_temperature=19.7,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 19.7
assert source == "qingping"
def test_tion_fallback():
controller = make_controller(
qingping_online=False,
qingping_temperature=19.7,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 18
assert source == "tion"
def test_tion_fallback_when_qingping_temperature_missing():
controller = make_controller(
qingping_online=True,
qingping_temperature=None,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 18
assert source == "tion"
def test_offline_tion_is_not_used():
controller = make_controller(
qingping_online=False,
qingping_temperature=None,
tion_online=False,
# Значение специально оставляем.
# Оно имитирует старый state Tion.
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature is None
assert source is None
def test_missing_tion_temperature():
controller = make_controller(
qingping_online=False,
qingping_temperature=None,
tion_online=True,
tion_temperature=None,
)
temperature, source = (
controller._get_temperature()
)
assert temperature is None
assert source is None
def main():
test_qingping_priority()
test_tion_fallback()
test_tion_fallback_when_qingping_temperature_missing()
test_offline_tion_is_not_used()
test_missing_tion_temperature()
print()
print("=" * 70)
print(
"ALL AUTO TEMPERATURE SOURCE "
"TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
main()
-248
View File
@@ -1,248 +0,0 @@
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
@@ -1,366 +0,0 @@
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())
@@ -1,279 +0,0 @@
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
@@ -1,107 +0,0 @@
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()
-326
View File
@@ -1,326 +0,0 @@
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())
-128
View File
@@ -1,128 +0,0 @@
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()
+18 -11
View File
@@ -134,7 +134,7 @@ def load_test_schedule():
return temp_dir, config return temp_dir, config
def heater_calls(calls): def temperature_calls(calls):
return [ return [
call call
for call in calls for call in calls
@@ -142,6 +142,7 @@ def heater_calls(calls):
"heater_on", "heater_on",
"heater_off", "heater_off",
"set_heater", "set_heater",
"set_target_temperature",
} }
] ]
@@ -178,7 +179,12 @@ async def test_auto_does_not_control_heater():
# 09:30 # 09:30
# #
# Обычный SET. # Обычный SET.
# heater=on должен принадлежать ScheduleService. #
# ScheduleService хранит желаемое heater=on,
# но физически heater управлять НЕ должен.
#
# Физический heater будет принадлежать
# единому температурному регулятору.
# -------------------------------------------------- # --------------------------------------------------
await process_at( await process_at(
@@ -198,12 +204,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = heater_calls( calls = temperature_calls(
tion.controller.calls tion.controller.calls
) )
assert calls != [], ( assert calls == [], (
"SET must control heater" "ScheduleService must not control "
"heater or target temperature during SET"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -263,13 +270,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = heater_calls( calls = temperature_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls == [], (
"ScheduleService must not control " "ScheduleService must not control "
"heater during AUTO" "heater or target temperature during AUTO"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -298,13 +305,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = heater_calls( calls = temperature_calls(
tion.controller.calls tion.controller.calls
) )
assert calls != [], ( assert calls == [], (
"ScheduleService must regain heater " "ScheduleService must not control "
"control after AUTO" "heater or target temperature after AUTO"
) )
finally: finally:
+384
View File
@@ -0,0 +1,384 @@
import asyncio
from types import SimpleNamespace
import app.api as api
class FakeTionState:
def __init__(self):
# Физическое состояние Tion.
#
# Специально ставим техническую уставку 30,
# чтобы проверить, что API её не покажет.
self.heater = False
self.heating = False
self.target_temp = 30
self.in_temp = 14
self.fan_speed = 2
def to_dict(self):
return {
"heater": self.heater,
"heating": self.heating,
"target_temp": self.target_temp,
"in_temp": self.in_temp,
"fan_speed": self.fan_speed,
}
class FakeTionService:
def __init__(self):
self.state = FakeTionState()
self.online = True
self.running = True
self.last_seen = None
self.last_error = None
self.execute_calls = []
async def execute(self, operation):
# При активном расписании температурные команды
# НЕ должны идти напрямую сюда.
self.execute_calls.append(operation)
class FakeSchedule:
def __init__(self):
self.running = True
self.paused = False
self.config = SimpleNamespace(
enabled=True,
)
self.override_active = False
self.override_settings = SimpleNamespace(
heater=None,
target_temp=None,
speed=None,
)
self.apply_override_calls = []
def resolve(self):
return SimpleNamespace(
enabled=True,
scheduled_settings=SimpleNamespace(
heater=True,
target_temp=24,
),
auto_active=False,
auto_target_temp=None,
)
async def apply_override(self, settings):
self.apply_override_calls.append(
settings
)
if settings.heater is not None:
self.override_settings.heater = (
settings.heater
)
if settings.target_temp is not None:
self.override_settings.target_temp = (
settings.target_temp
)
self.override_active = True
async def clear_override(self):
self.override_active = False
self.override_settings = SimpleNamespace(
heater=None,
target_temp=None,
speed=None,
)
async def pause(self):
self.paused = True
async def resume(self):
self.paused = False
class FakeAutoController:
def __init__(self, schedule):
self.schedule = schedule
self.manual_heater_enabled = None
self.manual_target_temperature = None
self.reconcile_calls = 0
def effective_temperature_config(self):
if self.schedule.paused:
return SimpleNamespace(
heater_enabled=(
self.manual_heater_enabled
),
target_temp=(
self.manual_target_temperature
),
)
heater = True
target = 24
if self.schedule.override_active:
override = (
self.schedule.override_settings
)
if override.heater is not None:
heater = override.heater
if override.target_temp is not None:
target = override.target_temp
return SimpleNamespace(
heater_enabled=heater,
target_temp=target,
)
def set_manual_heater_enabled(
self,
enabled,
):
self.manual_heater_enabled = enabled
def set_manual_target_temperature(
self,
temperature,
):
self.manual_target_temperature = (
temperature
)
def clear_manual_heater_control(self):
self.manual_heater_enabled = None
self.manual_target_temperature = None
async def reconcile_temperature(self):
self.reconcile_calls += 1
def status(self):
return {
"state": "test",
}
class FakeQingping:
def status(self):
return {
"online": True,
"temperature": 25.5,
}
def prepare():
schedule = FakeSchedule()
auto = FakeAutoController(schedule)
tion = FakeTionService()
api.schedule_service = schedule
api.auto_controller = auto
api.service = tion
api.qingping_service = FakeQingping()
# Чтобы тест не зависел от Elica.
api.get_elica_status = lambda: {
"online": True,
}
# Нам здесь не нужна внутренняя структура
# schedule-status.
api.get_schedule_status = lambda: {
"available": True,
"paused": schedule.paused,
}
return schedule, auto, tion
def test_status_uses_logical_temperature():
schedule, auto, tion = prepare()
status = api.get_status()
# Физически Tion:
assert tion.state.target_temp == 30
assert tion.state.heater is False
# Но пользователь должен видеть:
assert status["tion"]["target_temp"] == 24
assert status["tion"]["heater"] is True
# heating остаётся физическим.
assert status["tion"]["heating"] is False
async def test_temperature_creates_override():
schedule, auto, tion = prepare()
await api.set_temperature(26)
assert schedule.override_active is True
assert (
schedule.override_settings.target_temp
== 26
)
# Изменение только температуры
# не должно само задавать heater.
assert (
schedule.override_settings.heater
is None
)
# Tion напрямую не вызывается.
assert tion.execute_calls == []
# Новый температурный контур
# применяется сразу.
assert auto.reconcile_calls == 1
async def test_heater_creates_override():
schedule, auto, tion = prepare()
await api.set_heater("off")
assert schedule.override_active is True
assert (
schedule.override_settings.heater
is False
)
assert tion.execute_calls == []
assert auto.reconcile_calls == 1
async def test_pause_uses_logical_state():
schedule, auto, tion = prepare()
# Физический heater выключен.
assert tion.state.heater is False
# Но логически отопление разрешено:
config = (
auto.effective_temperature_config()
)
assert config.heater_enabled is True
assert config.target_temp == 24
await api.pause_schedule()
assert schedule.paused is True
# PAUSE должен запомнить ЛОГИЧЕСКОЕ
# состояние, а не физический heater=False.
assert (
auto.manual_heater_enabled
is True
)
assert (
auto.manual_target_temperature
== 24
)
assert auto.reconcile_calls == 1
async def test_resume_clears_manual_state():
schedule, auto, tion = prepare()
schedule.paused = True
auto.manual_heater_enabled = True
auto.manual_target_temperature = 25
await api.resume_schedule()
assert schedule.paused is False
assert (
auto.manual_heater_enabled
is None
)
assert (
auto.manual_target_temperature
is None
)
assert auto.reconcile_calls == 1
def test_temperature_routes():
paths = [
route.path
for route in api.app.routes
]
# increase мы решили удалить полностью.
assert (
"/api/tion/temperature/increase"
not in paths
)
# Основной endpoint должен существовать
# ровно один раз.
assert (
paths.count(
"/api/tion/temperature/{temperature}"
)
== 1
)
async def main():
test_status_uses_logical_temperature()
await test_temperature_creates_override()
await test_heater_creates_override()
await test_pause_uses_logical_state()
await test_resume_clears_manual_state()
test_temperature_routes()
print(
"ALL TEMPERATURE API TESTS PASSED"
)
if __name__ == "__main__":
asyncio.run(main())
+395
View File
@@ -0,0 +1,395 @@
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):
self.heater = None
self.target_temp = None
self.speed = None
def heater_on(self):
self.heater = True
def heater_off(self):
self.heater = False
def set_target_temperature(
self,
temperature,
):
self.target_temp = temperature
def set_speed(self, speed):
self.speed = speed
class FakeTion:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=14,
)
self.controller = (
FakeTionController()
)
async def execute(self, operation):
result = operation(
self.controller
)
if inspect.isawaitable(result):
await result
class FakeQingping:
def __init__(
self,
*,
online=True,
temperature=25,
):
self.online = online
self.state = SimpleNamespace(
temperature=temperature,
co2=None,
)
class FakeTemperaturePolicy:
def heater_required(
self,
temperature,
target_temp,
heater_on,
):
return temperature < target_temp
class FakeSchedule:
def __init__(
self,
*,
heater=True,
target_temp=24,
auto=False,
auto_target=None,
paused=False,
override=None,
):
self.paused = paused
self.override_active = (
override is not None
)
self.override_settings = (
override
or SimpleNamespace(
heater=None,
target_temp=None,
)
)
self.resolution = SimpleNamespace(
enabled=True,
scheduled_settings=(
SimpleNamespace(
heater=heater,
target_temp=target_temp,
)
),
auto_active=auto,
auto_target_temp=auto_target,
auto_fallback_speed=2,
)
def resolve(self, now=None):
return self.resolution
def make_controller(
schedule,
qingping,
):
tion = FakeTion()
controller = AutoController(
schedule_service=schedule,
qingping_service=qingping,
tion_service=tion,
temperature_policy=(
FakeTemperaturePolicy()
),
)
return controller, tion
async def test_set_online():
schedule = FakeSchedule(
heater=True,
target_temp=24,
)
qingping = FakeQingping(
online=True,
temperature=25.9,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is False
async def test_set_offline():
schedule = FakeSchedule(
heater=True,
target_temp=24,
)
qingping = FakeQingping(
online=False,
temperature=None,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == 24
assert tion.controller.heater is True
async def test_auto_online():
schedule = FakeSchedule(
heater=True,
target_temp=24,
auto=True,
auto_target=22,
)
qingping = FakeQingping(
online=True,
temperature=21,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is True
async def test_auto_offline():
schedule = FakeSchedule(
heater=True,
target_temp=24,
auto=True,
auto_target=22,
)
qingping = FakeQingping(
online=False,
temperature=None,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == 22
assert tion.controller.heater is True
async def test_override_temperature_only():
schedule = FakeSchedule(
heater=False,
target_temp=24,
override=SimpleNamespace(
heater=None,
target_temp=26,
),
)
qingping = FakeQingping(
online=True,
temperature=20,
)
controller, tion = make_controller(
schedule,
qingping,
)
config = (
controller
._get_effective_temperature_config(
schedule.resolve()
)
)
assert config.heater_enabled is False
assert config.target_temp == 26
await controller._process()
# Изменение только температуры
# НЕ включает heater.
assert tion.controller.heater is False
async def test_override_heater_only():
schedule = FakeSchedule(
heater=False,
target_temp=24,
override=SimpleNamespace(
heater=True,
target_temp=None,
),
)
qingping = FakeQingping(
online=True,
temperature=23,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is True
async def test_pause():
schedule = FakeSchedule(
paused=True,
)
qingping = FakeQingping(
online=True,
temperature=25,
)
controller, tion = make_controller(
schedule,
qingping,
)
controller.set_manual_heater_enabled(
True
)
controller.set_manual_target_temperature(
24
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is False
async def test_heater_false_priority():
schedule = FakeSchedule(
heater=False,
target_temp=30,
)
qingping = FakeQingping(
online=True,
temperature=10,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.heater is False
async def main():
await test_set_online()
await test_set_offline()
await test_auto_online()
await test_auto_offline()
await test_override_temperature_only()
await test_override_heater_only()
await test_pause()
await test_heater_false_priority()
print(
"ALL UNIFIED TEMPERATURE "
"TESTS PASSED"
)
if __name__ == "__main__":
asyncio.run(main())
+1 -1
View File
@@ -83,7 +83,7 @@ function render(status) {
airCard.style.setProperty("--air-color", airPalette.color); airCard.style.setProperty("--air-color", airPalette.color);
airCard.style.setProperty("--air-glow", airPalette.glow); airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`; $("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setText("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1)); setText("#room-temp", numberOrDash(sensor.temperature, 1));
setText("#humidity", numberOrDash(sensor.humidity)); setText("#humidity", numberOrDash(sensor.humidity));
setText("#current-time", schedule.current_time || tion.device_time || "—"); setText("#current-time", schedule.current_time || tion.device_time || "—");
setText("#next-time", schedule.next_time || "—"); setText("#next-time", schedule.next_time || "—");
+2 -2
View File
@@ -74,7 +74,7 @@ function renderAir(sensor, tion) {
airCard.style.setProperty("--air-glow", airPalette.glow); airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`; $("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad"); setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad");
text("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1)); text("#room-temp", numberOrDash(sensor.temperature, 1));
text("#humidity", numberOrDash(sensor.humidity)); text("#humidity", numberOrDash(sensor.humidity));
text("#pm25", numberOrDash(sensor.pm25)); text("#pm25", numberOrDash(sensor.pm25));
text("#pm10", numberOrDash(sensor.pm10)); text("#pm10", numberOrDash(sensor.pm10));
@@ -122,7 +122,7 @@ function render(status) {
$("#mode-outside").classList.toggle("active", tion.mode === "outside"); $("#mode-outside").classList.toggle("active", tion.mode === "outside");
$("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation"); $("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation");
text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция"); text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция");
text("#outside-temp", numberOrDash(tion.out_temp)); text("#outside-temp", numberOrDash(tion.in_temp));
text("#filter-remain", numberOrDash(tion.filter_remain)); text("#filter-remain", numberOrDash(tion.filter_remain));
const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2)); const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2));
$("#filter-progress").style.width = `${filterPercent}%`; $("#filter-progress").style.width = `${filterPercent}%`;
+1 -1
View File
@@ -158,6 +158,6 @@
</footer> </footer>
</form> </form>
</dialog> </dialog>
<script type="module" src="/ui/static/js/tion.js?v=20260927-1"></script> <script type="module" src="/ui/static/js/tion.js?v=2"></script>
</body> </body>
</html> </html>