Author SHA1 Message Date
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
Dmitriy 0eae8b76a0 Merge branch 'release' into dev_fedorov 2026-09-27 22:10:56 +03:00
Dmitriy bc7b85df60 fix: v1.5.5 поправил баг, когда при режиме авто меняешь температуру, управление шло по джатчикам тион. теперь по quingping 2026-09-27 22:10:46 +03:00
Dmitriy d23ad89d67 work: поправил баг, когда при режиме авто меняешь температуру, управление шло по джатчикам тион. теперь по quingping 2026-09-27 22:10:06 +03:00
Dmitriy dc1481bc0d Merge branch 'release' into dev_fedorov 2026-09-27 21:57:20 +03:00
Dmitriy d21836bf76 fix: v1.5.4 поправил автоматический сброс температуры если руками изменить в режиме авто 2026-09-27 21:57:09 +03:00
Dmitriy 28ae6542fb work: поправил автоматический сброс температуры если руками изменить в режиме авто 2026-09-27 21:56:19 +03:00
Dmitriy 521e01bc92 Merge branch 'release' into dev_fedorov 2026-09-27 21:44:55 +03:00
Dmitriy 8f7564a55d fix: v1.5.3 в режиме авто теперь отображается реально заданная желаемая температура. Раньше отображалась 30 град т.к. включением нагрева управляет логика а не тион 2026-09-27 21:44:22 +03:00
Dmitriy 9a2fd3b959 work: в режиме авто теперь отображается реально заданная желаемая температура. Раньше отображалась 30 град т.к. включением нагрева управляет логика а не тион 2026-09-27 21:38:39 +03:00
Dmitriy f46ad0861d Merge branch 'release' into dev_fedorov 2026-09-27 21:28:44 +03:00
Dmitriy 328182e1b4 fix: v1.5.2 изменил логику нагрева, теперь нагрев включается по датчику qingping а не тион. Если он недоступен то по тиону. 2026-09-27 21:28:31 +03:00
Dmitriy b2030187c1 work: изменил логику нагрева, теперь нагрев включается по датчику qingping а не тион. Если он недоступен то по тиону. 2026-09-27 21:27:49 +03:00
Dmitriy 0fc519be14 Merge branch 'release' into dev_fedorov
# Conflicts:
#	Version.toml
#	app/auto/controller.py
2026-09-27 20:31:53 +03:00
Dmitriy cea2637ec8 fix: v1.5.1 добавил await в вызов await self._update_elica_assist(fallback_speed) 2026-09-27 20:06:36 +03:00
Dmitriy cb6ed3328d work: v1.5.0 добавил автоматику управления вытяжкой. Скорости сопоставляются в auto.yaml. Сейчас 4 тион 1 элика, 5 - 2; 6 -3. 2026-09-27 20:01:55 +03:00
41 changed files with 1770 additions and 1068 deletions
+3 -3
View File
@@ -1,8 +1,8 @@
[version] [version]
major = 1 major = 1
minor = 5 minor = 5
patch = 0 patch = 9
[build] [build]
date = "2026-09-27" date = "2026-09-29"
time = "20:00:55" time = "23:02:17"
+250 -92
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,
@@ -327,6 +403,42 @@ def get_status() -> dict:
state = service.state state = service.state
tion_status = (
state.to_dict()
if state is not None
else None
)
# --------------------------------------------------
# В ручном режиме UI должен видеть желание
# пользователя, а не техническое состояние
# внешнего регулятора.
# --------------------------------------------------
if (
tion_status is not None
and auto_controller is not None
):
temperature_config = (auto_controller.effective_temperature_config())
if (
temperature_config.heater_enabled
is not None
):
tion_status["heater"] = (
temperature_config.heater_enabled
)
if (
temperature_config.target_temp
is not None
):
tion_status["target_temp"] = (
temperature_config.target_temp
)
return { return {
"online": service.online, "online": service.online,
"running": service.running, "running": service.running,
@@ -339,11 +451,8 @@ def get_status() -> dict:
"last_error": service.last_error, "last_error": service.last_error,
"tion": ( "tion": tion_status,
state.to_dict()
if state is not None
else None
),
"auto": get_auto_status(), "auto": get_auto_status(),
"qingping": qingping_service.status(), "qingping": qingping_service.status(),
@@ -396,17 +505,16 @@ 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.override_active config = (
and schedule_service.override_settings.target_temp is not None auto_controller
): .effective_temperature_config()
return (
schedule_service
.override_settings
.target_temp
) )
if config.target_temp is not None:
return config.target_temp
state = service.state state = service.state
if state is None: if state is None:
@@ -457,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:
@@ -604,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()
@@ -613,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()
@@ -662,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"]):
@@ -682,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():
@@ -744,76 +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())
)
return await execute_temperature_command(
return await execute_command(
operation, operation,
ScheduledSettings(heater=enabled),
)
# ----------------------------------------------------------------------
# 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()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings( ScheduledSettings(
target_temp=new_temperature, heater=enabled,
), ),
) )
@app.post("/api/tion/temperature/decrease")
async def decrease_temperature():
current_temperature = get_effective_temperature()
new_temperature = max(current_temperature - 1, MIN_TARGET_TEMP)
if new_temperature == current_temperature:
return get_status()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings(
target_temp=new_temperature,
),
)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# 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,
@@ -821,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,
@@ -865,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"],
@@ -888,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"],
@@ -910,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:
@@ -1000,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(),
@@ -1018,8 +1137,42 @@ async def pause_schedule():
detail="Schedule service unavailable", detail="Schedule service unavailable",
) )
# ВАЖНО:
# получаем логические настройки ДО pause(),
# потому что там ещё действует SET/AUTO/override.
temperature_config = None
if auto_controller is not None:
temperature_config = (
auto_controller
.effective_temperature_config()
)
await schedule_service.pause() await schedule_service.pause()
if (
auto_controller is not None
and temperature_config is not None
):
if (
temperature_config.heater_enabled
is not None
):
auto_controller.set_manual_heater_enabled(
temperature_config.heater_enabled
)
if (
temperature_config.target_temp
is not None
):
auto_controller.set_manual_target_temperature(
temperature_config.target_temp
)
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -1039,6 +1192,11 @@ async def resume_schedule():
await schedule_service.resume() await schedule_service.resume()
if auto_controller is not None:
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,
)
+338 -176
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,25 @@ 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
# --------------------------------------------------
# Ручное управление обогревом.
#
# Эти значения описывают желание пользователя,
# а не текущее физическое состояние Tion.
# --------------------------------------------------
self._manual_heater_enabled: bool | None = None
self._manual_target_temperature: int | None = None
# Фактическое решение нашего внешнего
# температурного регулятора.
self._manual_heating: bool | None = None
self._last_error: str | None = None self._last_error: str | None = None
@@ -89,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,
@@ -111,58 +163,54 @@ 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._target_heater = None
self._auto_heater = None self._auto_heater = None
self._manual_heating = (
self._target_temperature = None self._temperature_heating
)
self._temperature = None
self._temperature_source = None
self._last_error = None self._last_error = None
self._release_elica_assist() await self._release_elica_assist()
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 больше не может считать,
# что знает реальное состояние 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
self._release_elica_assist() await self._release_elica_assist()
return return
# ---------------------------------------------- # --------------------------------------------------
# AUTO сейчас не активен # Не AUTO.
# ---------------------------------------------- #
# Температура уже обработана выше.
# Здесь просто нечего делать с AUTO-скоростью.
# --------------------------------------------------
if ( if (
not resolution.enabled not resolution.enabled
@@ -170,49 +218,44 @@ class AutoController:
): ):
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
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
@@ -220,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
@@ -238,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"
@@ -267,156 +303,221 @@ class AutoController:
self._auto_speed = None self._auto_speed = None
await self._set_speed(fallback_speed) await self._set_speed(
fallback_speed
)
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: self,
resolution,
) -> EffectiveTemperatureConfig:
# -------------------------------------------------- # --------------------------------------------------
# Берём целевую температуру из накопленных # PAUSE.
# настроек расписания.
# #
# Например: # Источник настроек — ручное состояние.
#
# SET target_temp=20
# AUTO
#
# Во время AUTO target_temp остаётся 20.
# -------------------------------------------------- # --------------------------------------------------
target_temp = resolution.auto_target_temp if getattr(
self._schedule,
"paused",
False,
):
return EffectiveTemperatureConfig(
heater_enabled=(
self._manual_heater_enabled
),
target_temp=(
self._manual_target_temperature
),
)
# -------------------------------------------------- # --------------------------------------------------
# Получаем фактическую температуру. # Базовая конфигурация всегда приходит
# из накопленных SET-настроек.
# --------------------------------------------------
heater_enabled = (
resolution
.scheduled_settings
.heater
)
target_temp = (
resolution
.scheduled_settings
.target_temp
)
# --------------------------------------------------
# AUTO может иметь собственную температуру.
# #
# _get_temperature() сам выбирает: # Если её нет — остаётся температура
# накопленного SET.
# --------------------------------------------------
if (
resolution.auto_active
and resolution.auto_target_temp
is not None
):
target_temp = (
resolution.auto_target_temp
)
# --------------------------------------------------
# Temporary override — это НАЛОЖЕНИЕ
# поверх текущей конфигурации.
# #
# 1. Qingping # target_temp не включает heater автоматически.
# 2. Tion как резерв
# 3. None, если оба источника недоступны
# -------------------------------------------------- # --------------------------------------------------
temperature, source = self._get_temperature() if self._schedule.override_active:
self._temperature = temperature override = (
self._temperature_source = source 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
# -------------------------------------------------- # --------------------------------------------------
# Нет температурной policy. # heater=false имеет абсолютный приоритет.
#
# AUTO не умеет безопасно принять решение
# о нагреве → выключаем heater.
# -------------------------------------------------- # --------------------------------------------------
if self._temperature_policy is None: if enabled is False:
await self._set_heater(False) await self._set_heater(False)
self._auto_heater = False
self._temperature_heating = False
return return
# -------------------------------------------------- # --------------------------------------------------
# Нет целевой температуры. # Heater вообще не определён.
# #
# Непонятно, до какой температуры греть. # Ничего физически не меняем.
# Поэтому heater OFF. # --------------------------------------------------
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._auto_heater = False
self._temperature_heating = False
return return
# -------------------------------------------------- qingping_state = self._qingping.state
# Нет достоверной фактической температуры.
#
# Ни Qingping, ни резервный датчик Tion
# использовать нельзя.
#
# Heater OFF.
# --------------------------------------------------
if temperature is None: qingping_temperature = getattr(
await self._set_heater(False) qingping_state,
self._auto_heater = False "temperature",
return None,
)
# -------------------------------------------------- # --------------------------------------------------
# Есть всё необходимое: # Qingping доступен и TemperaturePolicy работает.
# #
# - фактическая температура; # Решение принимаем ТОЛЬКО по Qingping.
# - target_temp;
# - TemperaturePolicy.
#
# Policy решает, нужно ли сейчас греть.
# -------------------------------------------------- # --------------------------------------------------
if (
self._qingping.online
and qingping_temperature is not None
and self._temperature_policy is not None
):
self._temperature = (
qingping_temperature
)
self._temperature_source = (
"qingping"
)
heater_required = ( heater_required = (
self._temperature_policy self._temperature_policy
.heater_required( .heater_required(
temperature=temperature, temperature=(
qingping_temperature
),
target_temp=target_temp, target_temp=target_temp,
heater_on=( heater_on=(
self._auto_heater self._temperature_heating
is True is True
), ),
) )
) )
if heater_required: # Встроенный термостат Tion
# Наш внешний регулятор решил, что нужно греть. # не должен мешать внешнему регулятору.
# await self._set_target_temperature(
# Сначала поднимаем внутреннюю уставку Tion MAX_TARGET_TEMP
# до максимума, чтобы встроенный термостат
# не заблокировал нагрев по своему 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
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",
) )
await self._set_heater(
heater_required
)
self._temperature_heating = (
heater_required
)
return
# -------------------------------------------------- # --------------------------------------------------
# Qingping недоступен или температура отсутствует. # Qingping недоступен либо отсутствует
# TemperaturePolicy.
# #
# Пробуем резервный датчик температуры Tion. # Никаких решений по Tion.in_temp!
# #
# Важно проверять tion.online: # Возвращаем управление штатному
# TionService может хранить последнее состояние, # термостату Tion.
# даже если связь с устройством уже потеряна.
# -------------------------------------------------- # --------------------------------------------------
await self._set_target_temperature(
target_temp
)
await self._set_heater(True)
self._temperature_heating = None
# Tion.in_temp здесь только для диагностики.
tion_state = self._tion.state tion_state = self._tion.state
if ( if (
@@ -424,16 +525,19 @@ class AutoController:
and tion_state is not None and tion_state is not None
and tion_state.in_temp is not None and tion_state.in_temp is not None
): ):
return ( self._temperature = (
tion_state.in_temp, tion_state.in_temp
"tion",
) )
# -------------------------------------------------- self._temperature_source = "tion"
# Достоверной температуры нет вообще.
# -------------------------------------------------- else:
self._temperature = None
self._temperature_source = None
return None, None
async def _update_elica_assist( async def _update_elica_assist(
self, self,
@@ -787,6 +891,58 @@ class AutoController:
self._target_temperature = temperature self._target_temperature = temperature
def set_manual_heater_enabled(self, enabled: bool) -> None:
"""
Запоминает, хочет ли пользователь использовать
обогрев в ручном режиме.
Саму команду Tion этот метод пока не отправляет.
"""
self._manual_heater_enabled = enabled
self._target_heater = None
if not enabled:
self._manual_heating = False
def set_manual_target_temperature(self, temperature: int) -> None:
"""
Запоминает желаемую температуру помещения
для ручного режима.
"""
self._manual_target_temperature = temperature
self._target_temperature = None
def clear_manual_heater_control(self) -> None:
"""
Забываем состояние ручного температурного
регулятора при возврате к расписанию.
"""
self._manual_heater_enabled = None
self._manual_target_temperature = None
self._manual_heating = None
@property
def manual_heater_enabled(self) -> bool | None:
return self._manual_heater_enabled
@property
def manual_target_temperature(self) -> int | None:
return self._manual_target_temperature
def 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 {
@@ -808,6 +964,12 @@ class AutoController:
else None else None
), ),
"manual_heater": {
"enabled": self._manual_heater_enabled,
"target_temp": self._manual_target_temperature,
"heating": self._manual_heating,
},
"last_error": self._last_error, "last_error": self._last_error,
} }
@@ -36,7 +36,6 @@ templates:
weekend: weekend:
- time: "10:00" - time: "10:00"
action: action:
power: on power: on
@@ -62,16 +61,12 @@ templates:
speed: 1 speed: 1
days: days:
mon: workday mon: workday
tue: workday tue: workday
wed: workday wed: workday
thu: workday thu: workday
fri: workday fri: workday
sat: weekend sat: weekend
sun: weekend sun: weekend
-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()
+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>