37 Commits
Author SHA1 Message Date
Dmitriy 3298be6df7 work : изменил версию 2026-09-27 20:01:18 +03:00
Dmitriy f161d98746 work: добавил автоматику управления вытяжкой. Скорости сопоставляются в auto.yaml. Сейчас 4 тион 1 элика, 5 - 2; 6 -3. 2026-09-27 19:59:36 +03:00
Dmitriy e197e924ae Merge branch 'release' into dev_fedorov 2026-09-27 18:02:22 +03:00
Dmitriy 0c0f6c5d0f work: добавил защиту для случая если процесс bluetooth аварийно завершился, приложение считает его connected и не может подключиться 2026-09-27 17:13:08 +03:00
Dmitriy 81f946fc24 Merge branch 'release' into dev_fedorov 2026-09-27 17:09:22 +03:00
Dmitriy c61a6f8797 work : исправил включение бризера. Теперь отправляется power on и speed 2026-09-27 09:21:53 +03:00
Dmitriy 940f63ff94 Merge branch 'release' into dev_fedorov 2026-09-27 00:55:33 +03:00
Dmitriy 6a9613f40c work: исправил адрес сервера mqtt на miniPC 2026-09-27 00:54:32 +03:00
Dmitriy f06bafc72a Merge branch 'release' into dev_fedorov 2026-09-27 00:39:54 +03:00
Dmitriy cc339584a0 work: изменил patch 2026-09-27 00:38:55 +03:00
Dmitriy dfa3cafdf5 work: исправлены css главных панелей тиона и элики. 2026-09-27 00:38:05 +03:00
Dmitriy 536435aac2 Merge branch 'release' into dev_fedorov 2026-09-27 00:11:34 +03:00
Dmitriy 869c826774 work: добавил фалйы форм в отслеживание 2026-09-27 00:10:43 +03:00
Dmitriy c6607a75ab Merge branch 'release' into dev_fedorov 2026-09-27 00:00:46 +03:00
Dmitriy bf832ac86b work: функционал для работы с вятяжкой
* Добавил полный функционал управления elica через esp32 по MQTT
* Добавил в прошивку принудительную блокировку внешнего винтелятора при работающей вытяжке
* Добавил веб-панели для управления вытяжкой
2026-09-26 23:59:01 +03:00
Dmitriy 3b3c7a3f13 work: Добавил защиту от постоянного нажатия кнопки. В случае исключения всегда отправится команда на отжатие. Также добавил синхронизацию начального состояния вытяжки. 2026-09-22 23:07:40 +03:00
Dmitriy 75950a7eae work: Добавил высокоуровневый контроллер для работы с вытяжкой. 2026-09-22 22:45:33 +03:00
Dmitriy 4169b0c3e5 work: Низкий уровень работы с Элика завершен. Добавил логику для отслеживания состояния вытяжки. 2026-09-22 22:01:57 +03:00
Dmitriy 8ece9ba131 work: Добавил интерфейс для управления кнопками вытяжки. 2026-09-22 21:36:39 +03:00
Dmitriy f6e00842d8 work: Добавил функционал пульсирующего включения. Т.е. вкл\выкл. 2026-09-22 21:35:10 +03:00
Dmitriy 5e04013e2d work: Добавил функционал проверки состояний входов 2026-09-22 21:23:05 +03:00
Dmitriy 8d61712642 work: Изменил конфиг сервиса вытяжки для реальной платы. Добавил yaml конфигурацию платы. Сейчас доступны MQTT -прием статуса и управление реле. 2026-09-22 21:16:14 +03:00
Dmitriy 32f3fc754f work: добавил каркас под управление вытяжкой! 2026-09-20 18:24:17 +03:00
Dmitriy 9fd1b3976d Merge branch 'release' into dev_fedorov 2026-09-20 14:19:52 +03:00
Dmitriy 3754bbc380 work : добавил экспорт метрик для Prometheus 2026-09-20 14:18:40 +03:00
Dmitriy a000fb6c44 work : изменил расписание на реальное. 2026-09-20 13:42:34 +03:00
Dmitriy be4c2c403c work : переименовал проект 2026-09-20 12:55:06 +03:00
Fedorov Dmitriy e636bc53ca Merge branch 'release' into dev_fedorov 2026-09-20 11:29:58 +03:00
Fedorov Dmitriy fdb798a430 work : виджет стал более "горизонтальным" 2026-09-20 11:28:48 +03:00
Fedorov Dmitriy 33cdb205b3 Merge branch 'release' into dev_fedorov 2026-09-20 02:02:34 +03:00
Fedorov Dmitriy 8069ab65f2 work : добавил web в отслеживание 2026-09-20 02:01:44 +03:00
Fedorov Dmitriy 455d191ea1 Merge branch 'release' into dev_fedorov 2026-09-20 02:00:40 +03:00
Fedorov Dmitriy 0172b6bcf2 work: добавлин web интерфейс. 2026-09-20 01:59:36 +03:00
Fedorov Dmitriy 65cf547c6c Merge branch 'release' into dev_fedorov 2026-09-19 23:05:03 +03:00
Fedorov Dmitriy 741be479a6 work: исправил порядок объявления классов в app/auto/config TemperatureConfig объявлялся после AutoConfig в котором использовался. 2026-09-19 22:51:36 +03:00
Fedorov Dmitriy 958691a481 doc: поправил зависимости и расписание 2026-09-19 19:14:08 +03:00
Fedorov Dmitriy c22e8bc71d work: добавил режим ручного управления. Теперь можно отключать расписание! 2026-09-19 19:04:45 +03:00
41 changed files with 1071 additions and 1773 deletions
+3 -3
View File
@@ -1,8 +1,8 @@
[version] [version]
major = 1 major = 1
minor = 5 minor = 5
patch = 9 patch = 0
[build] [build]
date = "2026-09-29" date = "2026-09-27"
time = "23:38:58" time = "20:00:55"
+106 -264
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_components, load_auto_config,
) )
from app.auto.temperature_policy import TemperaturePolicy from app.auto.temperature_policy import TemperaturePolicy
@@ -138,118 +138,42 @@ async def lifespan(app: FastAPI):
schedule_load_error = None schedule_load_error = None
try: try:
auto_config = load_auto_config_components(AUTO_CONFIG_FILE) auto_config = load_auto_config(AUTO_CONFIG_FILE)
auto_interval = auto_config.check_interval elica_assist = ElicaAutoAssistState(auto_config.elica_assist)
auto_errors = dict(auto_config.errors) auto_policy = Co2SpeedPolicy(
base_speed=(
auto_config.co2.base_speed
),
thresholds=(
auto_config.co2.thresholds
),
hysteresis=(
auto_config.co2.hysteresis
),
)
# -------------------------------------------------- temperature_policy = TemperaturePolicy(auto_config.temperature)
# CO2 policy
# --------------------------------------------------
auto_policy = None
if auto_config.co2 is not None:
try: auto_interval = (auto_config.check_interval)
auto_policy = Co2SpeedPolicy(
base_speed=(
auto_config.co2.base_speed
),
thresholds=(
auto_config.co2.thresholds
),
hysteresis=(
auto_config.co2.hysteresis
),
)
except Exception as exc: auto_load_error = None
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)
except Exception as exc:
auto_errors[
"temperature_policy"
] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Elica Assist
# --------------------------------------------------
elica_assist = None
if (
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: except Exception as exc:
# Здесь остаются только ошибки,
# из-за которых невозможно разобрать
# auto.yaml вообще.
auto_policy = None auto_policy = None
temperature_policy = None temperature_policy = None
elica_assist = None elica_assist = None
# Безопасный встроенный интервал нужен,
# потому что auto.yaml сейчас недоступен.
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,
@@ -403,42 +327,6 @@ 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,
@@ -451,8 +339,11 @@ def get_status() -> dict:
"last_error": service.last_error, "last_error": service.last_error,
"tion": tion_status, "tion": (
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(),
@@ -505,16 +396,17 @@ def get_effective_speed() -> int:
def get_effective_temperature() -> int: def get_effective_temperature() -> int:
if auto_controller is not None: if (
schedule_service is not None
config = ( and schedule_service.override_active
auto_controller and schedule_service.override_settings.target_temp is not None
.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:
@@ -565,60 +457,6 @@ 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:
@@ -766,6 +604,7 @@ 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()
@@ -774,6 +613,7 @@ 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()
@@ -822,6 +662,7 @@ 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"]):
@@ -841,6 +682,7 @@ 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():
@@ -902,57 +744,96 @@ async def set_speed(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Heater # Heater
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/heater/{state}") @app.post("/api/tion/heater/{state}")
async def set_heater( async def set_heater(state: Literal["on", "off"]):
state: Literal["on", "off"],
):
enabled = state == "on" enabled = state == "on"
operation = ( if enabled:
(lambda tion: tion.heater_on()) operation = lambda tion: tion.heater_on()
if enabled else:
else operation = lambda tion: tion.heater_off()
(lambda tion: tion.heater_off())
return await execute_command(
operation,
ScheduledSettings(heater=enabled),
) )
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()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings( ScheduledSettings(
heater=enabled, target_temp=new_temperature,
), ),
) )
@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,
Path( Path(
ge=MIN_TARGET_TEMP, ge=MIN_TARGET_TEMP,
le=MAX_TARGET_TEMP, le=MAX_TARGET_TEMP,
), ),
], ],):
):
return await execute_temperature_command( return await execute_command(
lambda tion: lambda tion:
tion.set_target_temperature( tion.set_target_temperature(temperature),
temperature ScheduledSettings(target_temp=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,
@@ -984,6 +865,7 @@ 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"],
@@ -1006,6 +888,7 @@ 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"],
@@ -1027,6 +910,7 @@ 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:
@@ -1116,9 +1000,6 @@ 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(),
@@ -1137,42 +1018,8 @@ 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(),
@@ -1192,11 +1039,6 @@ 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,9 +1,7 @@
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 (
@@ -21,6 +19,4 @@ __all__ = [
"load_auto_config", "load_auto_config",
"Co2SpeedPolicy", "Co2SpeedPolicy",
"AutoController", "AutoController",
"AutoConfigComponents",
"load_auto_config_components",
] ]
+114 -212
View File
@@ -57,20 +57,6 @@ 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):
@@ -276,32 +262,111 @@ 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(
"temperature", "AUTO config",
value, raw,
) )
unknown = ( unknown = set(data) - {
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"
)
# --------------------------------------------------
# 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: if unknown_temperature:
raise ValueError( raise ValueError(
f"Unknown temperature config fields: " f"Unknown temperature config fields: "
f"{sorted(unknown)}" f"{sorted(unknown_temperature)}"
) )
hysteresis = data.get( temperature_hysteresis = (
"hysteresis" temperature_data.get(
"hysteresis"
)
) )
if ( if (
type(hysteresis) type(temperature_hysteresis)
not in { not in {
int, int,
float, float,
@@ -312,40 +377,45 @@ def _parse_temperature(value: Any) -> TemperatureConfig:
"must be a number" "must be a number"
) )
hysteresis = float(hysteresis) temperature_hysteresis = float(
temperature_hysteresis
)
if hysteresis < 0: if temperature_hysteresis < 0:
raise ValueError( raise ValueError(
"temperature.hysteresis " "temperature.hysteresis "
"must be >= 0" "must be >= 0"
) )
return TemperatureConfig( temperature = TemperatureConfig(
hysteresis=hysteresis, hysteresis=temperature_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",
value, data["elica_assist"],
) )
unknown = ( unknown_elica = (
set(data) set(elica_data)
- { - {
"enabled", "enabled",
"speed_map", "speed_map",
} }
) )
if unknown: if unknown_elica:
raise ValueError( raise ValueError(f"Unknown elica_assist config fields: {sorted(unknown_elica)}")
"Unknown elica_assist config fields: "
f"{sorted(unknown)}"
)
enabled = data.get("enabled") enabled = elica_data.get("enabled")
if type(enabled) is not bool: if type(enabled) is not bool:
raise ValueError( raise ValueError(
@@ -353,25 +423,19 @@ def _parse_elica_assist(value: Any) -> ElicaAssistConfig:
"must be a boolean" "must be a boolean"
) )
speed_map_data = data.get( speed_map_data = elica_data.get("speed_map")
"speed_map"
)
if not isinstance( if not isinstance(
speed_map_data, speed_map_data,
dict, dict,
): ):
raise ValueError( raise ValueError("elica_assist.speed_map must be an object")
"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 "
@@ -414,183 +478,21 @@ def _parse_elica_assist(value: Any) -> ElicaAssistConfig:
speed_map.sort() speed_map.sort()
return ElicaAssistConfig( elica_assist = 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)
# -------------------------------------------------- # --------------------------------------------------
# CO2 # Result
# -------------------------------------------------- # --------------------------------------------------
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=check_interval, check_interval=float(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,
)
+193 -355
View File
@@ -1,5 +1,4 @@
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
@@ -9,12 +8,6 @@ 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__(
@@ -53,25 +46,6 @@ 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
@@ -115,45 +89,19 @@ 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 # AUTO вообще не имеет права управлять Tion.
# 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,
@@ -163,54 +111,58 @@ 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._temperature_heating self._target_temperature = None
)
self._temperature = None
self._temperature_source = None
self._last_error = None self._last_error = None
await self._release_elica_assist() self._release_elica_assist()
return return
# В режимах расписания результат относится # ----------------------------------------------
# к общему температурному контуру. # Активен ручной override.
self._manual_heating = None
self._auto_heater = (
self._temperature_heating
)
# --------------------------------------------------
# Temporary override.
# #
# Температура уже обработана выше. # Пока пользователь вручную управляет Tion,
# AUTO скоростью во время override # AUTO вообще не вмешивается.
# по-прежнему не управляет. # ----------------------------------------------
# --------------------------------------------------
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
await self._release_elica_assist() self._release_elica_assist()
return return
# -------------------------------------------------- # ----------------------------------------------
# Не AUTO. # AUTO сейчас не активен
# # ----------------------------------------------
# Температура уже обработана выше.
# Здесь просто нечего делать с AUTO-скоростью.
# --------------------------------------------------
if ( if (
not resolution.enabled not resolution.enabled
@@ -218,44 +170,49 @@ 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
await self._release_elica_assist() 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 = ( self._reason = "auto_policy_unavailable"
"auto_policy_unavailable"
)
self._auto_speed = None self._auto_speed = None
await self._set_speed( await self._set_speed(fallback_speed)
fallback_speed
)
await self._update_elica_assist( await self._update_elica_assist(fallback_speed)
fallback_speed
) if self._temperature_policy is not None:
await self._process_heater(resolution)
self._last_error = None self._last_error = None
@@ -263,7 +220,10 @@ 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
@@ -278,23 +238,27 @@ class AutoController:
self._state = "active" self._state = "active"
self._reason = None self._reason = None
await self._set_speed( await self._set_speed(target_speed)
target_speed
)
await self._update_elica_assist( await self._update_elica_assist(target_speed)
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"
@@ -303,221 +267,156 @@ class AutoController:
self._auto_speed = None self._auto_speed = None
await self._set_speed( await self._set_speed(fallback_speed)
fallback_speed
)
await self._update_elica_assist( self._update_elica_assist(fallback_speed)
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(
self, async def _process_heater(self, resolution) -> None:
resolution,
) -> EffectiveTemperatureConfig:
# -------------------------------------------------- # --------------------------------------------------
# PAUSE. # Берём целевую температуру из накопленных
# настроек расписания.
# #
# Источник настроек — ручное состояние. # Например:
# --------------------------------------------------
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 может иметь собственную температуру.
# #
# Если её нет — остаётся температура # SET target_temp=20
# накопленного SET. # AUTO
# --------------------------------------------------
if (
resolution.auto_active
and resolution.auto_target_temp
is not None
):
target_temp = (
resolution.auto_target_temp
)
# --------------------------------------------------
# Temporary override — это НАЛОЖЕНИЕ
# поверх текущей конфигурации.
# #
# target_temp не включает heater автоматически. # Во время AUTO target_temp остаётся 20.
# -------------------------------------------------- # --------------------------------------------------
if self._schedule.override_active: target_temp = resolution.auto_target_temp
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 имеет абсолютный приоритет. # Получаем фактическую температуру.
#
# _get_temperature() сам выбирает:
#
# 1. Qingping
# 2. Tion как резерв
# 3. None, если оба источника недоступны
# -------------------------------------------------- # --------------------------------------------------
if enabled is False: 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) 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, ни резервный датчик 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
def _get_temperature(self) -> tuple[float | int | None, str | None]:
# --------------------------------------------------
# Основной источник — Qingping.
#
# Используем температуру Qingping только если
# сам поток данных датчика сейчас считается online.
# --------------------------------------------------
qingping_state = self._qingping.state qingping_state = self._qingping.state
qingping_temperature = getattr(
qingping_state,
"temperature",
None,
)
# --------------------------------------------------
# Qingping доступен и TemperaturePolicy работает.
#
# Решение принимаем ТОЛЬКО по Qingping.
# --------------------------------------------------
if ( if (
self._qingping.online self._qingping.online
and qingping_temperature is not None and qingping_state.temperature is not None
and self._temperature_policy is not None
): ):
self._temperature = ( return (
qingping_temperature qingping_state.temperature,
"qingping",
) )
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 недоступен либо отсутствует # Qingping недоступен или температура отсутствует.
# TemperaturePolicy.
# #
# Никаких решений по Tion.in_temp! # Пробуем резервный датчик температуры Tion.
# #
# Возвращаем управление штатному # Важно проверять tion.online:
# термостату Tion. # TionService может хранить последнее состояние,
# даже если связь с устройством уже потеряна.
# -------------------------------------------------- # --------------------------------------------------
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 (
@@ -525,19 +424,16 @@ 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
): ):
self._temperature = ( return (
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,
@@ -891,58 +787,6 @@ 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 {
@@ -964,12 +808,6 @@ 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,6 +36,7 @@ templates:
weekend: weekend:
- time: "10:00" - time: "10:00"
action: action:
power: on power: on
@@ -61,12 +62,16 @@ 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,9 +561,15 @@ 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)
@@ -592,6 +598,24 @@ 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
@@ -1,134 +0,0 @@
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
@@ -0,0 +1,304 @@
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())
@@ -0,0 +1,138 @@
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
@@ -0,0 +1,169 @@
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()
+11 -18
View File
@@ -134,7 +134,7 @@ def load_test_schedule():
return temp_dir, config return temp_dir, config
def temperature_calls(calls): def heater_calls(calls):
return [ return [
call call
for call in calls for call in calls
@@ -142,7 +142,6 @@ def temperature_calls(calls):
"heater_on", "heater_on",
"heater_off", "heater_off",
"set_heater", "set_heater",
"set_target_temperature",
} }
] ]
@@ -179,12 +178,7 @@ 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(
@@ -204,13 +198,12 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = temperature_calls( calls = heater_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls != [], (
"ScheduleService must not control " "SET must control heater"
"heater or target temperature during SET"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -270,13 +263,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = temperature_calls( calls = heater_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls == [], (
"ScheduleService must not control " "ScheduleService must not control "
"heater or target temperature during AUTO" "heater during AUTO"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -305,13 +298,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = temperature_calls( calls = heater_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls != [], (
"ScheduleService must not control " "ScheduleService must regain heater "
"heater or target temperature after AUTO" "control after AUTO"
) )
finally: finally:
-384
View File
@@ -1,384 +0,0 @@
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
@@ -1,395 +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):
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, 1)); setText("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 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, 1)); text("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 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.in_temp)); text("#outside-temp", numberOrDash(tion.out_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=2"></script> <script type="module" src="/ui/static/js/tion.js?v=20260927-1"></script>
</body> </body>
</html> </html>