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
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 2846fb0fbb fix: v1.4.3 добавил защиту для случая если процесс bluetooth аварийно завершился, приложение считает его connected и не может подключиться 2026-09-27 17:13:42 +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 41a4d6cd1b fix : v1.4.22 исправил включение бризера. Теперь отправляется power on и speed 2026-09-27 09:22:31 +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 cb9d0338a7 fix: 1.4.1 исправил адрес сервера mqtt на miniPC 2026-09-27 00:55:11 +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 7da45b7fef fix: v1.4.1 исправлены css главных панелей тиона и элики. 2026-09-27 00:39:45 +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 9fe85c3683 fix: 1.4.0 добавил фалйы форм в отслеживание 2026-09-27 00:11:18 +03:00
Dmitriy 869c826774 work: добавил фалйы форм в отслеживание 2026-09-27 00:10:43 +03:00
58 changed files with 7517 additions and 1072 deletions
+4 -4
View File
@@ -1,8 +1,8 @@
[version]
major = 1
minor = 4
patch = 0
minor = 5
patch = 9
[build]
date = "2026-09-26"
time = "23:54:18"
date = "2026-09-29"
time = "23:02:17"
+288 -119
View File
@@ -11,6 +11,7 @@ from pathlib import Path as FilePath
from app.qingping.service import QingpingService
from app.metrics import PrometheusMetricsService
from app.elica import ElicaConfig, ElicaController, ElicaService
from app.auto.elica_assist import ElicaAutoAssistState
from app.my_dataclasses import (
TION_MAC,
@@ -32,7 +33,7 @@ from app.my_dataclasses import (
from app.auto import (
AutoController,
Co2SpeedPolicy,
load_auto_config,
load_auto_config_components,
)
from app.auto.temperature_policy import TemperaturePolicy
@@ -137,44 +138,126 @@ async def lifespan(app: FastAPI):
schedule_load_error = None
try:
auto_config = load_auto_config(AUTO_CONFIG_FILE)
auto_config = load_auto_config_components(AUTO_CONFIG_FILE)
auto_policy = Co2SpeedPolicy(
base_speed=(
auto_config.co2.base_speed
),
thresholds=(
auto_config.co2.thresholds
),
hysteresis=(
auto_config.co2.hysteresis
),
)
auto_interval = auto_config.check_interval
temperature_policy = TemperaturePolicy(auto_config.temperature)
auto_errors = dict(auto_config.errors)
auto_interval = (auto_config.check_interval)
auto_load_error = None
except Exception as exc:
# --------------------------------------------------
# CO2 policy
# --------------------------------------------------
auto_policy = None
if auto_config.co2 is not None:
try:
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_errors["co2_policy"] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Temperature policy
# --------------------------------------------------
temperature_policy = None
# Безопасный встроенный интервал нужен,
# потому что auto.yaml сейчас недоступен.
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:
# Здесь остаются только ошибки,
# из-за которых невозможно разобрать
# auto.yaml вообще.
auto_policy = None
temperature_policy = None
elica_assist = None
auto_interval = 5.0
auto_load_error = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# AutoController создаётся даже если, например,
# CO2 policy не загрузилась.
#
# policy=None даст fallback скорости,
# но TemperaturePolicy при этом может работать.
# --------------------------------------------------
auto_controller = AutoController(
schedule_service=schedule_service,
qingping_service=qingping_service,
tion_service=service,
elica_controller=elica_controller,
policy=auto_policy,
temperature_policy=temperature_policy,
elica_assist=elica_assist,
interval=auto_interval,
)
@@ -250,43 +333,47 @@ async def ui_root():
# controllers/widgets without overloading generic "panel"/"widget" names.
@app.get("/ui/tion", include_in_schema=False)
async def ui_tion():
return FileResponse(WEB_ROOT / "tion.html")
return FileResponse(WEB_ROOT / "tion.html", headers={"Cache-Control": "no-store"})
@app.get("/ui/tion-widget", include_in_schema=False)
async def ui_tion_widget():
return FileResponse(WEB_ROOT / "tion-widget.html")
return FileResponse(WEB_ROOT / "tion-widget.html", headers={"Cache-Control": "no-store"})
@app.get("/ui/elica", include_in_schema=False)
async def ui_elica():
return FileResponse(WEB_ROOT / "elica.html")
return FileResponse(WEB_ROOT / "elica.html", headers={"Cache-Control": "no-store"})
@app.get("/ui/elica-widget", include_in_schema=False)
async def ui_elica_widget():
return FileResponse(WEB_ROOT / "elica-widget.html")
return FileResponse(WEB_ROOT / "elica-widget.html", headers={"Cache-Control": "no-store"})
# Backward-compatible aliases for existing bookmarks/Homarr embeds.
@app.get("/ui/panel", include_in_schema=False)
async def ui_panel_legacy():
return RedirectResponse(url="/ui/tion")
async def ui_panel_legacy(request: Request):
suffix = f"?{request.url.query}" if request.url.query else ""
return RedirectResponse(url=f"/ui/tion{suffix}")
@app.get("/ui/widget", include_in_schema=False)
async def ui_widget_legacy():
return RedirectResponse(url="/ui/tion-widget")
async def ui_widget_legacy(request: Request):
suffix = f"?{request.url.query}" if request.url.query else ""
return RedirectResponse(url=f"/ui/tion-widget{suffix}")
@app.get("/ui/exhaust", include_in_schema=False)
async def ui_exhaust_legacy():
return RedirectResponse(url="/ui/elica")
async def ui_exhaust_legacy(request: Request):
suffix = f"?{request.url.query}" if request.url.query else ""
return RedirectResponse(url=f"/ui/elica{suffix}")
@app.get("/ui/exhaust-widget", include_in_schema=False)
async def ui_exhaust_widget_legacy():
return RedirectResponse(url="/ui/elica-widget")
async def ui_exhaust_widget_legacy(request: Request):
suffix = f"?{request.url.query}" if request.url.query else ""
return RedirectResponse(url=f"/ui/elica-widget{suffix}")
@app.exception_handler(RequestValidationError)
@@ -316,6 +403,42 @@ def get_status() -> dict:
state = service.state
tion_status = (
state.to_dict()
if state is not None
else None
)
# --------------------------------------------------
# В ручном режиме UI должен видеть желание
# пользователя, а не техническое состояние
# внешнего регулятора.
# --------------------------------------------------
if (
tion_status is not None
and 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 {
"online": service.online,
"running": service.running,
@@ -328,11 +451,8 @@ def get_status() -> dict:
"last_error": service.last_error,
"tion": (
state.to_dict()
if state is not None
else None
),
"tion": tion_status,
"auto": get_auto_status(),
"qingping": qingping_service.status(),
@@ -385,17 +505,16 @@ def get_effective_speed() -> int:
def get_effective_temperature() -> int:
if (
schedule_service is not None
and schedule_service.override_active
and schedule_service.override_settings.target_temp is not None
):
return (
schedule_service
.override_settings
.target_temp
if auto_controller is not None:
config = (
auto_controller
.effective_temperature_config()
)
if config.target_temp is not None:
return config.target_temp
state = service.state
if state is None:
@@ -446,6 +565,60 @@ async def execute_command(operation, override: ScheduledSettings | None = None):
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:
@@ -593,7 +766,6 @@ def get_auto_status() -> dict:
# ----------------------------------------------------------------------
# Status
# ----------------------------------------------------------------------
@app.get("/api/status")
async def status():
return get_status()
@@ -602,7 +774,6 @@ async def status():
# ----------------------------------------------------------------------
# Elica / exhaust
# ----------------------------------------------------------------------
@app.get("/api/elica/status")
async def elica_status():
return get_elica_status()
@@ -651,7 +822,6 @@ async def set_external_fan(state: Literal["on", "off"]):
# ----------------------------------------------------------------------
# Power
# ----------------------------------------------------------------------
@app.post("/api/tion/power/{state}")
async def set_power(state: Literal["on", "off"]):
@@ -671,7 +841,6 @@ async def set_power(state: Literal["on", "off"]):
# ----------------------------------------------------------------------
# Fan speed increase / decrease
# ----------------------------------------------------------------------
@app.post("/api/tion/speed/increase")
async def increase_speed():
@@ -733,96 +902,57 @@ async def set_speed(
# ----------------------------------------------------------------------
# Heater
# ----------------------------------------------------------------------
@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"
if enabled:
operation = lambda tion: tion.heater_on()
else:
operation = lambda tion: tion.heater_off()
operation = (
(lambda tion: tion.heater_on())
if enabled
else
(lambda tion: tion.heater_off())
)
return await execute_command(
return await execute_temperature_command(
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(
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
# ----------------------------------------------------------------------
@app.post("/api/tion/temperature/{temperature}")
async def set_temperature(
temperature: Annotated[
int,
Path(
ge=MIN_TARGET_TEMP,
le=MAX_TARGET_TEMP,
),
],):
int,
Path(
ge=MIN_TARGET_TEMP,
le=MAX_TARGET_TEMP,
),
],
):
return await execute_command(
return await execute_temperature_command(
lambda tion:
tion.set_target_temperature(temperature),
ScheduledSettings(target_temp=temperature),
tion.set_target_temperature(
temperature
),
ScheduledSettings(
target_temp=temperature,
),
)
# ----------------------------------------------------------------------
# Air mode
# ----------------------------------------------------------------------
@app.post("/api/tion/mode/{mode}")
async def set_mode(
mode: str,
@@ -854,7 +984,6 @@ async def set_mode(
# ----------------------------------------------------------------------
# Sound
# ----------------------------------------------------------------------
@app.post("/api/tion/sound/{value}")
async def set_sound(
value: Literal["on", "off"],
@@ -877,7 +1006,6 @@ async def set_sound(
# ----------------------------------------------------------------------
# Light
# ----------------------------------------------------------------------
@app.post("/api/tion/light/{value}")
async def set_light(
value: Literal["on", "off"],
@@ -899,7 +1027,6 @@ async def set_light(
# ----------------------------------------------------------------------
# Переход в auto
# ----------------------------------------------------------------------
@app.get("/api/schedule/config")
async def get_schedule_config():
try:
@@ -989,6 +1116,9 @@ async def clear_schedule_override():
await schedule_service.clear_override()
if auto_controller is not None:
await auto_controller.reconcile_temperature()
return {
"ok": True,
"schedule": get_schedule_status(),
@@ -1007,8 +1137,42 @@ async def pause_schedule():
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()
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 {
"ok": True,
"schedule": get_schedule_status(),
@@ -1028,6 +1192,11 @@ async def resume_schedule():
await schedule_service.resume()
if auto_controller is not None:
auto_controller.clear_manual_heater_control()
await auto_controller.reconcile_temperature()
return {
"ok": True,
"schedule": get_schedule_status(),
+4
View File
@@ -1,7 +1,9 @@
from .config import (
AutoConfig,
AutoConfigComponents,
Co2Config,
load_auto_config,
load_auto_config_components,
)
from .co2_policy import (
@@ -19,4 +21,6 @@ __all__ = [
"load_auto_config",
"Co2SpeedPolicy",
"AutoController",
"AutoConfigComponents",
"load_auto_config_components",
]
+277 -70
View File
@@ -30,6 +30,21 @@ class Co2Config:
class TemperatureConfig:
hysteresis: float
@dataclass(
frozen=True,
slots=True,
)
class ElicaAssistConfig:
enabled: bool
# (скорость Tion, скорость Elica)
speed_map: tuple[
tuple[int, int],
...
]
@dataclass(
frozen=True,
slots=True,
@@ -39,8 +54,23 @@ class AutoConfig:
check_interval: float
co2: Co2Config
temperature: TemperatureConfig
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:
if not isinstance(value, dict):
@@ -246,14 +276,155 @@ def _parse_co2(value: Any) -> Co2Config:
thresholds=thresholds,
)
def _parse_temperature(value: Any) -> TemperatureConfig:
def load_auto_config(path: str | Path) -> AutoConfig:
data = _require_dict(
"temperature",
value,
)
unknown = (
set(data)
- {
"hysteresis",
}
)
if unknown:
raise ValueError(
f"Unknown temperature config fields: "
f"{sorted(unknown)}"
)
hysteresis = data.get(
"hysteresis"
)
if (
type(hysteresis)
not in {
int,
float,
}
):
raise ValueError(
"temperature.hysteresis "
"must be a number"
)
hysteresis = float(hysteresis)
if hysteresis < 0:
raise ValueError(
"temperature.hysteresis "
"must be >= 0"
)
return TemperatureConfig(
hysteresis=hysteresis,
)
def _parse_elica_assist(value: Any) -> ElicaAssistConfig:
data = _require_dict(
"elica_assist",
value,
)
unknown = (
set(data)
- {
"enabled",
"speed_map",
}
)
if unknown:
raise ValueError(
"Unknown elica_assist config fields: "
f"{sorted(unknown)}"
)
enabled = data.get("enabled")
if type(enabled) is not bool:
raise ValueError(
"elica_assist.enabled "
"must be a boolean"
)
speed_map_data = data.get(
"speed_map"
)
if not isinstance(
speed_map_data,
dict,
):
raise ValueError(
"elica_assist.speed_map "
"must be an object"
)
speed_map = []
for tion_speed, elica_speed in (
speed_map_data.items()
):
if type(tion_speed) is not int:
raise ValueError(
"elica_assist.speed_map keys "
"must be integers"
)
if not (
MIN_FAN_SPEED
<= tion_speed
<= MAX_FAN_SPEED
):
raise ValueError(
"Tion speed in "
"elica_assist.speed_map "
f"must be between "
f"{MIN_FAN_SPEED} and "
f"{MAX_FAN_SPEED}"
)
if type(elica_speed) is not int:
raise ValueError(
"Elica speed in "
"elica_assist.speed_map "
"must be an integer"
)
if not 1 <= elica_speed <= 4:
raise ValueError(
"Elica speed in "
"elica_assist.speed_map "
"must be between 1 and 4"
)
speed_map.append(
(
tion_speed,
elica_speed,
)
)
speed_map.sort()
return ElicaAssistConfig(
enabled=enabled,
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",
"r",
encoding="utf-8",
) as file:
raw = yaml.safe_load(file)
@@ -267,6 +438,7 @@ def load_auto_config(path: str | Path) -> AutoConfig:
"check_interval",
"co2",
"temperature",
"elica_assist",
}
if unknown:
@@ -288,10 +460,8 @@ def load_auto_config(path: str | Path) -> AutoConfig:
)
if (
type(check_interval) not in {
int,
float,
}
type(check_interval)
not in {int,float,}
):
raise ValueError(
"check_interval must be a number"
@@ -302,88 +472,125 @@ def load_auto_config(path: str | Path) -> AutoConfig:
"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
# --------------------------------------------------
if "co2" not in data:
raise ValueError(
"co2 config is required"
)
co2 = _parse_co2(
data["co2"]
)
raise ValueError("co2 config is required")
co2 = _parse_co2(data["co2"])
# --------------------------------------------------
# Temperature
# --------------------------------------------------
if "temperature" not in data:
raise ValueError(
"temperature config is required"
)
raise ValueError("temperature config is required")
temperature_data = _require_dict(
"temperature",
data["temperature"],
)
unknown_temperature = (
set(temperature_data)
- {
"hysteresis",
}
)
if unknown_temperature:
raise ValueError(
f"Unknown temperature config fields: "
f"{sorted(unknown_temperature)}"
)
temperature_hysteresis = (
temperature_data.get(
"hysteresis"
)
)
if (
type(temperature_hysteresis)
not in {
int,
float,
}
):
raise ValueError(
"temperature.hysteresis "
"must be a number"
)
temperature_hysteresis = float(
temperature_hysteresis
)
if temperature_hysteresis < 0:
raise ValueError(
"temperature.hysteresis "
"must be >= 0"
)
temperature = TemperatureConfig(
hysteresis=temperature_hysteresis,
)
temperature = _parse_temperature(data["temperature"])
# --------------------------------------------------
# Result
# 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(
version=version,
check_interval=float(
check_interval
),
check_interval=check_interval,
co2=co2,
temperature=temperature,
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,
)
+662 -177
View File
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
from dataclasses import dataclass
from enum import Enum
from .config import ElicaAssistConfig
class ElicaAssistMode(str, Enum):
IDLE = "idle"
OWNED = "owned"
SUPPRESSED = "suppressed"
@dataclass(slots=True)
class ElicaAssistRuntime:
mode: ElicaAssistMode = ElicaAssistMode.IDLE
reason: str | None = None
tion_speed: int | None = None
target_speed: int | None = None
# Скорость, которую автоматика считает
# установленной ею самой.
expected_speed: int | None = None
class ElicaAutoAssistState:
def __init__(
self,
config: ElicaAssistConfig,
):
self._config = config
self._speed_map = dict(
config.speed_map
)
self._runtime = ElicaAssistRuntime()
@property
def mode(self) -> ElicaAssistMode:
return self._runtime.mode
@property
def target_speed(self) -> int | None:
return self._runtime.target_speed
@property
def expected_speed(self) -> int | None:
return self._runtime.expected_speed
def set_tion_speed(self, tion_speed: int) -> int | None:
"""
Обновляет текущую AUTO-скорость Tion
и вычисляет требуемую скорость Elica.
Никаких команд Elica здесь нет.
"""
self._runtime.tion_speed = tion_speed
if not self._config.enabled:
target = None
else:
target = self._speed_map.get(tion_speed)
self._runtime.target_speed = target
# Если потребность в Elica закончилась,
# SUPPRESSED можно сбросить:
# следующий подъём Tion будет уже
# новым циклом.
if (
target is None
and self._runtime.mode
== ElicaAssistMode.SUPPRESSED
):
self._runtime.mode = (
ElicaAssistMode.IDLE
)
self._runtime.reason = None
self._runtime.expected_speed = None
return target
def mark_owned(self, speed: int) -> None:
"""
Будем вызывать позже только после того,
как автоматика действительно успешно
включила Elica.
"""
self._runtime.mode = ElicaAssistMode.OWNED
self._runtime.reason = None
self._runtime.expected_speed = speed
def suppress(self, reason: str) -> None:
"""
Elica принадлежит пользователю.
До конца текущего AUTO-цикла
автоматика её не трогает.
"""
self._runtime.mode = ElicaAssistMode.SUPPRESSED
self._runtime.reason = reason
self._runtime.expected_speed = None
def reset(self) -> None:
self._runtime = ElicaAssistRuntime()
def status(self) -> dict:
return {
"mode": self._runtime.mode.value,
"reason": self._runtime.reason,
"tion_speed": self._runtime.tion_speed,
"target_speed": self._runtime.target_speed,
"expected_speed": self._runtime.expected_speed,
}
def observe_elica(
self,
power: bool,
speed: int,
timer: bool = False,
) -> None:
"""
Передаёт state machine фактическое состояние Elica.
Пока никаких команд вытяжке не отправляет.
"""
target = self._runtime.target_speed
# Сейчас Elica для AUTO вообще не требуется.
if target is None:
return
# --------------------------------------------------
# IDLE
#
# Tion уже требует помощи Elica, но вытяжка
# оказалась включена ещё до того, как автоматика
# получила над ней управление.
#
# Значит считаем её пользовательской и не трогаем
# до конца текущего цикла.
# --------------------------------------------------
if self._runtime.mode == ElicaAssistMode.IDLE:
if power:
self.suppress(
"elica_already_on"
)
return
# --------------------------------------------------
# OWNED
#
# Позже в это состояние будем переходить после
# успешной автоматической команды.
#
# Если фактическое состояние перестало совпадать
# с тем, которое установила автоматика,
# считаем это ручным вмешательством.
# --------------------------------------------------
if self._runtime.mode == ElicaAssistMode.OWNED:
expected = (
self._runtime.expected_speed
)
if (
not power
or speed != expected
or timer
):
self.suppress(
"manual_intervention"
)
+40 -17
View File
@@ -20,11 +20,13 @@ class ElicaController:
state_timeout: float = 3.0,
poll_interval: float = 0.05,
speed_inter_press_delay: float = 0.4,
):
self._service = service
self._state_timeout = state_timeout
self._poll_interval = poll_interval
self._speed_inter_press_delay = max(0.0, speed_inter_press_delay)
self._last_speed_press_finished_at: float | None = None
# Не допускаем одновременное выполнение нескольких
# последовательностей нажатий кнопок.
@@ -111,7 +113,6 @@ class ElicaController:
# ------------------------------------------------------------------
# Power
# ------------------------------------------------------------------
async def power_on(self) -> ElicaLogicalState:
async with self._lock:
return await self._power_on_locked()
@@ -120,10 +121,45 @@ class ElicaController:
async with self._lock:
return await self._power_off_locked()
async def _press_speed_locked(self) -> None:
"""
Нажимает Speed с гарантированным минимальным
интервалом после предыдущего нажатия.
Интервал соблюдается и между разными
вызовами set_speed().
"""
loop = asyncio.get_running_loop()
if (
self._last_speed_press_finished_at is not None
and self._speed_inter_press_delay > 0
):
elapsed = (
loop.time()
- self._last_speed_press_finished_at
)
remaining = (
self._speed_inter_press_delay
- elapsed
)
if remaining > 0:
await asyncio.sleep(
remaining
)
await self._service.press_speed()
self._last_speed_press_finished_at = (
loop.time()
)
# ------------------------------------------------------------------
# Speed
# ------------------------------------------------------------------
async def set_speed(self, speed: int) -> ElicaLogicalState:
"""Устанавливает скорость 1-4 последовательными нажатиями Speed.
@@ -145,20 +181,12 @@ class ElicaController:
# У Elica кнопка Speed сама включает вытяжку. Первое
# нажатие из состояния OFF запускает её на скорости 1.
# Поэтому при выборе скорости Power здесь не нажимаем.
await self._service.press_speed()
await self._press_speed_locked()
state = await self._wait_state(
lambda value: value.power and value.speed == 1,
"speed 1",
)
# После физического отпускания кнопки Elica нужен
# небольшой гарантированный интервал до следующего
# нажатия. Иначе при быстром наборе 2/3/4 контроллер
# вытяжки иногда воспринимает два импульса как одно
# длинное нажатие или просто игнорирует следующий.
if speed != 1 and self._speed_inter_press_delay > 0:
await asyncio.sleep(self._speed_inter_press_delay)
# Если питание уже было включено, но индикатор скорости ещё
# не успел синхронизироваться, ждём корректное значение 1-4.
if not 1 <= state.speed <= 4:
@@ -173,7 +201,7 @@ class ElicaController:
for _ in range(presses):
expected_speed = current_speed % 4 + 1
await self._service.press_speed()
await self._press_speed_locked()
state = await self._wait_state(
lambda value, expected=expected_speed: (
@@ -184,11 +212,6 @@ class ElicaController:
current_speed = expected_speed
# Не нажимаем Speed повторно сразу после отпускания
# предыдущего импульса. Это особенно важно для переходов
# на 4-ю скорость, где требуется несколько нажатий подряд.
if current_speed != speed and self._speed_inter_press_delay > 0:
await asyncio.sleep(self._speed_inter_press_delay)
return state
+51 -9
View File
@@ -524,26 +524,68 @@ class ElicaService:
async def pulse_relay(self, relay: int, pulse_ms: int | None = None) -> None:
"""
Кратковременно включает реле и затем выключает его.
Используется для эмуляции нажатия кнопок Elica.
Перед первой командой обязательно ждём
синхронизации MQTT-feedback этого реле.
"""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
raise ValueError(
"Relay number must be between 1 and 8"
)
duration_ms = pulse_ms if pulse_ms is not None else self._config.pulse_ms
duration_ms = (
pulse_ms
if pulse_ms is not None
else self._config.pulse_ms
)
self.set_relay(relay, True)
# --------------------------------------------------
# ВАЖНО:
# после MQTT connect состояния входов панели
# и состояний реле приходят независимо.
#
# Нельзя начинать импульс, пока мы не получили
# хотя бы первое достоверное состояние именно
# этого OUT.
# --------------------------------------------------
await self.wait_relay_feedback_ready(relay)
# --------------------------------------------------
# Перед новым импульсом реле обязано быть OFF.
#
# Это дополнительно восстанавливает состояние,
# если предыдущая операция была аварийно
# прервана на включённом реле.
# --------------------------------------------------
if self.relay_state(relay):
self.set_relay(relay,False)
await self.wait_relay_state(relay,False)
# --------------------------------------------------
# Нажатие
# --------------------------------------------------
self.set_relay(relay,True)
try:
await self.wait_relay_state(relay, True)
await self.wait_relay_state(relay,True)
await asyncio.sleep(duration_ms / 1000)
finally:
# Relay обязательно пытаемся отпустить,
# даже если подтверждение ON не пришло.
try:
self.set_relay(relay, False)
except Exception:
logger.exception("Failed to release Elica relay %s", relay)
self.set_relay(relay,False)
await self.wait_relay_state(relay, False)
except Exception:
logger.exception("Failed to release Elica relay %s",relay)
# И ждём подтверждённого отпускания.
await self.wait_relay_state(relay,False)
+1 -1
View File
@@ -10,7 +10,7 @@ from typing import Any, Mapping
TION_MAC = "d1:74:9b:eb:ee:a6"
QINGPING_MAC = "CCB5D131BA93"
QINGPING_MQTT_HOST = "192.168.7.3"
QINGPING_MQTT_HOST = "192.168.7.100"
QINGPING_MQTT_PORT = 1883
# ESP32-контроллер вытяжки Elica подключён к Mosquitto на mini-PC/NAS.
+90 -2
View File
@@ -1,4 +1,7 @@
import asyncio
import logging
import shutil
import sys
from typing import Any
from bleak import BleakScanner
from tion_btle import TionS4
@@ -7,6 +10,7 @@ from .models import TionState
from app.my_dataclasses import *
logger = logging.getLogger(__name__)
class TionController:
"""
@@ -88,12 +92,23 @@ class TionController:
# от предыдущего соединения.
await self._reset_device()
# Получаем свежий BLEDevice.
# Сначала обычный поиск.
ble_device = await BleakScanner.find_device_by_address(
self._mac,
timeout=5.0,
)
if ble_device is None:
# Возможно, предыдущий процесс умер через SIGKILL,
# а ОС всё ещё удерживает старое BLE-соединение.
await self._recover_stale_system_connection()
# После recovery пробуем найти Tion ещё раз.
ble_device = await BleakScanner.find_device_by_address(
self._mac,
timeout=5.0,
)
if ble_device is None:
raise ConnectionError(
f"Tion {self._mac} not found"
@@ -150,8 +165,18 @@ class TionController:
"""
async def power_on(self) -> TionState:
# Tion 4S reliably wakes up when the power command also carries
# a valid fan speed. The device keeps the last speed even while
# powered off, so preserve it instead of forcing a new value.
speed = (
self._state.fan_speed
if self._state is not None
else MIN_FAN_SPEED
)
return await self._set({
"state": "on"
"state": "on",
"fan_speed": speed,
})
async def power_off(self) -> TionState:
@@ -273,3 +298,66 @@ class TionController:
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
await self.disconnect()
async def _recover_stale_system_connection(self) -> None:
"""
Попытаться освободить зависшее BLE-соединение,
оставшееся после аварийного завершения предыдущего процесса.
На Linux BlueZ может продолжать показывать Connected=yes,
хотя процесс-владелец уже умер. В таком состоянии Tion может
не advertising'иться, поэтому BleakScanner его не находит.
На других ОС ничего не делаем: основной код остаётся
платформенно-независимым.
"""
if not sys.platform.startswith("linux"):
return
bluetoothctl = shutil.which("bluetoothctl")
if bluetoothctl is None:
logger.warning(
"Tion stale-connection recovery skipped: "
"bluetoothctl not found"
)
return
logger.warning(
"Tion %s not found by scan; "
"trying to clear stale BlueZ connection",
self._mac,
)
process = await asyncio.create_subprocess_exec(
bluetoothctl,
"disconnect",
self._mac,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=5.0,
)
except asyncio.TimeoutError:
process.kill()
await process.communicate()
logger.warning(
"Timed out while clearing stale Tion BLE connection"
)
return
logger.warning(
"Tion BlueZ recovery finished: rc=%s stdout=%s stderr=%s",
process.returncode,
stdout.decode(errors="replace").strip(),
stderr.decode(errors="replace").strip(),
)
# Даём BlueZ и самому Tion время освободить старое соединение
# и снова начать advertising.
await asyncio.sleep(1.0)
@@ -24,3 +24,12 @@ co2:
temperature:
hysteresis: 0.5
elica_assist:
enabled: true
speed_map:
4: 1
5: 2
6: 3
@@ -36,7 +36,6 @@ templates:
weekend:
- time: "10:00"
action:
power: on
@@ -62,16 +61,12 @@ templates:
speed: 1
days:
mon: workday
tue: workday
wed: workday
thu: workday
fri: workday
sat: weekend
sun: weekend
@@ -0,0 +1,425 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.controller import AutoController
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-auto-elica-already-on-test-"
f"{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready.\n"
f"mqtt_connected="
f"{state.mqtt_connected}\n"
f"device_online="
f"{state.device_online}\n"
f"feedback_ready="
f"{service.feedback_ready}\n"
f"missing_feedback_inputs="
f"{service.missing_feedback_inputs}"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
initial = elica_controller.state
print()
print(
"Initial Elica:",
{
"power": initial.power,
"speed": initial.speed,
"timer": initial.timer,
},
)
# --------------------------------------------------
# Для этого теста Elica должна быть заранее
# включена пользователем.
# --------------------------------------------------
if not initial.power:
raise RuntimeError(
"Before starting this test, "
"manually turn Elica ON "
"at any speed."
)
initial_power = initial.power
initial_speed = initial.speed
initial_timer = initial.timer
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
auto_controller = AutoController(
schedule_service=object(),
qingping_service=object(),
tion_service=object(),
elica_controller=elica_controller,
policy=None,
temperature_policy=None,
elica_assist=assist,
interval=1.0,
)
# ==================================================
# ЭТАП 1
#
# Пользовательская Elica уже включена.
#
# Tion AUTO поднимается до 4.
#
# AutoController должен:
#
# увидеть Elica ON
# -> SUPPRESSED
# -> reason = elica_already_on
# -> ничего не переключать
# ==================================================
print()
print(
"STEP 1:"
)
print(
"Tion AUTO speed 4 while "
"Elica is already user-controlled."
)
await auto_controller._update_elica_assist(
4
)
after_speed_4 = elica_controller.state
print()
print(
"Elica after Tion speed 4:",
{
"power": after_speed_4.power,
"speed": after_speed_4.speed,
"timer": after_speed_4.timer,
},
)
print(
"Assist:",
assist.status(),
)
if assist.mode.value != "suppressed":
raise RuntimeError(
"Assist did not enter SUPPRESSED"
)
if (
assist.status()["reason"]
!= "elica_already_on"
):
raise RuntimeError(
"Expected reason elica_already_on"
)
# --------------------------------------------------
# Elica обязана остаться полностью неизменной.
# --------------------------------------------------
if (
after_speed_4.power != initial_power
or after_speed_4.speed != initial_speed
or after_speed_4.timer != initial_timer
):
raise RuntimeError(
"AutoController modified "
"already-running user Elica"
)
print()
print(
"SUPPRESSION PASSED"
)
# ==================================================
# ЭТАП 2
#
# Пока Tion остаётся в диапазоне,
# например поднимается 4 -> 5.
#
# Elica всё равно трогать нельзя.
# ==================================================
print()
print(
"STEP 2:"
)
print(
"Tion AUTO speed changes 4 -> 5."
)
print(
"Elica must remain untouched."
)
await auto_controller._update_elica_assist(
5
)
after_speed_5 = elica_controller.state
print()
print(
"Elica after Tion speed 5:",
{
"power": after_speed_5.power,
"speed": after_speed_5.speed,
"timer": after_speed_5.timer,
},
)
print(
"Assist:",
assist.status(),
)
if assist.mode.value != "suppressed":
raise RuntimeError(
"Assist left SUPPRESSED "
"during the same cycle"
)
if (
after_speed_5.power != initial_power
or after_speed_5.speed != initial_speed
or after_speed_5.timer != initial_timer
):
raise RuntimeError(
"AutoController modified Elica "
"while SUPPRESSED"
)
print()
print(
"SUPPRESSED HOLD PASSED"
)
# ==================================================
# ЭТАП 3
#
# Tion падает до 3.
#
# Текущий повышенный AUTO-цикл закончен.
#
# Elica должна остаться пользовательской,
# но Assist может вернуться в IDLE.
# ==================================================
print()
print("STEP 3:")
print("Tion AUTO speed drops to 3.")
print(
"Elica must remain ON and unchanged."
)
await auto_controller._update_elica_assist(
3
)
final_elica = elica_controller.state
print()
print(
"Final Elica:",
{
"power": final_elica.power,
"speed": final_elica.speed,
"timer": final_elica.timer,
},
)
print(
"Final Assist:",
assist.status(),
)
if (
final_elica.power != initial_power
or final_elica.speed != initial_speed
or final_elica.timer != initial_timer
):
raise RuntimeError(
"AutoController changed user Elica "
"when the Tion cycle ended"
)
if assist.mode.value != "idle":
raise RuntimeError(
"Assist did not return to IDLE "
"after Tion dropped below threshold"
)
print()
print(
"CYCLE END PASSED"
)
print()
print(
"TEST PASSED"
)
print()
print("Verified sequence:")
print(
"User Elica already ON"
" -> Tion 4"
" -> SUPPRESSED"
)
print(
"Tion 5"
" -> Elica untouched"
" -> still SUPPRESSED"
)
print(
"Tion 3"
" -> Elica untouched"
" -> IDLE"
)
finally:
print()
print("Stopping Elica service...")
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,355 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.controller import AutoController
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
"""
Используем отдельный MQTT client_id,
чтобы тест не конфликтовал с обычным
ClimatController.
"""
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-auto-elica-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready.\n"
f"mqtt_connected="
f"{state.mqtt_connected}\n"
f"device_online="
f"{state.device_online}\n"
f"feedback_ready="
f"{service.feedback_ready}\n"
f"missing_feedback_inputs="
f"{service.missing_feedback_inputs}"
)
await asyncio.sleep(0.1)
async def main() -> None:
# --------------------------------------------------
# Реальный ElicaService + ElicaController.
# --------------------------------------------------
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
initial = elica_controller.state
print()
print(
"Initial Elica:",
{
"power": initial.power,
"speed": initial.speed,
"timer": initial.timer,
},
)
# Для чистого теста начинаем с выключенной Elica.
if initial.power:
raise RuntimeError(
"Elica must be OFF before this test. "
"Turn it off manually and run again."
)
# --------------------------------------------------
# Создаём настоящий Elica Auto Assist.
# --------------------------------------------------
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# --------------------------------------------------
# Создаём настоящий AutoController.
#
# Schedule / Qingping / Tion здесь не нужны,
# потому что мы НЕ запускаем его основной цикл,
# а вызываем только _update_elica_assist().
# --------------------------------------------------
auto_controller = AutoController(
schedule_service=object(),
qingping_service=object(),
tion_service=object(),
elica_controller=elica_controller,
policy=None,
temperature_policy=None,
elica_assist=assist,
interval=1.0,
)
# ==================================================
# ЭТАП 1
#
# Имитируем:
#
# Tion AUTO выбрал скорость 4.
#
# Именно реальный метод AutoController должен:
#
# target = 1
# Elica OFF -> speed 1
# mode -> OWNED
# ==================================================
print()
print(
"Calling AutoController "
"_update_elica_assist(4)..."
)
await auto_controller._update_elica_assist(
4
)
acquired = elica_controller.state
print()
print(
"Elica after Tion speed 4:",
{
"power": acquired.power,
"speed": acquired.speed,
"timer": acquired.timer,
},
)
print(
"Assist:",
assist.status(),
)
if not acquired.power:
raise RuntimeError(
"AutoController did not turn Elica on"
)
if acquired.speed != 1:
raise RuntimeError(
f"Expected Elica speed 1, "
f"got {acquired.speed}"
)
if assist.mode.value != "owned":
raise RuntimeError(
"Auto Assist did not enter OWNED"
)
if assist.expected_speed != 1:
raise RuntimeError(
"expected_speed is not 1"
)
print()
print(
"ACQUIRE PASSED"
)
# ==================================================
# ЭТАП 2
#
# Имитируем:
#
# Tion AUTO упал до скорости 3.
#
# Теперь реальный AutoController должен:
#
# target = None
# проверить OWNED
# выключить Elica
# reset -> IDLE
# ==================================================
print()
print(
"Calling AutoController "
"_update_elica_assist(3)..."
)
await auto_controller._update_elica_assist(
3
)
released = elica_controller.state
print()
print(
"Elica after Tion speed 3:",
{
"power": released.power,
"speed": released.speed,
"timer": released.timer,
},
)
print(
"Assist:",
assist.status(),
)
if released.power:
raise RuntimeError(
"AutoController did not turn Elica off"
)
if assist.mode.value != "idle":
raise RuntimeError(
"Auto Assist did not return to IDLE"
)
if assist.expected_speed is not None:
raise RuntimeError(
"expected_speed was not cleared"
)
print()
print(
"RELEASE PASSED"
)
print()
print(
"TEST PASSED"
)
print(
"Real AutoController successfully performed:"
)
print(
"Tion 4 -> Elica speed 1 -> OWNED"
)
print(
"Tion 3 -> Elica OFF -> IDLE"
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,422 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.controller import AutoController
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
MANUAL_CHANGE_TIMEOUT = 60.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-auto-exit-manual-test-"
f"{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready"
)
await asyncio.sleep(0.1)
async def wait_for_manual_change(
service: ElicaService,
*,
power: bool,
speed: int,
timer: bool,
):
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ MANUAL_CHANGE_TIMEOUT
)
while True:
state = service.state
ready = (
state.mqtt_connected
and state.device_online
and service.feedback_ready
)
if ready:
logical = service.logical_state
if (
logical.power != power
or logical.speed != speed
or logical.timer != timer
):
return logical
if loop.time() >= deadline:
raise RuntimeError(
"No manual Elica change detected "
f"within {MANUAL_CHANGE_TIMEOUT} seconds"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
initial = elica_controller.state
print()
print(
"Initial Elica:",
{
"power": initial.power,
"speed": initial.speed,
"timer": initial.timer,
},
)
if initial.power:
raise RuntimeError(
"Elica must be OFF before this test"
)
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
auto_controller = AutoController(
schedule_service=object(),
qingping_service=object(),
tion_service=object(),
elica_controller=elica_controller,
policy=None,
temperature_policy=None,
elica_assist=assist,
interval=1.0,
)
# ==================================================
# STEP 1
#
# AUTO активен:
# Tion 4 -> Elica 1 -> OWNED
# ==================================================
print()
print("STEP 1:")
print(
"Tion AUTO speed 4 "
"-> Auto Assist acquires Elica"
)
await auto_controller._update_elica_assist(
4
)
owned = elica_controller.state
print()
print(
"Elica:",
{
"power": owned.power,
"speed": owned.speed,
"timer": owned.timer,
},
)
print(
"Assist:",
assist.status(),
)
if (
not owned.power
or owned.speed != 1
):
raise RuntimeError(
"Auto Assist did not acquire "
"Elica at speed 1"
)
if assist.mode.value != "owned":
raise RuntimeError(
"Assist did not enter OWNED"
)
print()
print(
"ACQUIRE PASSED"
)
# ==================================================
# STEP 2
#
# Пользователь вручную меняет Elica.
# Например 1 -> 2.
# ==================================================
print()
print("STEP 2:")
print(
"Now MANUALLY change Elica."
)
print(
"For example change speed 1 -> 2."
)
print(
"The test is waiting..."
)
changed = await wait_for_manual_change(
service,
power=owned.power,
speed=owned.speed,
timer=owned.timer,
)
print()
print(
"Manual Elica state:",
{
"power": changed.power,
"speed": changed.speed,
"timer": changed.timer,
},
)
# ==================================================
# STEP 3
#
# ВАЖНО:
# AutoController ещё не успел сделать обычный
# проход _update_elica_assist().
#
# Сразу имитируем выход из AUTO.
#
# _release_elica_assist() сам обязан заметить,
# что actual != expected, и НЕ выключить Elica.
# ==================================================
print()
print("STEP 3:")
print(
"Simulating immediate exit from AUTO..."
)
print(
"Elica must NOT be switched off."
)
await auto_controller._release_elica_assist()
final_elica = elica_controller.state
print()
print(
"Final Elica:",
{
"power": final_elica.power,
"speed": final_elica.speed,
"timer": final_elica.timer,
},
)
print(
"Final Assist:",
assist.status(),
)
# --------------------------------------------------
# Elica должна остаться точно такой,
# какой её сделал пользователь.
# --------------------------------------------------
if (
final_elica.power != changed.power
or final_elica.speed != changed.speed
or final_elica.timer != changed.timer
):
raise RuntimeError(
"AutoController modified user's Elica "
"during AUTO exit"
)
# --------------------------------------------------
# Сессия Auto Assist должна закончиться.
# --------------------------------------------------
if assist.mode.value != "idle":
raise RuntimeError(
"Assist did not return to IDLE "
"after AUTO exit"
)
if assist.expected_speed is not None:
raise RuntimeError(
"expected_speed was not cleared"
)
print()
print(
"MANUAL TAKEOVER ON AUTO EXIT PASSED"
)
print()
print(
"TEST PASSED"
)
print()
print(
"Verified sequence:"
)
print(
"AUTO -> Tion 4 "
"-> Elica 1 "
"-> OWNED"
)
print(
"User changes Elica"
)
print(
"AUTO exit "
"-> Elica untouched "
"-> IDLE"
)
print()
print(
"Turn Elica off manually "
"after the test."
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,555 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.controller import AutoController
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
MANUAL_CHANGE_TIMEOUT = 60.0
class TestElicaService(ElicaService):
"""
Отдельный MQTT client_id для live-теста.
"""
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-auto-elica-manual-test-"
f"{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready.\n"
f"mqtt_connected="
f"{state.mqtt_connected}\n"
f"device_online="
f"{state.device_online}\n"
f"feedback_ready="
f"{service.feedback_ready}\n"
f"missing_feedback_inputs="
f"{service.missing_feedback_inputs}"
)
await asyncio.sleep(0.1)
async def wait_for_manual_change(
service: ElicaService,
*,
power: bool,
speed: int,
timer: bool,
):
"""
Ждём реального изменения Elica пользователем.
Потеря MQTT/feedback изменением
не считается.
"""
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ MANUAL_CHANGE_TIMEOUT
)
while True:
state = service.state
ready = (
state.mqtt_connected
and state.device_online
and service.feedback_ready
)
if ready:
logical = service.logical_state
if (
logical.power != power
or logical.speed != speed
or logical.timer != timer
):
return logical
if loop.time() >= deadline:
raise RuntimeError(
"No manual Elica change detected "
f"within {MANUAL_CHANGE_TIMEOUT} seconds"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
initial = elica_controller.state
print()
print(
"Initial Elica:",
{
"power": initial.power,
"speed": initial.speed,
"timer": initial.timer,
},
)
if initial.power:
raise RuntimeError(
"Elica must be OFF before this test. "
"Turn it off manually and run again."
)
# --------------------------------------------------
# Создаём настоящий Auto Assist.
# --------------------------------------------------
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# --------------------------------------------------
# Настоящий AutoController.
#
# Основной цикл мы не запускаем.
# Вызываем только _update_elica_assist().
# --------------------------------------------------
auto_controller = AutoController(
schedule_service=object(),
qingping_service=object(),
tion_service=object(),
elica_controller=elica_controller,
policy=None,
temperature_policy=None,
elica_assist=assist,
interval=1.0,
)
# ==================================================
# ЭТАП 1
#
# Tion 4
# -> AutoController включает Elica 1
# -> OWNED
# ==================================================
print()
print(
"STEP 1:"
)
print(
"Tion AUTO speed 4 "
"-> Auto Assist should acquire Elica"
)
await auto_controller._update_elica_assist(
4
)
owned = elica_controller.state
print()
print(
"Elica:",
{
"power": owned.power,
"speed": owned.speed,
"timer": owned.timer,
},
)
print(
"Assist:",
assist.status(),
)
if (
not owned.power
or owned.speed != 1
):
raise RuntimeError(
"AutoController did not acquire "
"Elica at speed 1"
)
if assist.mode.value != "owned":
raise RuntimeError(
"Assist did not enter OWNED"
)
print()
print(
"ACQUIRE PASSED"
)
# ==================================================
# ЭТАП 2
#
# Теперь пользователь физически меняет Elica.
#
# Например:
#
# speed 1 -> 2
#
# AutoController пока ничего не делает.
# Просто ждём реальный MQTT feedback.
# ==================================================
print()
print(
"STEP 2:"
)
print(
"Now MANUALLY change Elica."
)
print(
"For example change speed 1 -> 2."
)
print(
"The test is waiting..."
)
changed = await wait_for_manual_change(
service,
power=owned.power,
speed=owned.speed,
timer=owned.timer,
)
print()
print(
"Manual Elica state:",
{
"power": changed.power,
"speed": changed.speed,
"timer": changed.timer,
},
)
# ==================================================
# ЭТАП 3
#
# Tion всё ещё 4.
#
# Следующий проход AutoController должен увидеть:
#
# expected_speed = 1
# actual speed = 2
#
# -> manual_intervention
# -> SUPPRESSED
#
# И НИКАКИХ команд Elica.
# ==================================================
print()
print(
"STEP 3:"
)
print(
"Tion is still speed 4."
)
print(
"AutoController should detect "
"manual intervention..."
)
await auto_controller._update_elica_assist(
4
)
after_takeover = elica_controller.state
print()
print(
"Elica after detection:",
{
"power": after_takeover.power,
"speed": after_takeover.speed,
"timer": after_takeover.timer,
},
)
print(
"Assist:",
assist.status(),
)
if assist.mode.value != "suppressed":
raise RuntimeError(
"Assist did not enter SUPPRESSED"
)
if (
assist.status()["reason"]
!= "manual_intervention"
):
raise RuntimeError(
"Expected reason manual_intervention"
)
# Elica должна остаться ровно такой,
# какой её сделал пользователь.
if (
after_takeover.power
!= changed.power
or after_takeover.speed
!= changed.speed
or after_takeover.timer
!= changed.timer
):
raise RuntimeError(
"AutoController changed Elica "
"after manual intervention"
)
print()
print(
"MANUAL TAKEOVER PASSED"
)
# ==================================================
# ЭТАП 4
#
# Теперь Tion падает ниже порога:
#
# 4 -> 3
#
# Текущий автоматический цикл заканчивается.
#
# Но Elica уже пользовательская,
# поэтому выключать её ЗАПРЕЩЕНО.
#
# SUPPRESSED -> IDLE
# Elica остаётся включена.
# ==================================================
print()
print(
"STEP 4:"
)
print(
"Tion AUTO speed drops to 3."
)
print(
"Elica must NOT be switched off."
)
await auto_controller._update_elica_assist(
3
)
final_elica = elica_controller.state
print()
print(
"Final Elica:",
{
"power": final_elica.power,
"speed": final_elica.speed,
"timer": final_elica.timer,
},
)
print(
"Final Assist:",
assist.status(),
)
# --------------------------------------------------
# Проверяем, что пользовательское состояние
# вообще не изменилось.
# --------------------------------------------------
if (
final_elica.power
!= changed.power
or final_elica.speed
!= changed.speed
or final_elica.timer
!= changed.timer
):
raise RuntimeError(
"AutoController modified user's "
"Elica when Tion dropped to speed 3"
)
# Новый цикл должен быть готов начаться
# в будущем.
if assist.mode.value != "idle":
raise RuntimeError(
"Assist did not return to IDLE "
"after the automatic cycle ended"
)
print()
print(
"RELEASE AFTER TAKEOVER PASSED"
)
print()
print(
"TEST PASSED"
)
print()
print(
"Verified sequence:"
)
print(
"Tion 4"
" -> Auto Elica 1"
" -> OWNED"
)
print(
"User changes Elica"
" -> SUPPRESSED"
)
print(
"Tion 3"
" -> Elica untouched"
" -> IDLE"
)
print()
print(
"Turn Elica off manually "
"after the test."
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,314 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.controller import AutoController
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-auto-exit-test-"
f"{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
initial = elica_controller.state
print()
print(
"Initial Elica:",
{
"power": initial.power,
"speed": initial.speed,
"timer": initial.timer,
},
)
if initial.power:
raise RuntimeError(
"Elica must be OFF before this test"
)
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
auto_controller = AutoController(
schedule_service=object(),
qingping_service=object(),
tion_service=object(),
elica_controller=elica_controller,
policy=None,
temperature_policy=None,
elica_assist=assist,
interval=1.0,
)
# --------------------------------------------------
# ЭТАП 1
#
# Имитируем рабочий AUTO:
# Tion speed 4 -> Elica speed 1 -> OWNED
# --------------------------------------------------
print()
print("STEP 1:")
print(
"Tion AUTO speed 4 "
"-> Auto Assist acquires Elica"
)
await auto_controller._update_elica_assist(
4
)
owned = elica_controller.state
print()
print(
"Elica:",
{
"power": owned.power,
"speed": owned.speed,
"timer": owned.timer,
},
)
print(
"Assist:",
assist.status(),
)
if (
not owned.power
or owned.speed != 1
):
raise RuntimeError(
"Auto Assist did not acquire "
"Elica at speed 1"
)
if assist.mode.value != "owned":
raise RuntimeError(
"Assist did not enter OWNED"
)
print()
print(
"ACQUIRE PASSED"
)
# --------------------------------------------------
# ЭТАП 2
#
# Теперь имитируем не Tion speed 3,
# а полный ВЫХОД ИЗ AUTO.
#
# Именно _release_elica_assist()
# должен выключить принадлежащую нам Elica.
# --------------------------------------------------
print()
print("STEP 2:")
print(
"Simulating exit from Tion AUTO..."
)
await auto_controller._release_elica_assist()
released = elica_controller.state
print()
print(
"Elica after AUTO exit:",
{
"power": released.power,
"speed": released.speed,
"timer": released.timer,
},
)
print(
"Assist after AUTO exit:",
assist.status(),
)
# --------------------------------------------------
# ПРОВЕРКИ
# --------------------------------------------------
if released.power:
raise RuntimeError(
"Elica remained ON after AUTO exit"
)
if assist.mode.value != "idle":
raise RuntimeError(
"Assist did not return to IDLE"
)
if assist.expected_speed is not None:
raise RuntimeError(
"expected_speed was not cleared"
)
print()
print(
"AUTO EXIT RELEASE PASSED"
)
print()
print(
"TEST PASSED"
)
print()
print(
"Verified sequence:"
)
print(
"AUTO active"
" -> Tion 4"
" -> Elica 1"
" -> OWNED"
)
print(
"AUTO exit"
" -> Elica OFF"
" -> IDLE"
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,341 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
# По нашей текущей таблице:
# Tion 4 -> Elica 1
TION_SPEED = 4
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
"""
Отдельный MQTT client_id для live-теста,
чтобы не конфликтовать с запущенным
ClimatController.
"""
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-elica-acquire-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
"""
Ждём подключения к MQTT, ESP32
и полной обратной связи панели Elica.
"""
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready.\n"
f"mqtt_connected="
f"{state.mqtt_connected}\n"
f"device_online="
f"{state.device_online}\n"
f"feedback_ready="
f"{service.feedback_ready}\n"
f"missing_feedback_inputs="
f"{service.missing_feedback_inputs}"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
# --------------------------------------------------
# Перед началом теста Elica обязана быть OFF.
# --------------------------------------------------
state = controller.state
print()
print(
"Initial Elica:",
{
"power": state.power,
"speed": state.speed,
"timer": state.timer,
},
)
if state.power:
raise RuntimeError(
"Elica must be OFF before this test. "
"Turn it off manually and run the test again."
)
# --------------------------------------------------
# Создаём Auto Assist.
# --------------------------------------------------
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# --------------------------------------------------
# Имитируем решение AUTO Tion.
# --------------------------------------------------
target_speed = (
assist.set_tion_speed(
TION_SPEED
)
)
print()
print(
"Tion AUTO speed:",
TION_SPEED,
)
print(
"Elica target:",
target_speed,
)
print(
"Assist before observe:",
assist.status(),
)
# --------------------------------------------------
# Проверяем исходное состояние Elica.
#
# Она OFF, поэтому ассистент должен
# остаться IDLE и разрешить захват.
# --------------------------------------------------
assist.observe_elica(
power=state.power,
speed=state.speed,
timer=state.timer,
)
print(
"Assist after observe:",
assist.status(),
)
if assist.mode.value != "idle":
raise RuntimeError(
"Auto Assist did not remain IDLE "
"with Elica switched off"
)
if target_speed is None:
raise RuntimeError(
"No Elica target speed "
"for current Tion speed"
)
print()
print(
"AUTO ASSIST IS NOW GOING TO "
f"SET ELICA SPEED {target_speed}"
)
# --------------------------------------------------
# ПЕРВАЯ РЕАЛЬНАЯ КОМАНДА.
#
# Из OFF вызов set_speed(1) нажмёт Speed
# и дождётся подтверждения:
#
# power=True
# speed=1
# --------------------------------------------------
result = await controller.set_speed(
target_speed
)
print()
print(
"Confirmed Elica:",
{
"power": result.power,
"speed": result.speed,
"timer": result.timer,
},
)
# --------------------------------------------------
# Только после подтверждённой команды
# объявляем Elica принадлежащей автоматике.
# --------------------------------------------------
assist.mark_owned(
result.speed
)
print(
"Assist after mark_owned:",
assist.status(),
)
# --------------------------------------------------
# Передаём подтверждённое фактическое
# состояние ещё раз.
#
# Оно совпадает с expected_speed,
# поэтому OWNED должен сохраниться.
# --------------------------------------------------
assist.observe_elica(
power=result.power,
speed=result.speed,
timer=result.timer,
)
print()
print(
"Assist after confirmed feedback:",
assist.status(),
)
if assist.mode.value != "owned":
raise RuntimeError(
"Auto Assist did not enter OWNED state"
)
if result.speed != target_speed:
raise RuntimeError(
"Elica reached unexpected speed"
)
print()
print(
"TEST PASSED"
)
print(
"Elica was acquired by Auto Assist "
f"at speed {result.speed}."
)
print(
"Turn Elica off manually after the test."
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
+368
View File
@@ -0,0 +1,368 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
# Имитируем ситуацию:
# AUTO-контроллер Tion выбрал скорость 4.
TION_SPEED = 4
ELICA_READY_TIMEOUT = 15.0
ELICA_CHANGE_TIMEOUT = 60.0
class TestElicaService(ElicaService):
"""
Тестовая версия ElicaService.
Отличие только одно:
используется отдельный MQTT client_id,
чтобы не конфликтовать с запущенным
ClimatController.
"""
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-elica-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
"""
Ждём полноценного подключения Elica:
MQTT + ESP32 online + обратная связь.
"""
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready.\n"
f"mqtt_connected="
f"{state.mqtt_connected}\n"
f"device_online="
f"{state.device_online}\n"
f"feedback_ready="
f"{service.feedback_ready}\n"
f"missing_feedback_inputs="
f"{service.missing_feedback_inputs}"
)
await asyncio.sleep(0.1)
async def wait_for_elica_change(
service: ElicaService,
*,
power: bool,
speed: int,
timer: bool,
):
"""
Ждём реального ручного изменения Elica.
ВАЖНО:
потеря MQTT, offline ESP32 или потеря
feedback НЕ считаются ручным изменением.
"""
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_CHANGE_TIMEOUT
)
while True:
state = service.state
# ----------------------------------------------
# Если связь временно потеряна,
# состояние logical_state использовать нельзя.
#
# Иначе OFF/0 после disconnect можно ошибочно
# принять за ручное выключение Elica.
# ----------------------------------------------
ready = (
state.mqtt_connected
and state.device_online
and service.feedback_ready
)
if ready:
logical = service.logical_state
changed = (
logical.power != power
or logical.speed != speed
or logical.timer != timer
)
if changed:
return logical
if loop.time() >= deadline:
raise RuntimeError(
"No real Elica change detected "
f"within "
f"{ELICA_CHANGE_TIMEOUT} seconds"
)
await asyncio.sleep(0.1)
async def main() -> None:
# --------------------------------------------------
# Запускаем только тестовый ElicaService.
#
# Tion, Qingping, FastAPI и Schedule
# здесь не участвуют.
# --------------------------------------------------
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
# --------------------------------------------------
# Ждём реальную ESP32 Elica.
# --------------------------------------------------
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
# --------------------------------------------------
# Читаем текущее состояние.
# --------------------------------------------------
elica = service.logical_state
print()
print(
"Real Elica:",
{
"power": elica.power,
"speed": elica.speed,
"timer": elica.timer,
},
)
# --------------------------------------------------
# Загружаем Auto Assist.
# --------------------------------------------------
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# --------------------------------------------------
# Имитируем:
#
# Tion AUTO выбрал скорость 4.
#
# По текущей таблице:
# Tion 4 -> Elica 1.
# --------------------------------------------------
target = assist.set_tion_speed(
TION_SPEED
)
print()
print(
"Tion AUTO speed:",
TION_SPEED,
)
print(
"Elica target:",
target,
)
print()
print(
"Before observe:",
assist.status(),
)
# --------------------------------------------------
# Передаём исходное реальное состояние Elica.
# --------------------------------------------------
assist.observe_elica(
power=elica.power,
speed=elica.speed,
timer=elica.timer,
)
print(
"After observe:",
assist.status(),
)
# --------------------------------------------------
# Запоминаем именно подтверждённое состояние.
# --------------------------------------------------
initial_power = elica.power
initial_speed = elica.speed
initial_timer = elica.timer
print()
print(
"Now change Elica manually."
)
print(
"Change speed, turn it on/off "
"or enable Timer."
)
print(
"The test is waiting for "
"REAL MQTT feedback..."
)
# --------------------------------------------------
# Здесь тест ждёт физического изменения Elica.
# Disconnect теперь изменение не имитирует.
# --------------------------------------------------
changed = await wait_for_elica_change(
service,
power=initial_power,
speed=initial_speed,
timer=initial_timer,
)
print()
print(
"Elica changed:",
{
"power": changed.power,
"speed": changed.speed,
"timer": changed.timer,
},
)
# --------------------------------------------------
# Передаём ручное изменение Auto Assist.
# --------------------------------------------------
assist.observe_elica(
power=changed.power,
speed=changed.speed,
timer=changed.timer,
)
print()
print(
"After manual change:",
assist.status(),
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,335 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
ELICA_CHANGE_TIMEOUT = 60.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-elica-owned-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready"
)
await asyncio.sleep(0.1)
async def wait_for_elica_change(
service: ElicaService,
*,
power: bool,
speed: int,
timer: bool,
):
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_CHANGE_TIMEOUT
)
while True:
state = service.state
ready = (
state.mqtt_connected
and state.device_online
and service.feedback_ready
)
if ready:
logical = service.logical_state
if (
logical.power != power
or logical.speed != speed
or logical.timer != timer
):
return logical
if loop.time() >= deadline:
raise RuntimeError(
"No real Elica change detected "
f"within {ELICA_CHANGE_TIMEOUT} seconds"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
elica = service.logical_state
print()
print(
"Current Elica:",
{
"power": elica.power,
"speed": elica.speed,
"timer": elica.timer,
},
)
# Для этого теста Elica должна быть
# уже включена на скорости 1, 2 или 3.
if (
not elica.power
or elica.speed not in (1, 2, 3)
):
raise RuntimeError(
"Before starting this test, "
"manually turn Elica on "
"at speed 1, 2 or 3"
)
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# Находим скорость Tion, которой
# соответствует текущая скорость Elica.
tion_speed = None
for (
candidate_tion_speed,
candidate_elica_speed,
) in config.elica_assist.speed_map:
if (
candidate_elica_speed
== elica.speed
):
tion_speed = (
candidate_tion_speed
)
break
if tion_speed is None:
raise RuntimeError(
"Current Elica speed is not "
"present in elica_assist.speed_map"
)
# --------------------------------------------------
# Имитируем:
#
# Tion AUTO потребовал такую скорость Elica,
# и автоматика якобы успешно её установила.
# --------------------------------------------------
target = assist.set_tion_speed(
tion_speed
)
assist.mark_owned(
elica.speed
)
print()
print(
"Tion AUTO speed:",
tion_speed,
)
print(
"Elica target:",
target,
)
print(
"Assist after mark_owned:",
assist.status(),
)
# --------------------------------------------------
# Передаём совпадающую обратную связь.
#
# OWNED должен сохраниться.
# --------------------------------------------------
assist.observe_elica(
power=elica.power,
speed=elica.speed,
timer=elica.timer,
)
print()
print(
"After matching feedback:",
assist.status(),
)
initial_power = elica.power
initial_speed = elica.speed
initial_timer = elica.timer
print()
print(
"Now change Elica manually."
)
print(
"For example, change its speed."
)
print(
"The test is waiting for "
"REAL MQTT feedback..."
)
changed = await wait_for_elica_change(
service,
power=initial_power,
speed=initial_speed,
timer=initial_timer,
)
print()
print(
"Elica changed:",
{
"power": changed.power,
"speed": changed.speed,
"timer": changed.timer,
},
)
# --------------------------------------------------
# Теперь Auto Assist должен увидеть,
# что фактическое состояние больше
# не совпадает с expected_speed.
# --------------------------------------------------
assist.observe_elica(
power=changed.power,
speed=changed.speed,
timer=changed.timer,
)
print()
print(
"After manual intervention:",
assist.status(),
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,375 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-elica-release-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
state = controller.state
print()
print(
"Initial Elica:",
{
"power": state.power,
"speed": state.speed,
"timer": state.timer,
},
)
if state.power:
raise RuntimeError(
"Elica must be OFF before this test"
)
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# --------------------------------------------------
# ЭТАП 1
#
# Tion AUTO = 4
# Elica target = 1
# Получаем OWNED.
# --------------------------------------------------
target = assist.set_tion_speed(
4
)
print()
print(
"Tion AUTO speed:",
4,
)
print(
"Elica target:",
target,
)
if target != 1:
raise RuntimeError(
f"Expected target 1, got {target}"
)
assist.observe_elica(
power=state.power,
speed=state.speed,
timer=state.timer,
)
result = await controller.set_speed(
target
)
assist.mark_owned(
result.speed
)
assist.observe_elica(
power=result.power,
speed=result.speed,
timer=result.timer,
)
print()
print(
"Elica acquired:",
{
"power": result.power,
"speed": result.speed,
"timer": result.timer,
},
)
print(
"Assist:",
assist.status(),
)
if assist.mode.value != "owned":
raise RuntimeError(
"Assist did not enter OWNED"
)
# --------------------------------------------------
# ЭТАП 2
#
# Tion AUTO падает до 3.
#
# target_speed должен стать None.
# --------------------------------------------------
target = assist.set_tion_speed(
3
)
print()
print(
"Tion AUTO speed:",
3,
)
print(
"Elica target:",
target,
)
if target is not None:
raise RuntimeError(
"Expected no Elica target "
"at Tion speed 3"
)
# --------------------------------------------------
# Перед выключением обязательно ещё раз
# проверяем фактическое состояние.
#
# Если оно уже не совпадает с expected_speed,
# значит пользователь вмешался.
# --------------------------------------------------
current = controller.state
print()
print(
"Elica before release:",
{
"power": current.power,
"speed": current.speed,
"timer": current.timer,
},
)
print(
"Assist before release:",
assist.status(),
)
assist.observe_elica(
power=current.power,
speed=current.speed,
timer=current.timer,
)
# После проверки мы всё ещё должны
# владеть Elica.
if assist.mode.value != "owned":
raise RuntimeError(
"Auto Assist lost ownership "
"before release. "
"Elica will NOT be switched off."
)
expected = assist.expected_speed
if (
not current.power
or current.speed != expected
or current.timer
):
raise RuntimeError(
"Actual Elica state does not match "
"the state owned by Auto Assist"
)
# --------------------------------------------------
# ПЕРВОЕ АВТОМАТИЧЕСКОЕ ВЫКЛЮЧЕНИЕ.
# --------------------------------------------------
print()
print(
"AUTO ASSIST IS NOW GOING TO "
"TURN ELICA OFF"
)
result_off = await controller.power_off()
print()
print(
"Confirmed Elica:",
{
"power": result_off.power,
"speed": result_off.speed,
"timer": result_off.timer,
},
)
# После успешного выключения
# текущий автоматический цикл завершён.
assist.reset()
print(
"Assist after release:",
assist.status(),
)
# --------------------------------------------------
# ПРОВЕРКИ
# --------------------------------------------------
if result_off.power:
raise RuntimeError(
"Elica did not switch off"
)
if assist.mode.value != "idle":
raise RuntimeError(
"Assist did not return to IDLE"
)
if assist.expected_speed is not None:
raise RuntimeError(
"expected_speed was not cleared"
)
print()
print(
"TEST PASSED"
)
print(
"Auto Assist acquired Elica, "
"then released and switched it off "
"when Tion dropped to speed 3."
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,316 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-elica-speed-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready"
)
await asyncio.sleep(0.1)
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
state = controller.state
print()
print(
"Initial Elica:",
{
"power": state.power,
"speed": state.speed,
"timer": state.timer,
},
)
# Для этого теста Elica должна быть выключена.
if state.power:
raise RuntimeError(
"Elica must be OFF before this test"
)
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# --------------------------------------------------
# Этап 1:
# Tion AUTO = 4 -> Elica должна стать 1
# --------------------------------------------------
target_1 = assist.set_tion_speed(4)
print()
print(
"Tion AUTO speed:",
4,
)
print(
"Elica target:",
target_1,
)
if target_1 != 1:
raise RuntimeError(
f"Expected Elica target 1, got {target_1}"
)
assist.observe_elica(
power=state.power,
speed=state.speed,
timer=state.timer,
)
result_1 = await controller.set_speed(
target_1
)
assist.mark_owned(
result_1.speed
)
assist.observe_elica(
power=result_1.power,
speed=result_1.speed,
timer=result_1.timer,
)
print()
print(
"After first acquire:",
{
"power": result_1.power,
"speed": result_1.speed,
"timer": result_1.timer,
},
)
print(
"Assist:",
assist.status(),
)
if assist.mode.value != "owned":
raise RuntimeError(
"Assist did not enter OWNED"
)
# --------------------------------------------------
# Этап 2:
# Tion AUTO меняется 4 -> 5
# Значит Elica 1 -> 2
# --------------------------------------------------
target_2 = assist.set_tion_speed(5)
print()
print(
"Tion AUTO speed:",
5,
)
print(
"New Elica target:",
target_2,
)
if target_2 != 2:
raise RuntimeError(
f"Expected Elica target 2, got {target_2}"
)
# --------------------------------------------------
# Пока владельцем остаётся автоматика,
# поэтому ей разрешено изменить скорость.
# --------------------------------------------------
result_2 = await controller.set_speed(
target_2
)
print()
print(
"Confirmed Elica after speed change:",
{
"power": result_2.power,
"speed": result_2.speed,
"timer": result_2.timer,
},
)
# Обновляем expected_speed только после
# подтверждённой команды.
assist.mark_owned(
result_2.speed
)
assist.observe_elica(
power=result_2.power,
speed=result_2.speed,
timer=result_2.timer,
)
print()
print(
"Assist after speed change:",
assist.status(),
)
if assist.mode.value != "owned":
raise RuntimeError(
"Assist lost OWNED after "
"automatic speed change"
)
if result_2.speed != 2:
raise RuntimeError(
"Elica did not reach speed 2"
)
print()
print(
"TEST PASSED"
)
print(
"Auto Assist changed Elica "
"from speed 1 to speed 2 "
"and kept OWNED."
)
print(
"Turn Elica off manually after the test."
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,448 @@
import asyncio
import os
import paho.mqtt.client as mqtt
from app.auto.config import load_auto_config
from app.auto.elica_assist import ElicaAutoAssistState
from app.elica import (
ElicaConfig,
ElicaController,
ElicaService,
)
from app.my_dataclasses import (
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
)
AUTO_CONFIG = "config/auto.yaml"
ELICA_READY_TIMEOUT = 15.0
class TestElicaService(ElicaService):
async def start(self) -> None:
if self._running:
return
client_id = (
f"climatcontroller-elica-down-test-{os.getpid()}"
)
print(
"Test MQTT client_id:",
client_id,
)
client = mqtt.Client(
callback_api_version=(
mqtt.CallbackAPIVersion.VERSION2
),
client_id=client_id,
)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.reconnect_delay_set(
min_delay=1,
max_delay=30,
)
self._client = client
self._running = True
client.connect_async(
self._config.mqtt_host,
self._config.mqtt_port,
keepalive=60,
)
client.loop_start()
async def wait_for_elica(
service: ElicaService,
) -> None:
loop = asyncio.get_running_loop()
deadline = (
loop.time()
+ ELICA_READY_TIMEOUT
)
while True:
state = service.state
if (
state.mqtt_connected
and state.device_online
and service.feedback_ready
):
return
if loop.time() >= deadline:
raise RuntimeError(
"Elica did not become ready"
)
await asyncio.sleep(0.1)
async def set_speed_with_trace(
controller: ElicaController,
service: ElicaService,
target_speed: int,
):
"""
Выполняет обычный controller.set_speed(),
параллельно записывая фактические скорости Elica.
Это позволяет увидеть реальный цикл:
2 -> 3 -> 4 -> 1
"""
path: list[int] = []
initial = service.logical_state
if (
initial.power
and 1 <= initial.speed <= 4
):
path.append(initial.speed)
task = asyncio.create_task(
controller.set_speed(
target_speed
)
)
while not task.done():
state = service.logical_state
if (
state.power
and 1 <= state.speed <= 4
):
if (
not path
or path[-1] != state.speed
):
path.append(
state.speed
)
await asyncio.sleep(0.02)
result = await task
# На всякий случай фиксируем конечное
# подтверждённое состояние.
if (
result.power
and 1 <= result.speed <= 4
and (
not path
or path[-1] != result.speed
)
):
path.append(
result.speed
)
return result, path
async def main() -> None:
service = TestElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
controller = ElicaController(
service
)
print(
"Starting Elica service..."
)
await service.start()
try:
print(
f"Connecting to MQTT "
f"{ELICA_MQTT_HOST}:"
f"{ELICA_MQTT_PORT}..."
)
await wait_for_elica(
service
)
print(
"Elica connected and "
"feedback ready"
)
state = controller.state
print()
print(
"Initial Elica:",
{
"power": state.power,
"speed": state.speed,
"timer": state.timer,
},
)
# Для чистоты начинаем с OFF.
if state.power:
raise RuntimeError(
"Elica must be OFF before this test"
)
config = load_auto_config(
AUTO_CONFIG
)
assist = ElicaAutoAssistState(
config.elica_assist
)
# ==================================================
# ЭТАП 1
#
# Tion AUTO = 5
# Elica target = 2
#
# Получаем OWNED на скорости 2.
# ==================================================
target_2 = assist.set_tion_speed(
5
)
print()
print(
"Tion AUTO speed:",
5,
)
print(
"Elica target:",
target_2,
)
if target_2 != 2:
raise RuntimeError(
f"Expected Elica target 2, "
f"got {target_2}"
)
assist.observe_elica(
power=state.power,
speed=state.speed,
timer=state.timer,
)
result_2 = await controller.set_speed(
target_2
)
assist.mark_owned(
result_2.speed
)
assist.observe_elica(
power=result_2.power,
speed=result_2.speed,
timer=result_2.timer,
)
print()
print(
"Elica acquired:",
{
"power": result_2.power,
"speed": result_2.speed,
"timer": result_2.timer,
},
)
print(
"Assist:",
assist.status(),
)
if (
assist.mode.value != "owned"
or result_2.speed != 2
):
raise RuntimeError(
"Failed to acquire Elica "
"at speed 2"
)
# ==================================================
# ЭТАП 2
#
# Tion AUTO падает:
#
# 5 -> 4
#
# Новая цель Elica:
#
# 2 -> 1
#
# Но физически Elica должна пройти:
#
# 2 -> 3 -> 4 -> 1
# ==================================================
target_1 = assist.set_tion_speed(
4
)
print()
print(
"Tion AUTO speed:",
4,
)
print(
"New Elica target:",
target_1,
)
print(
"Assist before speed change:",
assist.status(),
)
if target_1 != 1:
raise RuntimeError(
f"Expected Elica target 1, "
f"got {target_1}"
)
# ВАЖНО:
#
# Здесь НЕ вызываем observe_elica()
# во время промежуточных скоростей.
#
# 3 и 4 являются частью нашей
# собственной команды set_speed(1),
# а не действиями пользователя.
result_1, speed_path = (
await set_speed_with_trace(
controller,
service,
target_1,
)
)
print()
print(
"Observed speed path:",
speed_path,
)
print(
"Confirmed Elica:",
{
"power": result_1.power,
"speed": result_1.speed,
"timer": result_1.timer,
},
)
# Только ПОСЛЕ завершения всей нашей
# последовательности обновляем владение.
assist.mark_owned(
result_1.speed
)
assist.observe_elica(
power=result_1.power,
speed=result_1.speed,
timer=result_1.timer,
)
print()
print(
"Assist after speed change:",
assist.status(),
)
# ==================================================
# ПРОВЕРКИ
# ==================================================
if speed_path != [2, 3, 4, 1]:
raise RuntimeError(
"Unexpected Elica speed path: "
f"{speed_path}; "
"expected [2, 3, 4, 1]"
)
if result_1.speed != 1:
raise RuntimeError(
"Elica did not reach speed 1"
)
if assist.mode.value != "owned":
raise RuntimeError(
"Auto Assist lost OWNED "
"during automatic speed change"
)
if assist.expected_speed != 1:
raise RuntimeError(
"Auto Assist expected_speed "
"was not updated to 1"
)
print()
print(
"TEST PASSED"
)
print(
"Automatic Elica transition:"
)
print(
"2 -> 3 -> 4 -> 1"
)
print(
"Auto Assist kept OWNED."
)
print()
print(
"Turn Elica off manually "
"after the test."
)
finally:
print()
print(
"Stopping Elica service..."
)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
-24
View File
@@ -561,15 +561,9 @@ class ScheduleService:
if resolution.auto_active:
# В режиме AUTO скорость принадлежит
# AutoController.
#
# Остальные параметры расписания
# (power, heater, temperature, mode...)
# должны продолжать работать.
settings = replace(
settings,
speed=None,
heater=None,
target_temp=None,
)
await self._apply_settings(settings)
@@ -598,24 +592,6 @@ class ScheduleService:
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:
await self._tion.execute(
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
def heater_calls(calls):
def temperature_calls(calls):
return [
call
for call in calls
@@ -142,6 +142,7 @@ def heater_calls(calls):
"heater_on",
"heater_off",
"set_heater",
"set_target_temperature",
}
]
@@ -178,7 +179,12 @@ async def test_auto_does_not_control_heater():
# 09:30
#
# Обычный SET.
# heater=on должен принадлежать ScheduleService.
#
# ScheduleService хранит желаемое heater=on,
# но физически heater управлять НЕ должен.
#
# Физический heater будет принадлежать
# единому температурному регулятору.
# --------------------------------------------------
await process_at(
@@ -198,12 +204,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls,
)
calls = heater_calls(
calls = temperature_calls(
tion.controller.calls
)
assert calls != [], (
"SET must control heater"
assert calls == [], (
"ScheduleService must not control "
"heater or target temperature during SET"
)
tion.controller.calls.clear()
@@ -263,13 +270,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls,
)
calls = heater_calls(
calls = temperature_calls(
tion.controller.calls
)
assert calls == [], (
"ScheduleService must not control "
"heater during AUTO"
"heater or target temperature during AUTO"
)
tion.controller.calls.clear()
@@ -298,13 +305,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls,
)
calls = heater_calls(
calls = temperature_calls(
tion.controller.calls
)
assert calls != [], (
"ScheduleService must regain heater "
"control after AUTO"
assert calls == [], (
"ScheduleService must not control "
"heater or target temperature after AUTO"
)
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())
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+109
View File
@@ -0,0 +1,109 @@
/* Elica-specific layout only.
IMPORTANT: body/.widget backgrounds are intentionally NOT overridden here.
Both Tion and Elica receive the exact same material from aeroglass-widget.css. */
.hood-icon svg { width: 1.75rem; height: 1.75rem; filter: drop-shadow(0 0 5px rgba(20,123,213,.18)); }
.exhaust-widget-speed { min-height: 12.2rem; }
.exhaust-widget-hero { grid-template-columns: 3.1rem 1fr 3.1rem; }
.hero-spacer { width: 3.1rem; height: 3.1rem; }
.exhaust-widget-segments { grid-template-columns: repeat(4, 1fr); }
.exhaust-widget-labels { grid-template-columns: repeat(4, 1fr); }
.external-fan-card { position: relative; overflow: hidden; }
.external-fan-card::after {
content: "";
position: absolute;
z-index: 0;
width: 10rem;
height: 10rem;
right: -4.4rem;
bottom: -5.4rem;
border-radius: 50%;
background: var(--blue-halo);
opacity: .16;
filter: blur(34px);
pointer-events: none;
}
.external-fan-card > * { position: relative; z-index: 1; }
.external-fan-card[data-on="true"] .fan-glyph { animation: exhaust-widget-spin 1.35s linear infinite; }
@keyframes exhaust-widget-spin { to { transform: rotate(360deg); } }
.exhaust-actions { display: grid; gap: .55rem; }
.exhaust-action-row { display: flex; align-items: center; justify-content: space-between; gap: .65rem; }
.exhaust-action-copy { min-width: 0; display: flex; align-items: center; gap: .55rem; }
.exhaust-action-copy > span { min-width: 0; display: grid; gap: .08rem; }
.exhaust-action-copy b { font-size: .78rem; }
.exhaust-action-copy small { color: var(--widget-muted); font-size: .58rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.exhaust-action-copy .section-icon, .bulb-icon { width: 1.55rem; height: 1.55rem; flex: 0 0 auto; }
.bulb-icon { color: #d59d17; filter: drop-shadow(0 0 5px rgba(213,157,23,.15)); }
.exhaust-divider { display: block; width: 100%; height: 1px; background: linear-gradient(90deg, transparent, var(--tile-edge-soft) 12%, var(--tile-edge-soft) 88%, transparent); }
.glass-switch.compact { width: 5.1rem; min-height: 2.45rem; font-size: .78rem; }
.glass-action {
min-height: 2.45rem;
padding: .5rem .68rem;
flex: 0 0 auto;
border: 1px solid var(--tile-edge);
border-radius: .76rem;
color: var(--widget-ink);
background: radial-gradient(circle at 20% -30%, rgba(255,255,255,.46), transparent 48%), linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
cursor: pointer;
font-size: .61rem;
font-weight: 760;
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
transition: transform .15s ease, filter .15s ease;
}
.glass-action:hover { transform: translateY(-1px); filter: brightness(1.05); }
.glass-action:active { transform: scale(.98); }
:root[data-theme="dark"] .glass-action { border-color: rgba(193,228,245,.22); background: radial-gradient(circle at 20% -30%, rgba(208,243,255,.09), transparent 48%), linear-gradient(145deg, rgba(77,112,133,.21), rgba(20,44,59,.26)); }
.exhaust-widget .open-panel svg { width: 1.45rem; height: 1.45rem; }
:root[data-widget-layout="horizontal"] .exhaust-widget {
width: min(100%, 64rem);
grid-template-columns: minmax(0, 1.45fr) minmax(14rem, .92fr) minmax(15rem, .86fr);
grid-template-areas:
"header header header"
"speed switches actions"
"open open open";
}
:root[data-widget-layout="horizontal"] .exhaust-widget-header { grid-area: header; }
:root[data-widget-layout="horizontal"] .exhaust-widget-speed { grid-area: speed; min-height: 8.8rem; }
:root[data-widget-layout="horizontal"] .exhaust-switch-grid {
grid-area: switches;
min-width: 0;
display: grid !important;
grid-template-columns: 1fr;
grid-template-rows: repeat(2, minmax(0, 1fr));
gap: .48rem;
align-content: stretch;
}
:root[data-widget-layout="horizontal"] .exhaust-switch-grid > .switch-card {
grid-area: auto !important;
min-width: 0;
min-height: 4.15rem;
padding: .55rem .62rem;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: .45rem;
}
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .switch-title,
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .switch-title > span { min-width: 0; }
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .glass-switch { min-height: 2.45rem; width: 4.7rem; }
:root[data-widget-layout="horizontal"] .exhaust-actions { grid-area: actions; align-content: center; padding: .62rem .68rem; }
:root[data-widget-layout="horizontal"] .exhaust-action-copy small { max-width: 8.5rem; }
:root[data-widget-layout="horizontal"] .open-panel { grid-area: open; }
:root[data-widget-layout="horizontal"] .exhaust-widget-hero { margin: .45rem 0 .35rem; }
@media (max-width: 799px) {
:root[data-widget-layout="vertical"] .exhaust-widget { width: min(100%, 31.5rem); }
}
@media (max-width: 420px) {
.exhaust-action-copy small { max-width: 10rem; }
.glass-action { padding-inline: .55rem; }
}
+161
View File
@@ -0,0 +1,161 @@
/* Elica uses the same aeroglass material system as the Tion panel.
This file only defines the Elica-specific layout and controls. */
.exhaust-panel {
width: min(100%, 78rem);
min-height: auto;
display: grid;
gap: .75rem;
}
.exhaust-header { padding-bottom: .25rem; }
.exhaust-identity { min-width: 0; }
.exhaust-identity .identity-copy { min-width: 0; }
.exhaust-identity .title-row { display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; }
.exhaust-identity .identity-copy > small { display: block; margin-top: .28rem; color: var(--panel-muted); font-size: .7rem; }
.hood-mark {
width: 3.25rem;
height: 3.25rem;
padding: .68rem;
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 1rem;
color: #147bd5;
}
.hood-mark svg { width: 100%; height: 100%; filter: drop-shadow(0 0 6px rgba(20,123,213,.2)); }
.exhaust-badge { min-width: 19rem; }
.exhaust-badge svg { width: 2.25rem; height: 2.25rem; }
.panel-link { text-decoration: none; }
.exhaust-primary {
display: grid;
grid-template-columns: minmax(19rem, 1.42fr) repeat(2, minmax(13rem, .82fr));
grid-template-areas:
"speed power fan"
"speed action action";
gap: .75rem;
}
.exhaust-speed-card { grid-area: speed; min-height: 20rem; }
.exhaust-switch-card { min-height: 9.6rem; }
.power-card { grid-area: power; }
.exhaust-fan-card { grid-area: fan; }
.exhaust-action-card { grid-area: action; min-height: 9.6rem; justify-content: center; gap: .75rem; }
.exhaust-hero-control {
grid-template-columns: 3rem 1fr 3rem;
margin: auto 0 .9rem;
}
.hero-spacer { width: 3rem; height: 3rem; }
.exhaust-speed-segments { grid-template-columns: repeat(4, 1fr); gap: .2rem; }
.exhaust-speed-labels { grid-template-columns: repeat(4, 1fr); }
.exhaust-speed-segments button.active { transform: translateY(-1px); }
.exhaust-fan-card::after {
content: "";
position: absolute;
z-index: 0;
width: 13rem;
height: 13rem;
right: -5rem;
bottom: -7rem;
border-radius: 50%;
pointer-events: none;
filter: blur(44px);
background: var(--blue-halo);
opacity: .17;
}
.exhaust-fan-card > * { position: relative; z-index: 1; }
.exhaust-fan-card[data-on="true"] .fan-glyph { animation: exhaust-fan-spin 1.35s linear infinite; }
@keyframes exhaust-fan-spin { to { transform: rotate(360deg); } }
.action-row { display: flex; align-items: center; justify-content: space-between; gap: .9rem; }
.action-copy { display: flex; align-items: center; gap: .7rem; min-width: 0; }
.action-copy h2 { margin: 0; font-size: 1rem; line-height: 1.2; }
.action-copy p { margin: .18rem 0 0; color: var(--panel-muted); font-size: .68rem; line-height: 1.35; }
.bulb-icon { width: 2.1rem; height: 2.1rem; padding: .16rem; flex: 0 0 auto; color: #d59d17; filter: drop-shadow(0 0 6px rgba(213,157,23,.18)); }
.glass-divider { height: 1px; background: linear-gradient(90deg, transparent, var(--tile-line-soft) 12%, var(--tile-line-soft) 88%, transparent); }
.compact-switch {
width: 6.2rem;
min-height: 3.25rem;
flex: 0 0 auto;
font-size: 1.05rem;
}
.aero-button {
min-height: 3rem;
padding: .65rem .95rem;
flex: 0 0 auto;
border: 1px solid var(--tile-line);
border-radius: .9rem;
color: var(--panel-ink);
background:
radial-gradient(circle at 20% -25%, rgba(255,255,255,.48), transparent 48%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
backdrop-filter: blur(14px) saturate(122%);
-webkit-backdrop-filter: blur(14px) saturate(122%);
cursor: pointer;
font-size: .72rem;
font-weight: 760;
transition: transform .15s ease, filter .15s ease, box-shadow .15s ease;
}
.aero-button:hover { transform: translateY(-1px); filter: brightness(1.05); }
.aero-button:active { transform: scale(.98); }
:root[data-theme="dark"] .aero-button { border-color: rgba(193,228,245,.24); background: radial-gradient(circle at 20% -25%, rgba(208,243,255,.1), transparent 48%), linear-gradient(145deg, rgba(77,112,133,.22), rgba(20,44,59,.27)); }
.exhaust-status-section { margin-top: 0; }
.status-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .55rem; }
.status-item { min-height: 5rem; padding: .75rem .85rem; border-radius: .85rem; display: grid; align-content: center; gap: .25rem; }
.status-item span { color: var(--panel-muted); font-size: .58rem; text-transform: uppercase; letter-spacing: .07em; font-weight: 800; }
.status-item strong { font-size: .78rem; }
.status-item strong.good { color: #0a8a50; }
.status-item strong.warn { color: #bc6b16; }
.status-item strong.bad { color: #bd4050; }
:root[data-theme="dark"] .status-item strong.good { color: #7de5ad; }
:root[data-theme="dark"] .status-item strong.warn { color: #ffc078; }
:root[data-theme="dark"] .status-item strong.bad { color: #ff98a2; }
.diagnostic-note { margin: .6rem .25rem .05rem; color: var(--panel-muted); font-size: .63rem; }
.pending { opacity: .72; }
button:disabled { cursor: wait; }
@media (max-width: 980px) {
.exhaust-badge { display: none; }
.exhaust-primary {
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-areas:
"speed speed"
"power fan"
"action action";
}
.exhaust-speed-card { min-height: 16rem; }
}
@media (max-width: 640px) {
.exhaust-panel { gap: .6rem; }
.exhaust-header { align-items: flex-start; }
.exhaust-identity .identity-copy > small { display: none; }
.hood-mark { width: 2.8rem; height: 2.8rem; border-radius: .9rem; }
.exhaust-primary {
grid-template-columns: 1fr;
grid-template-areas: "speed" "power" "fan" "action";
}
.exhaust-speed-card { min-height: 14.5rem; }
.exhaust-switch-card { min-height: 8.2rem; }
.status-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.action-row { gap: .55rem; }
.action-copy p { font-size: .62rem; }
}
@media (max-width: 430px) {
.header-tools { gap: .35rem; }
.panel-link { display: none; }
.exhaust-speed-card, .exhaust-switch-card, .exhaust-action-card { padding: .8rem; }
.compact-switch { width: 5.35rem; min-height: 2.8rem; }
.aero-button { padding-inline: .7rem; }
}
@@ -5,9 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Elica — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/widget.css">
<link rel="stylesheet" href="/ui/static/css/exhaust-widget.css">
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/elica-widget.css?v=20260927-1">
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
@@ -80,6 +80,6 @@
<span>Открыть панель вытяжки</span><b aria-hidden="true">↗</b>
</button>
</main>
<script type="module" src="/ui/static/js/exhaust-widget.js"></script>
<script type="module" src="/ui/static/js/elica-widget.js?v=20260927-1"></script>
</body>
</html>
+5 -5
View File
@@ -5,9 +5,9 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Elica — управление вытяжкой</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/panel.css">
<link rel="stylesheet" href="/ui/static/css/exhaust.css">
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/elica.css?v=20260927-1">
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
@@ -31,7 +31,7 @@
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><strong>Вытяжная вентиляция</strong><small>Управление Elica и внешним вентилятором</small></span>
</div>
<a class="icon-button panel-link" href="/ui/panel" title="Открыть Tion 4S" aria-label="Открыть Tion 4S">
<a class="icon-button panel-link" href="/ui/tion" title="Открыть Tion 4S" aria-label="Открыть Tion 4S">
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#wind"></use></svg>
</a>
<button id="refresh-button" class="icon-button" type="button" title="Обновить данные">
@@ -113,6 +113,6 @@
</section>
</main>
<script type="module" src="/ui/static/js/exhaust.js"></script>
<script type="module" src="/ui/static/js/elica.js?v=20260927-1"></script>
</body>
</html>
+4 -2
View File
@@ -179,7 +179,9 @@ export const api = {
export function configureTheme(button) {
const allowed = ["auto", "light", "dark"];
const explicit = query.get("theme");
let mode = allowed.includes(explicit) ? explicit : (localStorage.getItem("tion-theme") || "auto");
let mode = allowed.includes(explicit)
? explicit
: (localStorage.getItem("climate-theme") || localStorage.getItem("tion-theme") || "auto");
const apply = () => {
const dark = mode === "dark" || (mode === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
@@ -196,7 +198,7 @@ export function configureTheme(button) {
if (button) button.addEventListener("click", () => {
mode = allowed[(allowed.indexOf(mode) + 1) % allowed.length];
localStorage.setItem("tion-theme", mode);
localStorage.setItem("climate-theme", mode);
apply();
});
+190
View File
@@ -0,0 +1,190 @@
import { configureTheme, showToast } from "./api.js";
const requestedLayout = new URLSearchParams(window.location.search).get("layout");
const layoutMode = ["horizontal", "vertical"].includes(requestedLayout) ? requestedLayout : null;
const wideLayout = window.matchMedia("(min-width: 800px)");
function applyLayout() {
document.documentElement.dataset.widgetLayout = layoutMode || (wideLayout.matches ? "horizontal" : "vertical");
}
applyLayout();
wideLayout.addEventListener("change", () => !layoutMode && applyLayout());
const $ = selector => document.querySelector(selector);
const $$ = selector => [...document.querySelectorAll(selector)];
const themeMode = configureTheme($("#theme-button"));
let state = null;
let busy = false;
let polling = false;
function setPill(label, tone) {
const element = $("#connection");
element.textContent = label;
element.className = `pill ${tone}`;
}
function drawToggle(selector, active, label = null) {
const button = $(selector);
const enabled = Boolean(active);
button.setAttribute("aria-pressed", String(enabled));
button.textContent = label || (enabled ? "ON" : "OFF");
}
function ready(status) {
return Boolean(status?.running && status?.mqtt_connected && status?.device_online);
}
function feedbackReady(status) {
return ready(status) && Boolean(status?.feedback_ready);
}
function drawSpeed(value) {
const speed = Math.max(0, Math.min(4, Number(value) || 0));
const output = $("#speed");
output.textContent = speed || "—";
output.classList.remove("skeleton");
$$('[data-speed]').forEach(button => {
const segment = Number(button.dataset.speed);
button.classList.toggle("active", speed > 0 && segment <= speed);
button.setAttribute("aria-pressed", String(segment === speed));
});
}
function render(status) {
state = status;
const elica = status?.elica || {};
const external = status?.external_fan || {};
const controllerOnline = ready(status);
const panelOnline = feedbackReady(status);
if (!status?.running) setPill("Сервис остановлен", "bad");
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
else if (!status?.device_online) setPill("ESP32 offline", "bad");
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
else setPill("Online", "good");
$("#header-detail").textContent = elica.power
? `Вытяжка включена${elica.speed ? ` · скорость ${elica.speed}` : ""}`
: "Вытяжная вентиляция";
drawSpeed(elica.speed);
$("#speed-note").textContent = panelOnline
? (elica.power ? "Фактическая ступень по индикаторам Elica" : "Выбор скорости включит вытяжку")
: "Ждём синхронизацию панели Elica";
drawToggle("#power-toggle", elica.power);
$("#power-detail").textContent = elica.power ? "Включена" : "Выключена";
if (external.available && typeof external.on === "boolean") {
drawToggle("#external-fan-toggle", external.on);
$("#external-fan-card").dataset.on = String(external.on);
$("#external-fan-detail").textContent = external.on ? "Работает · NC замкнут" : "Остановлен · NC разомкнут";
} else {
drawToggle("#external-fan-toggle", false, "—");
$("#external-fan-card").dataset.on = "false";
$("#external-fan-detail").textContent = "Ждём OUT5";
}
drawToggle("#timer-toggle", elica.timer);
$("#timer-detail").textContent = elica.timer ? "Активен" : "Выключен";
const hoodDisabled = busy || !panelOnline;
$("#power-toggle").disabled = hoodDisabled;
$$('[data-speed]').forEach(button => { button.disabled = hoodDisabled; });
$("#timer-toggle").disabled = hoodDisabled;
$("#light-toggle").disabled = hoodDisabled;
$("#external-fan-toggle").disabled = busy || !controllerOnline || !external.available;
}
async function request(path, options = {}) {
const response = await fetch(path, {
cache: "no-store",
headers: { Accept: "application/json" },
...options,
});
if (!response.ok) {
let message = `Ошибка ${response.status}`;
try {
const body = await response.json();
if (body?.detail && typeof body.detail === "object") {
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
} else message = body?.detail || body?.message || message;
} catch (_) {}
throw new Error(String(message));
}
return response.json();
}
async function refresh(silent = false) {
if (polling) return;
polling = true;
try { render(await request("/api/elica/status")); }
catch (error) {
setPill("API недоступен", "bad");
if (!silent) showToast(error.message, true);
} finally { polling = false; }
}
async function act(path, source, optimistic = null) {
if (busy) return;
busy = true;
optimistic?.();
if (state) render(state);
source?.setAttribute("disabled", "");
try { render(await request(path, { method: "POST" })); }
catch (error) { showToast(error.message, true); await refresh(true); }
finally {
busy = false;
source?.removeAttribute("disabled");
if (state) render(state);
}
}
$("#power-toggle").addEventListener("click", event => {
const next = !Boolean(state?.elica?.power);
act(`/api/elica/power/${next ? "on" : "off"}`, event.currentTarget, () => {
if (state?.elica) state.elica.power = next;
drawToggle("#power-toggle", next);
});
});
$$('[data-speed]').forEach(button => button.addEventListener("click", () => {
const speed = Number(button.dataset.speed);
act(`/api/elica/speed/${speed}`, button, () => {
if (state?.elica) { state.elica.power = true; state.elica.speed = speed; }
drawSpeed(speed);
});
}));
$("#timer-toggle").addEventListener("click", event => {
const next = !Boolean(state?.elica?.timer);
act(`/api/elica/timer/${next ? "on" : "off"}`, event.currentTarget, () => {
if (state?.elica) state.elica.timer = next;
drawToggle("#timer-toggle", next);
});
});
$("#light-toggle").addEventListener("click", event => {
act("/api/elica/light/toggle", event.currentTarget);
});
$("#external-fan-toggle").addEventListener("click", event => {
const next = !Boolean(state?.external_fan?.on);
act(`/api/elica/external-fan/${next ? "on" : "off"}`, event.currentTarget, () => {
if (state?.external_fan) state.external_fan.on = next;
drawToggle("#external-fan-toggle", next);
$("#external-fan-card").dataset.on = String(next);
});
});
$("#open-panel").addEventListener("click", () => {
const url = new URL("/ui/elica", window.location.origin);
url.searchParams.set("theme", themeMode());
window.open(url.toString(), "_blank", "noopener");
});
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(true); });
refresh();
setInterval(() => !document.hidden && !busy && refresh(true), 1500);
+241
View File
@@ -0,0 +1,241 @@
import { configureTheme, showToast } from "./api.js";
const $ = selector => document.querySelector(selector);
const $$ = selector => [...document.querySelectorAll(selector)];
const connection = $("#connection");
const powerToggle = $("#power-toggle");
const powerCaption = $("#power-caption");
const speedValue = $("#speed-value");
const speedCaption = $("#speed-caption");
const speedButtons = $$("[data-speed]");
const timerToggle = $("#timer-toggle");
const timerCaption = $("#timer-caption");
const lightToggle = $("#light-toggle");
const externalFanToggle = $("#external-fan-toggle");
const externalFanCaption = $("#external-fan-caption");
const externalFanCard = $("#external-fan-card");
const mqttStatus = $("#mqtt-status");
const deviceStatus = $("#device-status");
const feedbackStatus = $("#feedback-status");
const relay5Status = $("#relay5-status");
const diagnosticNote = $("#diagnostic-note");
const updatedAt = $("#updated-at");
const refreshButton = $("#refresh-button");
const themeButton = $("#theme-button");
configureTheme(themeButton);
let latest = null;
let polling = false;
let commandBusy = false;
let refreshTimer = null;
function setTextState(element, text, tone = "") {
element.textContent = text;
element.className = tone;
}
function setPill(text, tone) {
connection.textContent = text;
connection.className = `pill ${tone}`;
}
function setToggle(button, enabled, label = null) {
const isOn = Boolean(enabled);
button.setAttribute("aria-pressed", String(isOn));
const text = button.querySelector("span");
if (text) text.textContent = label || (isOn ? "ON" : "OFF");
else button.textContent = label || (isOn ? "ON" : "OFF");
}
function controllerReady(status) {
return Boolean(
status?.running &&
status?.mqtt_connected &&
status?.device_online
);
}
function hoodReady(status) {
return controllerReady(status) && Boolean(status?.feedback_ready);
}
function render(status) {
latest = status;
const logical = status?.elica || {};
const external = status?.external_fan || {};
const ready = controllerReady(status);
const feedbackReady = hoodReady(status);
if (!status?.running) setPill("Сервис остановлен", "bad");
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
else if (!status?.device_online) setPill("ESP32 offline", "bad");
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
else setPill("Online", "good");
setToggle(powerToggle, logical.power);
powerCaption.textContent = logical.power
? `Включена${logical.speed ? ` · скорость ${logical.speed}` : ""}`
: "Вытяжка выключена";
const speed = Number(logical.speed) || 0;
speedValue.textContent = speed || "—";
speedButtons.forEach(button => {
button.classList.toggle("active", speed > 0 && Number(button.dataset.speed) <= speed);
});
speedCaption.textContent = feedbackReady
? (logical.power ? "Фактическая скорость по индикаторам Elica." : "При выборе скорости вытяжка включится автоматически.")
: "Ждём синхронизацию входов панели Elica.";
setToggle(timerToggle, logical.timer);
timerCaption.textContent = logical.timer
? "Таймер активен · индикатор скорости мигает"
: "Таймер выключен";
if (external.available && typeof external.on === "boolean") {
setToggle(externalFanToggle, external.on);
externalFanCard.dataset.on = String(external.on);
externalFanCaption.textContent = external.on
? "Включён · NC замкнут, OUT5 выключен"
: "Выключен · NC разомкнут, OUT5 включен";
} else {
setToggle(externalFanToggle, false, "—");
externalFanCard.dataset.on = "false";
externalFanCaption.textContent = "Ждём обратную связь OUT5";
}
setTextState(mqttStatus, status?.mqtt_connected ? "Подключён" : "Нет связи", status?.mqtt_connected ? "good" : "bad");
setTextState(deviceStatus, status?.device_online ? "Online" : "Offline", status?.device_online ? "good" : "bad");
setTextState(feedbackStatus, status?.feedback_ready ? "Синхронизирована" : "Ожидание", status?.feedback_ready ? "good" : "warn");
if (external.available) {
setTextState(relay5Status, external.relay_on ? "ON · NC открыт" : "OFF · NC закрыт", external.relay_on ? "warn" : "good");
} else {
setTextState(relay5Status, "Нет данных", "warn");
}
const missing = status?.missing_feedback_inputs || [];
diagnosticNote.textContent = missing.length
? `Не получены входы Elica: ${missing.join(", ")}.`
: "Состояния вытяжки подтверждаются по MQTT и физическим входам ESP32.";
const stamp = status?.last_message_at ? new Date(status.last_message_at) : new Date();
updatedAt.textContent = Number.isNaN(stamp.getTime())
? "—"
: `Обновлено ${stamp.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}`;
const disableHood = commandBusy || !feedbackReady;
powerToggle.disabled = disableHood;
speedButtons.forEach(button => { button.disabled = disableHood; });
timerToggle.disabled = disableHood;
lightToggle.disabled = disableHood;
externalFanToggle.disabled = commandBusy || !ready || !external.available;
document.body.classList.toggle("pending", commandBusy);
}
async function request(path, options = {}) {
const response = await fetch(path, {
cache: "no-store",
headers: { Accept: "application/json" },
...options,
});
if (!response.ok) {
let message = `Ошибка ${response.status}`;
try {
const body = await response.json();
if (body?.detail && typeof body.detail === "object") {
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
} else {
message = body?.detail || body?.message || message;
}
} catch (_) {}
throw new Error(String(message));
}
return response.json();
}
async function refresh({ silent = false } = {}) {
if (polling) return;
polling = true;
try {
render(await request("/api/elica/status"));
} catch (error) {
setPill("API недоступен", "bad");
if (!silent) showToast(error.message, true);
} finally {
polling = false;
}
}
async function command(path, optimistic = null) {
if (commandBusy) return;
commandBusy = true;
if (latest) render(latest);
if (optimistic) optimistic();
try {
const status = await request(path, { method: "POST" });
render(status);
} catch (error) {
showToast(error.message, true);
await refresh({ silent: true });
} finally {
commandBusy = false;
if (latest) render(latest);
}
}
powerToggle.addEventListener("click", () => {
const next = !Boolean(latest?.elica?.power);
command(`/api/elica/power/${next ? "on" : "off"}`, () => {
setToggle(powerToggle, next);
powerCaption.textContent = next ? "Включаем…" : "Выключаем…";
});
});
speedButtons.forEach(button => button.addEventListener("click", () => {
const speed = Number(button.dataset.speed);
command(`/api/elica/speed/${speed}`, () => {
speedValue.textContent = String(speed);
speedButtons.forEach(item => item.classList.toggle("active", item === button));
speedCaption.textContent = `Устанавливаем скорость ${speed}…`;
});
}));
timerToggle.addEventListener("click", () => {
const next = !Boolean(latest?.elica?.timer);
command(`/api/elica/timer/${next ? "on" : "off"}`, () => {
setToggle(timerToggle, next);
timerCaption.textContent = next ? "Включаем таймер…" : "Выключаем таймер…";
});
});
lightToggle.addEventListener("click", () => {
command("/api/elica/light/toggle", () => {
lightToggle.textContent = "Команда…";
setTimeout(() => { lightToggle.textContent = "Переключить"; }, 700);
});
});
externalFanToggle.addEventListener("click", () => {
const next = !Boolean(latest?.external_fan?.on);
command(`/api/elica/external-fan/${next ? "on" : "off"}`, () => {
setToggle(externalFanToggle, next);
externalFanCard.dataset.on = String(next);
externalFanCaption.textContent = next ? "Включаем…" : "Выключаем…";
});
});
refreshButton.addEventListener("click", () => refresh());
document.addEventListener("visibilitychange", () => {
if (!document.hidden) refresh({ silent: true });
});
refresh();
refreshTimer = window.setInterval(() => refresh({ silent: true }), 1000);
window.addEventListener("beforeunload", () => window.clearInterval(refreshTimer));
+1 -1
View File
@@ -83,7 +83,7 @@ function render(status) {
airCard.style.setProperty("--air-color", airPalette.color);
airCard.style.setProperty("--air-glow", airPalette.glow);
$("#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("#current-time", schedule.current_time || tion.device_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);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
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("#pm25", numberOrDash(sensor.pm25));
text("#pm10", numberOrDash(sensor.pm10));
@@ -122,7 +122,7 @@ function render(status) {
$("#mode-outside").classList.toggle("active", tion.mode === "outside");
$("#mode-recirculation").classList.toggle("active", 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));
const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2));
$("#filter-progress").style.width = `${filterPercent}%`;
+3 -3
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Tion 4S — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/widget.css">
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1">
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
@@ -124,6 +124,6 @@
</button>
<span id="demo-note" class="demo-note" hidden>Демонстрационный режим — команды не отправляются устройству</span>
</main>
<script type="module" src="/ui/static/js/widget.js"></script>
<script type="module" src="/ui/static/js/tion-widget.js?v=20260927-1"></script>
</body>
</html>
+3 -3
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Tion 4S — панель управления</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/panel.css">
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1">
</head>
<body>
<div class="ambient"></div>
@@ -158,6 +158,6 @@
</footer>
</form>
</dialog>
<script type="module" src="/ui/static/js/panel.js"></script>
<script type="module" src="/ui/static/js/tion.js?v=2"></script>
</body>
</html>