16 Commits
Author SHA1 Message Date
Dmitriy 4786f4e749 fix : v1.5.9 еще внес правки по отображению температуры. 2026-09-29 23:40:00 +03:00
Dmitriy 8e0ee11095 fix : v1.5.8 исправил отображение температуры на странице. Отображалась температура на выходе из бризера, т.е. в комнате. 2026-09-29 23:04:06 +03:00
Dmitriy 5fc2149755 fix: v1.5.7 исправил архитектуру управления температурой. Теперь отдельный контроллер отвечает за нагрев для всех режимов авто ручной или временный ручной. Раньше в каждом режиме была своя логика. 2026-09-29 22:55:36 +03:00
Dmitriy 075690a98b fix: v1.5.6 поправил баг отображения температуры 30 град при переходе между режимами. в api.py были не верные отступы. 2026-09-27 22:16:58 +03:00
Dmitriy bc7b85df60 fix: v1.5.5 поправил баг, когда при режиме авто меняешь температуру, управление шло по джатчикам тион. теперь по quingping 2026-09-27 22:10:46 +03:00
Dmitriy d21836bf76 fix: v1.5.4 поправил автоматический сброс температуры если руками изменить в режиме авто 2026-09-27 21:57:09 +03:00
Dmitriy 8f7564a55d fix: v1.5.3 в режиме авто теперь отображается реально заданная желаемая температура. Раньше отображалась 30 град т.к. включением нагрева управляет логика а не тион 2026-09-27 21:44:22 +03:00
Dmitriy 328182e1b4 fix: v1.5.2 изменил логику нагрева, теперь нагрев включается по датчику qingping а не тион. Если он недоступен то по тиону. 2026-09-27 21:28:31 +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 2846fb0fbb fix: v1.4.3 добавил защиту для случая если процесс bluetooth аварийно завершился, приложение считает его connected и не может подключиться 2026-09-27 17:13:42 +03:00
Dmitriy 41a4d6cd1b fix : v1.4.22 исправил включение бризера. Теперь отправляется power on и speed 2026-09-27 09:22:31 +03:00
Dmitriy cb9d0338a7 fix: 1.4.1 исправил адрес сервера mqtt на miniPC 2026-09-27 00:55:11 +03:00
Dmitriy 7da45b7fef fix: v1.4.1 исправлены css главных панелей тиона и элики. 2026-09-27 00:39:45 +03:00
Dmitriy 9fe85c3683 fix: 1.4.0 добавил фалйы форм в отслеживание 2026-09-27 00:11:18 +03:00
Dmitriy 774d16f10a feat: v 1.4.0 Полный функционал для работы с вятяжкой
* Добавил полный функционал управления elica через esp32 по MQTT
    * Добавил в прошивку принудительную блокировку внешнего винтелятора при работающей вытяжке
    * Добавил веб-панели для управления вытяжкой
2026-09-27 00:00:26 +03:00
62 changed files with 8191 additions and 1083 deletions
+4 -4
View File
@@ -1,8 +1,8 @@
[version] [version]
major = 1 major = 1
minor = 3 minor = 5
patch = 0 patch = 9
[build] [build]
date = "2026-09-20" date = "2026-09-29"
time = "14:17:42" time = "23:38:58"
+399 -113
View File
@@ -10,12 +10,16 @@ from fastapi.staticfiles import StaticFiles
from pathlib import Path as FilePath from pathlib import Path as FilePath
from app.qingping.service import QingpingService from app.qingping.service import QingpingService
from app.metrics import PrometheusMetricsService from app.metrics import PrometheusMetricsService
from app.elica import ElicaConfig, ElicaController, ElicaService
from app.auto.elica_assist import ElicaAutoAssistState
from app.my_dataclasses import ( from app.my_dataclasses import (
TION_MAC, TION_MAC,
QINGPING_MAC, QINGPING_MAC,
QINGPING_MQTT_HOST, QINGPING_MQTT_HOST,
QINGPING_MQTT_PORT, QINGPING_MQTT_PORT,
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
MIN_FAN_SPEED, MIN_FAN_SPEED,
MAX_FAN_SPEED, MAX_FAN_SPEED,
MIN_TARGET_TEMP, MIN_TARGET_TEMP,
@@ -29,7 +33,7 @@ from app.my_dataclasses import (
from app.auto import ( from app.auto import (
AutoController, AutoController,
Co2SpeedPolicy, Co2SpeedPolicy,
load_auto_config, load_auto_config_components,
) )
from app.auto.temperature_policy import TemperaturePolicy from app.auto.temperature_policy import TemperaturePolicy
@@ -87,6 +91,14 @@ qingping_service = QingpingService(
mac=QINGPING_MAC, mac=QINGPING_MAC,
) )
elica_service = ElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(elica_service)
schedule_service: ScheduleService | None = None schedule_service: ScheduleService | None = None
schedule_load_error: str | None = None schedule_load_error: str | None = None
@@ -109,6 +121,7 @@ async def lifespan(app: FastAPI):
await service.start() await service.start()
await qingping_service.start() await qingping_service.start()
await elica_service.start()
try: try:
try: try:
@@ -125,44 +138,126 @@ async def lifespan(app: FastAPI):
schedule_load_error = None schedule_load_error = None
try: try:
auto_config = load_auto_config(AUTO_CONFIG_FILE) auto_config = load_auto_config_components(AUTO_CONFIG_FILE)
auto_policy = Co2SpeedPolicy( auto_interval = auto_config.check_interval
base_speed=(
auto_config.co2.base_speed
),
thresholds=(
auto_config.co2.thresholds
),
hysteresis=(
auto_config.co2.hysteresis
),
)
temperature_policy = TemperaturePolicy(auto_config.temperature) auto_errors = dict(auto_config.errors)
auto_interval = (auto_config.check_interval) # --------------------------------------------------
# CO2 policy
auto_load_error = None # --------------------------------------------------
except Exception as exc:
auto_policy = None 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 temperature_policy = None
# Безопасный встроенный интервал нужен, if (
# потому что auto.yaml сейчас недоступен. 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_interval = 5.0
auto_load_error = ( auto_load_error = (
f"{type(exc).__name__}: {exc}" f"{type(exc).__name__}: {exc}"
) )
# --------------------------------------------------
# AutoController создаётся даже если, например,
# CO2 policy не загрузилась.
#
# policy=None даст fallback скорости,
# но TemperaturePolicy при этом может работать.
# --------------------------------------------------
auto_controller = AutoController( auto_controller = AutoController(
schedule_service=schedule_service, schedule_service=schedule_service,
qingping_service=qingping_service, qingping_service=qingping_service,
tion_service=service, tion_service=service,
elica_controller=elica_controller,
policy=auto_policy, policy=auto_policy,
temperature_policy=temperature_policy, temperature_policy=temperature_policy,
elica_assist=elica_assist,
interval=auto_interval, interval=auto_interval,
) )
@@ -200,6 +295,7 @@ async def lifespan(app: FastAPI):
if schedule_service is not None: if schedule_service is not None:
await schedule_service.stop() await schedule_service.stop()
await elica_service.stop()
await qingping_service.stop() await qingping_service.stop()
await service.stop() await service.stop()
@@ -225,22 +321,59 @@ app.mount(
@app.get("/", include_in_schema=False) @app.get("/", include_in_schema=False)
async def root(): async def root():
return RedirectResponse(url="/ui/panel") return RedirectResponse(url="/ui/tion")
@app.get("/ui", include_in_schema=False) @app.get("/ui", include_in_schema=False)
async def ui_root(): async def ui_root():
return RedirectResponse(url="/ui/panel") return RedirectResponse(url="/ui/tion")
# Canonical UI routes. Device-specific names make room for additional
# 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", 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", headers={"Cache-Control": "no-store"})
@app.get("/ui/elica", include_in_schema=False)
async def ui_elica():
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", 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(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) @app.get("/ui/widget", include_in_schema=False)
async def ui_widget(): async def ui_widget_legacy(request: Request):
return FileResponse(WEB_ROOT / "widget.html") suffix = f"?{request.url.query}" if request.url.query else ""
return RedirectResponse(url=f"/ui/tion-widget{suffix}")
@app.get("/ui/panel", include_in_schema=False) @app.get("/ui/exhaust", include_in_schema=False)
async def ui_panel(): async def ui_exhaust_legacy(request: Request):
return FileResponse(WEB_ROOT / "panel.html") 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(request: Request):
suffix = f"?{request.url.query}" if request.url.query else ""
return RedirectResponse(url=f"/ui/elica-widget{suffix}")
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
@@ -270,6 +403,42 @@ def get_status() -> dict:
state = service.state state = service.state
tion_status = (
state.to_dict()
if state is not None
else None
)
# --------------------------------------------------
# В ручном режиме UI должен видеть желание
# пользователя, а не техническое состояние
# внешнего регулятора.
# --------------------------------------------------
if (
tion_status is not None
and auto_controller is not None
):
temperature_config = (auto_controller.effective_temperature_config())
if (
temperature_config.heater_enabled
is not None
):
tion_status["heater"] = (
temperature_config.heater_enabled
)
if (
temperature_config.target_temp
is not None
):
tion_status["target_temp"] = (
temperature_config.target_temp
)
return { return {
"online": service.online, "online": service.online,
"running": service.running, "running": service.running,
@@ -282,18 +451,37 @@ def get_status() -> dict:
"last_error": service.last_error, "last_error": service.last_error,
"tion": ( "tion": tion_status,
state.to_dict()
if state is not None
else None
),
"auto": get_auto_status(), "auto": get_auto_status(),
"qingping": qingping_service.status(), "qingping": qingping_service.status(),
"elica": get_elica_status(),
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
} }
def get_elica_status() -> dict:
"""Текущее состояние ESP32, вытяжки Elica и внешнего вентилятора."""
return elica_service.status()
async def execute_elica_command(operation):
try:
await operation()
except Exception as exc:
raise HTTPException(
status_code=503,
detail={
"message": "Elica unavailable",
"error": f"{type(exc).__name__}: {exc}",
},
) from exc
return get_elica_status()
def get_effective_speed() -> int: def get_effective_speed() -> int:
if ( if (
@@ -317,17 +505,16 @@ def get_effective_speed() -> int:
def get_effective_temperature() -> int: def get_effective_temperature() -> int:
if ( if auto_controller is not None:
schedule_service is not None
and schedule_service.override_active config = (
and schedule_service.override_settings.target_temp is not None auto_controller
): .effective_temperature_config()
return (
schedule_service
.override_settings
.target_temp
) )
if config.target_temp is not None:
return config.target_temp
state = service.state state = service.state
if state is None: if state is None:
@@ -378,6 +565,60 @@ async def execute_command(operation, override: ScheduledSettings | None = None):
return get_status() return get_status()
async def execute_temperature_command(
operation,
settings: ScheduledSettings,
):
try:
if (
auto_controller is not None
and schedule_service is not None
and schedule_service.running
and schedule_service.config.enabled
):
# ------------------------------------------
# PAUSE = полноценный ручной режим.
# ------------------------------------------
if schedule_service.paused:
if settings.heater is not None:
auto_controller.set_manual_heater_enabled(settings.heater)
if settings.target_temp is not None:
auto_controller.set_manual_target_temperature(settings.target_temp)
# ------------------------------------------
# SET / AUTO = temporary override.
# ------------------------------------------
else:
await schedule_service.apply_override(settings)
# Не ждём следующего 5-секундного цикла.
await auto_controller.reconcile_temperature()
else:
# Fallback, если расписание/AutoController
# вообще не работают.
await service.execute(operation)
except Exception as exc:
raise HTTPException(
status_code=503,
detail={
"message": "Tion unavailable",
"error": (
f"{type(exc).__name__}: {exc}"
),
},
) from exc
return get_status()
def occurrence_to_dict(occurrence) -> dict | None: def occurrence_to_dict(occurrence) -> dict | None:
@@ -525,16 +766,62 @@ def get_auto_status() -> dict:
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Status # Status
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/status") @app.get("/api/status")
async def status(): async def status():
return get_status() return get_status()
# ----------------------------------------------------------------------
# Elica / exhaust
# ----------------------------------------------------------------------
@app.get("/api/elica/status")
async def elica_status():
return get_elica_status()
@app.post("/api/elica/power/{state}")
async def set_elica_power(state: Literal["on", "off"]):
operation = (
elica_controller.power_on
if state == "on"
else elica_controller.power_off
)
return await execute_elica_command(operation)
@app.post("/api/elica/speed/{speed}")
async def set_elica_speed(
speed: Annotated[int, Path(ge=1, le=4)],
):
return await execute_elica_command(
lambda: elica_controller.set_speed(speed)
)
@app.post("/api/elica/timer/{state}")
async def set_elica_timer(state: Literal["on", "off"]):
enabled = state == "on"
return await execute_elica_command(
lambda: elica_controller.set_timer(enabled)
)
@app.post("/api/elica/light/toggle")
async def toggle_elica_light():
return await execute_elica_command(elica_controller.toggle_light)
@app.post("/api/elica/external-fan/{state}")
async def set_external_fan(state: Literal["on", "off"]):
enabled = state == "on"
return await execute_elica_command(
lambda: elica_controller.set_external_fan(enabled)
)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Power # Power
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/power/{state}") @app.post("/api/tion/power/{state}")
async def set_power(state: Literal["on", "off"]): async def set_power(state: Literal["on", "off"]):
@@ -554,7 +841,6 @@ async def set_power(state: Literal["on", "off"]):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Fan speed increase / decrease # Fan speed increase / decrease
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/speed/increase") @app.post("/api/tion/speed/increase")
async def increase_speed(): async def increase_speed():
@@ -616,96 +902,57 @@ async def set_speed(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Heater # Heater
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/heater/{state}") @app.post("/api/tion/heater/{state}")
async def set_heater(state: Literal["on", "off"]): async def set_heater(
state: Literal["on", "off"],
):
enabled = state == "on" enabled = state == "on"
if enabled: operation = (
operation = lambda tion: tion.heater_on() (lambda tion: tion.heater_on())
else: if enabled
operation = lambda tion: tion.heater_off() else
(lambda tion: tion.heater_off())
)
return await execute_temperature_command(
return await execute_command(
operation, operation,
ScheduledSettings(heater=enabled),
)
# ----------------------------------------------------------------------
# Target temperature increase / decrease
# ----------------------------------------------------------------------
@app.post("/api/tion/temperature/increase")
async def increase_temperature():
current_temperature = get_effective_temperature()
new_temperature = min(current_temperature + 1, MAX_TARGET_TEMP)
if new_temperature == current_temperature:
return get_status()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings( ScheduledSettings(
target_temp=new_temperature, heater=enabled,
), ),
) )
@app.post("/api/tion/temperature/decrease")
async def decrease_temperature():
current_temperature = get_effective_temperature()
new_temperature = max(current_temperature - 1, MIN_TARGET_TEMP)
if new_temperature == current_temperature:
return get_status()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings(
target_temp=new_temperature,
),
)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Target temperature # Target temperature
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/temperature/{temperature}") @app.post("/api/tion/temperature/{temperature}")
async def set_temperature( async def set_temperature(
temperature: Annotated[ temperature: Annotated[
int, int,
Path( Path(
ge=MIN_TARGET_TEMP, ge=MIN_TARGET_TEMP,
le=MAX_TARGET_TEMP, le=MAX_TARGET_TEMP,
), ),
],): ],
):
return await execute_command( return await execute_temperature_command(
lambda tion: lambda tion:
tion.set_target_temperature(temperature), tion.set_target_temperature(
ScheduledSettings(target_temp=temperature), temperature
),
ScheduledSettings(
target_temp=temperature,
),
) )
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Air mode # Air mode
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/mode/{mode}") @app.post("/api/tion/mode/{mode}")
async def set_mode( async def set_mode(
mode: str, mode: str,
@@ -737,7 +984,6 @@ async def set_mode(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Sound # Sound
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/sound/{value}") @app.post("/api/tion/sound/{value}")
async def set_sound( async def set_sound(
value: Literal["on", "off"], value: Literal["on", "off"],
@@ -760,7 +1006,6 @@ async def set_sound(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Light # Light
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/light/{value}") @app.post("/api/tion/light/{value}")
async def set_light( async def set_light(
value: Literal["on", "off"], value: Literal["on", "off"],
@@ -782,7 +1027,6 @@ async def set_light(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Переход в auto # Переход в auto
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/schedule/config") @app.get("/api/schedule/config")
async def get_schedule_config(): async def get_schedule_config():
try: try:
@@ -872,6 +1116,9 @@ async def clear_schedule_override():
await schedule_service.clear_override() await schedule_service.clear_override()
if auto_controller is not None:
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -890,8 +1137,42 @@ async def pause_schedule():
detail="Schedule service unavailable", detail="Schedule service unavailable",
) )
# ВАЖНО:
# получаем логические настройки ДО pause(),
# потому что там ещё действует SET/AUTO/override.
temperature_config = None
if auto_controller is not None:
temperature_config = (
auto_controller
.effective_temperature_config()
)
await schedule_service.pause() await schedule_service.pause()
if (
auto_controller is not None
and temperature_config is not None
):
if (
temperature_config.heater_enabled
is not None
):
auto_controller.set_manual_heater_enabled(
temperature_config.heater_enabled
)
if (
temperature_config.target_temp
is not None
):
auto_controller.set_manual_target_temperature(
temperature_config.target_temp
)
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -911,6 +1192,11 @@ async def resume_schedule():
await schedule_service.resume() await schedule_service.resume()
if auto_controller is not None:
auto_controller.clear_manual_heater_control()
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
+4
View File
@@ -1,7 +1,9 @@
from .config import ( from .config import (
AutoConfig, AutoConfig,
AutoConfigComponents,
Co2Config, Co2Config,
load_auto_config, load_auto_config,
load_auto_config_components,
) )
from .co2_policy import ( from .co2_policy import (
@@ -19,4 +21,6 @@ __all__ = [
"load_auto_config", "load_auto_config",
"Co2SpeedPolicy", "Co2SpeedPolicy",
"AutoController", "AutoController",
"AutoConfigComponents",
"load_auto_config_components",
] ]
+277 -70
View File
@@ -30,6 +30,21 @@ class Co2Config:
class TemperatureConfig: class TemperatureConfig:
hysteresis: float hysteresis: float
@dataclass(
frozen=True,
slots=True,
)
class ElicaAssistConfig:
enabled: bool
# (скорость Tion, скорость Elica)
speed_map: tuple[
tuple[int, int],
...
]
@dataclass( @dataclass(
frozen=True, frozen=True,
slots=True, slots=True,
@@ -39,8 +54,23 @@ class AutoConfig:
check_interval: float check_interval: float
co2: Co2Config co2: Co2Config
temperature: TemperatureConfig 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: def _require_dict(name: str, value: Any) -> dict:
if not isinstance(value, dict): if not isinstance(value, dict):
@@ -246,14 +276,155 @@ def _parse_co2(value: Any) -> Co2Config:
thresholds=thresholds, 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) path = Path(path)
with path.open( with path.open(
"r", "r",
encoding="utf-8", encoding="utf-8",
) as file: ) as file:
raw = yaml.safe_load(file) raw = yaml.safe_load(file)
@@ -267,6 +438,7 @@ def load_auto_config(path: str | Path) -> AutoConfig:
"check_interval", "check_interval",
"co2", "co2",
"temperature", "temperature",
"elica_assist",
} }
if unknown: if unknown:
@@ -288,10 +460,8 @@ def load_auto_config(path: str | Path) -> AutoConfig:
) )
if ( if (
type(check_interval) not in { type(check_interval)
int, not in {int,float,}
float,
}
): ):
raise ValueError( raise ValueError(
"check_interval must be a number" "check_interval must be a number"
@@ -302,88 +472,125 @@ def load_auto_config(path: str | Path) -> AutoConfig:
"check_interval must be > 0" "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 # CO2
# -------------------------------------------------- # --------------------------------------------------
if "co2" not in data: if "co2" not in data:
raise ValueError( raise ValueError("co2 config is required")
"co2 config is required" co2 = _parse_co2(data["co2"])
)
co2 = _parse_co2(
data["co2"]
)
# -------------------------------------------------- # --------------------------------------------------
# Temperature # Temperature
# -------------------------------------------------- # --------------------------------------------------
if "temperature" not in data: if "temperature" not in data:
raise ValueError( raise ValueError("temperature config is required")
"temperature config is required"
)
temperature_data = _require_dict( temperature = _parse_temperature(data["temperature"])
"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,
)
# -------------------------------------------------- # --------------------------------------------------
# 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( return AutoConfig(
version=version, version=version,
check_interval=float( check_interval=check_interval,
check_interval
),
co2=co2, co2=co2,
temperature=temperature, temperature=temperature,
elica_assist=elica_assist,
) )
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"
)
+14
View File
@@ -0,0 +1,14 @@
from .config import ElicaConfig
from .controller import ElicaController
from .models import ElicaLogicalState, ElicaPanelState, ElicaState, ExternalFanState
from .service import ElicaService
__all__ = [
"ElicaConfig",
"ElicaController",
"ElicaLogicalState",
"ElicaPanelState",
"ElicaService",
"ElicaState",
"ExternalFanState",
]
+7
View File
@@ -19,6 +19,13 @@ class ElicaConfig:
light_relay: int = 3 light_relay: int = 3
timer_relay: int = 4 timer_relay: int = 4
# Внешний вытяжной вентилятор подключён к OUT5.
# Нагрузка заведена через NC-контакт реле, поэтому логическое
# состояние вентилятора инвертировано относительно катушки реле:
# relay OFF -> NC замкнут -> fan ON; relay ON -> fan OFF.
external_fan_relay: int = 5
external_fan_normally_closed: bool = True
# Индикаторы Elica -> IN # Индикаторы Elica -> IN
speed_1_input: int = 1 speed_1_input: int = 1
speed_2_input: int = 2 speed_2_input: int = 2
+136 -32
View File
@@ -19,14 +19,19 @@ class ElicaController:
service: ElicaService, service: ElicaService,
state_timeout: float = 3.0, state_timeout: float = 3.0,
poll_interval: float = 0.05, poll_interval: float = 0.05,
speed_inter_press_delay: float = 0.4,
): ):
self._service = service self._service = service
self._state_timeout = state_timeout self._state_timeout = state_timeout
self._poll_interval = poll_interval 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
# Не допускаем одновременное выполнение нескольких # Не допускаем одновременное выполнение нескольких
# последовательностей нажатий кнопок. # последовательностей нажатий кнопок.
self._lock = asyncio.Lock() self._lock = asyncio.Lock()
self._external_fan_lock = asyncio.Lock()
@property @property
def service(self) -> ElicaService: def service(self) -> ElicaService:
@@ -61,6 +66,7 @@ class ElicaController:
while True: while True:
self._ensure_available() self._ensure_available()
self._ensure_feedback_ready()
state = self.state state = self.state
if predicate(state): if predicate(state):
@@ -76,7 +82,7 @@ class ElicaController:
async def _power_on_locked(self) -> ElicaLogicalState: async def _power_on_locked(self) -> ElicaLogicalState:
"""Включает вытяжку. Вызывается только под self._lock.""" """Включает вытяжку. Вызывается только под self._lock."""
self._ensure_available() await self._ensure_ready()
state = self.state state = self.state
if state.power: if state.power:
@@ -91,7 +97,7 @@ class ElicaController:
async def _power_off_locked(self) -> ElicaLogicalState: async def _power_off_locked(self) -> ElicaLogicalState:
"""Выключает вытяжку. Вызывается только под self._lock.""" """Выключает вытяжку. Вызывается только под self._lock."""
self._ensure_available() await self._ensure_ready()
state = self.state state = self.state
if not state.power: if not state.power:
@@ -107,7 +113,6 @@ class ElicaController:
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Power # Power
# ------------------------------------------------------------------ # ------------------------------------------------------------------
async def power_on(self) -> ElicaLogicalState: async def power_on(self) -> ElicaLogicalState:
async with self._lock: async with self._lock:
return await self._power_on_locked() return await self._power_on_locked()
@@ -116,60 +121,99 @@ class ElicaController:
async with self._lock: async with self._lock:
return await self._power_off_locked() 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 # Speed
# ------------------------------------------------------------------ # ------------------------------------------------------------------
async def set_speed(self, speed: int) -> ElicaLogicalState: async def set_speed(self, speed: int) -> ElicaLogicalState:
""" """Устанавливает скорость 1-4 последовательными нажатиями Speed.
Устанавливает скорость 1-4.
Контроллер нажимает кнопку Speed и после каждого нажатия У Elica одна кнопка скорости и фиксированный цикл:
проверяет фактическую скорость по индикаторам. 1 -> 2 -> 3 -> 4 -> 1
Поэтому сначала определяем текущую скорость по индикаторам,
вычисляем точное число нажатий и после каждого нажатия ждём
подтверждения следующей скорости.
""" """
if not 1 <= speed <= 4: if not 1 <= speed <= 4:
raise ValueError("Elica speed must be between 1 and 4") raise ValueError("Elica speed must be between 1 and 4")
async with self._lock: async with self._lock:
self._ensure_available() await self._ensure_ready()
state = self.state state = self.state
if not state.power: if not state.power:
state = await self._power_on_locked() # У Elica кнопка Speed сама включает вытяжку. Первое
# нажатие из состояния OFF запускает её на скорости 1.
# Поэтому при выборе скорости Power здесь не нажимаем.
await self._press_speed_locked()
state = await self._wait_state(
lambda value: value.power and value.speed == 1,
"speed 1",
)
# После включения power LED может обновиться раньше speed LED. # Если питание уже было включено, но индикатор скорости ещё
if state.speed == 0: # не успел синхронизироваться, ждём корректное значение 1-4.
if not 1 <= state.speed <= 4:
state = await self._wait_state( state = await self._wait_state(
lambda value: value.power and 1 <= value.speed <= 4, lambda value: value.power and 1 <= value.speed <= 4,
"initial speed", "initial speed",
) )
if state.speed == speed: current_speed = state.speed
return state presses = (speed - current_speed) % 4
# Не предполагаем конкретный порядок скоростей. for _ in range(presses):
# После каждого нажатия смотрим, что реально получилось. expected_speed = current_speed % 4 + 1
for _ in range(4):
previous_speed = state.speed
await self._service.press_speed() await self._press_speed_locked()
state = await self._wait_state( state = await self._wait_state(
lambda value: ( lambda value, expected=expected_speed: (
value.power value.power and value.speed == expected
and 1 <= value.speed <= 4
and value.speed != previous_speed
), ),
"speed change", f"speed {expected_speed}",
) )
if state.speed == speed: current_speed = expected_speed
return state
raise RuntimeError(
f"Unable to set Elica speed to {speed}; " return state
f"current speed: {state.speed}"
)
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Timer # Timer
@@ -182,7 +226,7 @@ class ElicaController:
Состояние подтверждается по миганию индикатора скорости. Состояние подтверждается по миганию индикатора скорости.
""" """
async with self._lock: async with self._lock:
self._ensure_available() await self._ensure_ready()
state = self.state state = self.state
if not enabled and not state.power: if not enabled and not state.power:
@@ -227,5 +271,65 @@ class ElicaController:
поэтому light_on/light_off реализовать достоверно нельзя. поэтому light_on/light_off реализовать достоверно нельзя.
""" """
async with self._lock: async with self._lock:
await self._ensure_ready()
await self._service.press_light()
# ------------------------------------------------------------------
# External fan (OUT5 / NC contact)
# ------------------------------------------------------------------
async def set_external_fan(self, enabled: bool) -> bool:
"""
Управляет внешним вентилятором через OUT5.
Вентилятор подключён к NC-контакту, поэтому для включения
вентилятора катушка реле должна быть выключена, а для выключения
— включена. Физическая инверсия скрыта внутри этого метода.
"""
async with self._external_fan_lock:
self._ensure_available() self._ensure_available()
await self._service.press_light()
relay = self._service.config.external_fan_relay
await self._service.wait_relay_feedback_ready(
relay,
timeout=self._state_timeout,
)
relay_enabled = (
not enabled
if self._service.config.external_fan_normally_closed
else enabled
)
if self._service.relay_state(relay) != relay_enabled:
self._service.set_relay(relay, relay_enabled)
await self._service.wait_relay_state(
relay,
relay_enabled,
timeout=self._state_timeout,
)
state = self._service.external_fan_state
if state.on is None:
raise RuntimeError("External fan state is unavailable")
return state.on
async def external_fan_on(self) -> bool:
return await self.set_external_fan(True)
async def external_fan_off(self) -> bool:
return await self.set_external_fan(False)
# ------------------------------------------------------------------
# Синхронизация начального состояния
# ------------------------------------------------------------------
async def _ensure_ready(self) -> None:
"""Проверяет доступность и ждёт исходной синхронизации feedback."""
self._ensure_available()
await self._service.wait_feedback_ready(timeout=self._state_timeout)
self._ensure_available()
def _ensure_feedback_ready(self) -> None:
if not self._service.feedback_ready:
raise RuntimeError("Elica feedback is not synchronized")
+15 -3
View File
@@ -20,8 +20,9 @@ class ElicaState:
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
) )
# Фактические состояния IN1-IN8, # Состояния оптовходов IN1-IN8, полученные от ESPHome через MQTT.
# полученные от ESPHome через MQTT. # True означает электрически активный вход платы. Для линий
# индикаторов Elica это НЕ равно "LED включён": Elica активна LOW.
input_states: tuple[bool, ...] = ( input_states: tuple[bool, ...] = (
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
@@ -55,4 +56,15 @@ class ElicaLogicalState:
timer: bool = False timer: bool = False
def to_dict(self) -> dict: def to_dict(self) -> dict:
return asdict(self) return asdict(self)
@dataclass(frozen=True, slots=True)
class ExternalFanState:
available: bool = False
on: bool | None = None
relay: int = 5
relay_on: bool | None = None
normally_closed: bool = True
def to_dict(self) -> dict:
return asdict(self)
+212 -15
View File
@@ -5,7 +5,7 @@ import paho.mqtt.client as mqtt
from dataclasses import replace from dataclasses import replace
from datetime import datetime, timezone from datetime import datetime, timezone
from .config import ElicaConfig from .config import ElicaConfig
from .models import ElicaState, ElicaPanelState, ElicaLogicalState from .models import ElicaState, ElicaPanelState, ElicaLogicalState, ExternalFanState
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -31,7 +31,9 @@ class ElicaService:
self._last_speed = 0 self._last_speed = 0
self._speed_led_off_at: float | None = None self._speed_led_off_at: float | None = None
self._last_blink_at: float | None = None self._last_blink_at: float | None = None
self._received_input_mask = 0
self._received_relay_mask = 0
@property @property
def config(self) -> ElicaConfig: def config(self) -> ElicaConfig:
@@ -109,6 +111,9 @@ class ElicaService:
logger.info("ESP32 elica MQTT connected") logger.info("ESP32 elica MQTT connected")
self._received_input_mask = 0
self._received_relay_mask = 0
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Подписки сервиса # Подписки сервиса
# ------------------------------------------------------------------ # ------------------------------------------------------------------
@@ -139,6 +144,9 @@ class ElicaService:
else: else:
logger.info("ESP32 Elica MQTT disconnected: %s",reason_code) logger.info("ESP32 Elica MQTT disconnected: %s",reason_code)
self._received_input_mask = 0
self._received_relay_mask = 0
self._state = replace( self._state = replace(
self._state, self._state,
mqtt_connected=False, mqtt_connected=False,
@@ -249,6 +257,7 @@ class ElicaService:
relay_states=tuple(relay_states), relay_states=tuple(relay_states),
last_message_at=datetime.now(timezone.utc), last_message_at=datetime.now(timezone.utc),
) )
self._received_relay_mask |= 1 << (relay - 1)
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Input state # Input state
# ------------------------------------------------------------------ # ------------------------------------------------------------------
@@ -293,6 +302,9 @@ class ElicaService:
input_states=tuple(input_states), input_states=tuple(input_states),
last_message_at=datetime.now(timezone.utc), last_message_at=datetime.now(timezone.utc),
) )
self._received_input_mask |= 1 << (input_number - 1)
self._update_panel_tracker() self._update_panel_tracker()
def input_state(self, input_number: int) -> bool: def input_state(self, input_number: int) -> bool:
@@ -308,6 +320,12 @@ class ElicaService:
def _update_panel_tracker(self) -> None: def _update_panel_tracker(self) -> None:
"""Отслеживает скорость и мигание индикатора таймера.""" """Отслеживает скорость и мигание индикатора таймера."""
# Пока не получили все пять входов панели, не пытаемся
# интерпретировать их начальные значения. После инверсии Elica
# значение False по умолчанию выглядело бы как включённый LED.
if not self.feedback_ready:
return
panel = self.panel_state panel = self.panel_state
now = time.monotonic() now = time.monotonic()
@@ -348,6 +366,9 @@ class ElicaService:
@property @property
def logical_state(self) -> ElicaLogicalState: def logical_state(self) -> ElicaLogicalState:
"""Возвращает интерпретированное состояние вытяжки Elica.""" """Возвращает интерпретированное состояние вытяжки Elica."""
if not self.feedback_ready:
return ElicaLogicalState()
panel = self.panel_state panel = self.panel_state
now = time.monotonic() now = time.monotonic()
@@ -447,6 +468,43 @@ class ElicaService:
return self._state.relay_states[relay - 1] return self._state.relay_states[relay - 1]
def relay_feedback_ready(self, relay: int) -> bool:
"""True, если после подключения уже получено состояние реле."""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
return bool(self._received_relay_mask & (1 << (relay - 1)))
@property
def external_fan_state(self) -> ExternalFanState:
"""Логическое состояние внешнего вентилятора на OUT5."""
relay = self._config.external_fan_relay
ready = self.relay_feedback_ready(relay)
if not ready:
return ExternalFanState(
available=False,
on=None,
relay=relay,
relay_on=None,
normally_closed=self._config.external_fan_normally_closed,
)
relay_on = self.relay_state(relay)
fan_on = (
not relay_on
if self._config.external_fan_normally_closed
else relay_on
)
return ExternalFanState(
available=True,
on=fan_on,
relay=relay,
relay_on=relay_on,
normally_closed=self._config.external_fan_normally_closed,
)
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# Public status # Public status
# ------------------------------------------------------------------ # ------------------------------------------------------------------
@@ -457,24 +515,106 @@ class ElicaService:
"pulse_ms": self._config.pulse_ms, "pulse_ms": self._config.pulse_ms,
"panel": self.panel_state.to_dict(), "panel": self.panel_state.to_dict(),
"elica": self.logical_state.to_dict(), "elica": self.logical_state.to_dict(),
"external_fan": self.external_fan_state.to_dict(),
"feedback_ready": self.feedback_ready,
"missing_feedback_inputs": self.missing_feedback_inputs,
**self._state.to_dict(), **self._state.to_dict(),
} }
async def pulse_relay(self, relay: int, pulse_ms: int | None = None) -> None: 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"
)
duration_ms = (
pulse_ms
if pulse_ms is not None
else self._config.pulse_ms
)
# --------------------------------------------------
# ВАЖНО:
# после 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 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)
# И ждём подтверждённого отпускания.
await self.wait_relay_state(relay,False)
async def wait_relay_feedback_ready(
self,
relay: int,
timeout: float = 3.0,
poll_interval: float = 0.02,
) -> None:
"""Ждёт первого MQTT-состояния указанного реле после connect."""
if not 1 <= relay <= 8: 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 deadline = asyncio.get_running_loop().time() + timeout
while not self.relay_feedback_ready(relay):
if not self._running:
raise RuntimeError("Elica service is not running")
if not self._state.mqtt_connected:
raise RuntimeError("Elica MQTT is not connected")
if not self._state.device_online:
raise RuntimeError("ESP32 Elica controller is offline")
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError(
f"Relay {relay} feedback synchronization timeout"
)
await asyncio.sleep(poll_interval)
self.set_relay(relay, True)
await self.wait_relay_state(relay, True)
await asyncio.sleep(duration_ms / 1000)
self.set_relay(relay, False)
await self.wait_relay_state(relay, False)
async def wait_relay_state( async def wait_relay_state(
self, self,
@@ -524,13 +664,70 @@ class ElicaService:
# ------------------------------------------------------------------ # ------------------------------------------------------------------
@property @property
def panel_state(self) -> ElicaPanelState: def panel_state(self) -> ElicaPanelState:
"""Возвращает текущее физическое состояние индикаторов Elica.""" """Возвращает фактическое состояние светодиодов панели Elica.
Входы обратной связи имеют обратную полярность относительно LED:
высокий уровень на IN означает, что соответствующий индикатор
Elica погашен, низкий уровень — что индикатор горит.
MQTT-состояние входа поэтому инвертируем именно здесь, на границе
между электрическим состоянием IN и логическим состоянием панели.
"""
return ElicaPanelState( return ElicaPanelState(
speed_leds=( speed_leds=(
self.input_state(self._config.speed_1_input), not self.input_state(self._config.speed_1_input),
self.input_state(self._config.speed_2_input), not self.input_state(self._config.speed_2_input),
self.input_state(self._config.speed_3_input), not self.input_state(self._config.speed_3_input),
self.input_state(self._config.speed_4_input), not self.input_state(self._config.speed_4_input),
), ),
power_led=self.input_state(self._config.power_input), power_led=not self.input_state(self._config.power_input),
) )
@property
def feedback_ready(self) -> bool:
"""True, когда получены состояния всех входов, необходимых для Elica."""
return not self.missing_feedback_inputs
@property
def missing_feedback_inputs(self) -> tuple[int, ...]:
"""Возвращает номера входов Elica, состояние которых ещё не получено."""
required = (
self._config.speed_1_input,
self._config.speed_2_input,
self._config.speed_3_input,
self._config.speed_4_input,
self._config.power_input,
)
return tuple(
input_number
for input_number in required
if not self._received_input_mask & (1 << (input_number - 1))
)
async def wait_feedback_ready(
self,
timeout: float = 3.0,
poll_interval: float = 0.05,
) -> None:
"""Ждёт получения исходного состояния всех входов панели Elica."""
deadline = asyncio.get_running_loop().time() + timeout
while not self.feedback_ready:
if not self._running:
raise RuntimeError("Elica service is not running")
if not self._state.mqtt_connected:
raise RuntimeError("Elica MQTT is not connected")
if not self._state.device_online:
raise RuntimeError("ESP32 Elica controller is offline")
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError(
f"Elica feedback synchronization timeout; "
f"missing inputs: {self.missing_feedback_inputs}"
)
await asyncio.sleep(poll_interval)
+5 -1
View File
@@ -10,9 +10,13 @@ from typing import Any, Mapping
TION_MAC = "d1:74:9b:eb:ee:a6" TION_MAC = "d1:74:9b:eb:ee:a6"
QINGPING_MAC = "CCB5D131BA93" QINGPING_MAC = "CCB5D131BA93"
QINGPING_MQTT_HOST = "192.168.7.3" QINGPING_MQTT_HOST = "192.168.7.100"
QINGPING_MQTT_PORT = 1883 QINGPING_MQTT_PORT = 1883
# ESP32-контроллер вытяжки Elica подключён к Mosquitto на mini-PC/NAS.
ELICA_MQTT_HOST = "192.168.7.100"
ELICA_MQTT_PORT = 1883
MIN_FAN_SPEED = 1 MIN_FAN_SPEED = 1
MAX_FAN_SPEED = 6 MAX_FAN_SPEED = 6
+91 -3
View File
@@ -1,4 +1,7 @@
import asyncio import asyncio
import logging
import shutil
import sys
from typing import Any from typing import Any
from bleak import BleakScanner from bleak import BleakScanner
from tion_btle import TionS4 from tion_btle import TionS4
@@ -7,6 +10,7 @@ from .models import TionState
from app.my_dataclasses import * from app.my_dataclasses import *
logger = logging.getLogger(__name__)
class TionController: class TionController:
""" """
@@ -88,12 +92,23 @@ class TionController:
# от предыдущего соединения. # от предыдущего соединения.
await self._reset_device() await self._reset_device()
# Получаем свежий BLEDevice. # Сначала обычный поиск.
ble_device = await BleakScanner.find_device_by_address( ble_device = await BleakScanner.find_device_by_address(
self._mac, self._mac,
timeout=5.0, 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: if ble_device is None:
raise ConnectionError( raise ConnectionError(
f"Tion {self._mac} not found" f"Tion {self._mac} not found"
@@ -150,8 +165,18 @@ class TionController:
""" """
async def power_on(self) -> TionState: 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({ return await self._set({
"state": "on" "state": "on",
"fan_speed": speed,
}) })
async def power_off(self) -> TionState: async def power_off(self) -> TionState:
@@ -272,4 +297,67 @@ class TionController:
return self return self
async def __aexit__(self, exc_type, exc_value, traceback) -> None: async def __aexit__(self, exc_type, exc_value, traceback) -> None:
await self.disconnect() 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)
+10 -1
View File
@@ -23,4 +23,13 @@ co2:
speed: 6 speed: 6
temperature: temperature:
hysteresis: 0.5 hysteresis: 0.5
elica_assist:
enabled: true
speed_map:
4: 1
5: 2
6: 3
@@ -36,7 +36,6 @@ templates:
weekend: weekend:
- time: "10:00" - time: "10:00"
action: action:
power: on power: on
@@ -62,16 +61,12 @@ templates:
speed: 1 speed: 1
days: days:
mon: workday mon: workday
tue: workday tue: workday
wed: workday wed: workday
thu: workday thu: workday
fri: workday fri: workday
sat: weekend sat: weekend
sun: weekend sun: weekend
+71 -1
View File
@@ -80,6 +80,18 @@ globals:
restore_value: no restore_value: no
initial_value: '0xFF' initial_value: '0xFF'
# Tracks the real Elica Power LED so OUT5 can be used as a hard
# interlock for the external fan. The LED line is active LOW.
- id: elica_power_initialized
type: bool
restore_value: no
initial_value: 'false'
- id: elica_power_was_on
type: bool
restore_value: no
initial_value: 'false'
script: script:
- id: write_relays - id: write_relays
mode: restart mode: restart
@@ -114,12 +126,53 @@ interval:
id(input_state) = v; id(input_state) = v;
// Elica Power LED is connected to IN5 (74HC165 mask 0x40).
// IMPORTANT: on this board the 74HC165 raw state is inverted
// relative to the MQTT binary_sensor state. Empirically:
// raw bit 1 -> Elica Power LED ON, raw bit 0 -> LED OFF.
const bool elica_power_on = (v & 0x40) != 0;
bool relay5_changed = false;
if (!id(elica_power_initialized)) {
id(elica_power_initialized) = true;
// If ESP32 boots while Elica is already running, enforce
// the interlock immediately. If Elica is OFF, boot defaults
// already leave Relay 5 OFF -> NC closed -> fan ON.
if (elica_power_on && !(id(relay_state) & 0x10)) {
id(relay_state) |= 0x10;
relay5_changed = true;
}
} else if (elica_power_on) {
// Hard interlock: while Elica is ON, Relay 5 must stay ON.
// Relay 5 ON opens the NC contact and stops the external fan.
if (!(id(relay_state) & 0x10)) {
id(relay_state) |= 0x10;
relay5_changed = true;
}
} else if (id(elica_power_was_on)) {
// Elica has just switched OFF: automatically restore the
// external fan. Relay 5 OFF closes NC and starts the fan.
if (id(relay_state) & 0x10) {
id(relay_state) &= ~0x10;
relay5_changed = true;
}
}
id(elica_power_was_on) = elica_power_on;
// Shared bus changed while reading 74HC165: // Shared bus changed while reading 74HC165:
// restore the requested relay state in 74HC595. // restore the requested relay state in 74HC595.
digitalWrite(25, LOW); digitalWrite(25, LOW);
shiftOut(33, 26, MSBFIRST, ~id(relay_state)); shiftOut(33, 26, MSBFIRST, ~id(relay_state));
digitalWrite(25, HIGH); digitalWrite(25, HIGH);
// Keep MQTT/web-server state in sync when the interlock itself
// changes Relay 5 rather than an external command doing it.
if (relay5_changed) {
id(relay5).publish_state((id(relay_state) & 0x10) != 0);
}
switch: switch:
- platform: template - platform: template
name: "Relay 1" name: "Relay 1"
@@ -177,6 +230,15 @@ switch:
command_topic: "elica/relay/4/set" command_topic: "elica/relay/4/set"
state_topic: "elica/relay/4/state" state_topic: "elica/relay/4/state"
# OUT5 управляет внешним вентилятором через NC-контакт.
# relay5=OFF -> NC замкнут -> внешний вентилятор ВКЛ.
# relay5=ON -> NC разомкнут -> внешний вентилятор ВЫКЛ.
#
# HARD INTERLOCK по фактическому Power LED Elica (IN5):
# Elica ON -> Relay 5 принудительно ON -> внешний вентилятор OFF.
# Elica OFF -> при переходе автоматически Relay 5 OFF -> вентилятор ON.
# Пока Elica включена, MQTT-команда Relay 5 OFF игнорируется, чтобы
# внешний вентилятор нельзя было случайно включить одновременно с Elica.
- platform: template - platform: template
name: "Relay 5" name: "Relay 5"
id: relay5 id: relay5
@@ -186,7 +248,15 @@ switch:
- lambda: id(relay_state) |= 0x10; - lambda: id(relay_state) |= 0x10;
- script.execute: write_relays - script.execute: write_relays
turn_off_action: turn_off_action:
- lambda: id(relay_state) &= ~0x10; - lambda: |-
// Use the same raw IN5 polarity as the interlock above:
// raw bit 1 means the Elica Power LED is ON.
const bool elica_power_on = (id(input_state) & 0x40) != 0;
if (elica_power_on) {
id(relay_state) |= 0x10;
} else {
id(relay_state) &= ~0x10;
}
- script.execute: write_relays - script.execute: write_relays
command_topic: "elica/relay/5/set" command_topic: "elica/relay/5/set"
state_topic: "elica/relay/5/state" state_topic: "elica/relay/5/state"
@@ -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: if resolution.auto_active:
# В режиме AUTO скорость принадлежит # В режиме AUTO скорость принадлежит
# AutoController. # AutoController.
#
# Остальные параметры расписания
# (power, heater, temperature, mode...)
# должны продолжать работать.
settings = replace( settings = replace(
settings, settings,
speed=None, speed=None,
heater=None,
target_temp=None,
) )
await self._apply_settings(settings) await self._apply_settings(settings)
@@ -598,24 +592,6 @@ class ScheduleService:
tion.set_air_mode(settings.mode) tion.set_air_mode(settings.mode)
) )
if settings.target_temp is not None:
await self._tion.execute(
lambda tion:
tion.set_target_temperature(
settings.target_temp
)
)
if settings.heater is not None:
if settings.heater:
await self._tion.execute(
lambda tion: tion.heater_on()
)
else:
await self._tion.execute(
lambda tion: tion.heater_off()
)
if settings.speed is not None: if settings.speed is not None:
await self._tion.execute( await self._tion.execute(
lambda tion: lambda tion:
+134
View File
@@ -0,0 +1,134 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from app.auto.config import (
load_auto_config_components,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
from app.auto.elica_assist import (
ElicaAutoAssistState,
)
BROKEN_CO2_CONFIG = """
version: 1
check_interval: 5.0
co2:
base_speed: 2
hysteresis: 100
thresholds:
- ppm: 700
speed: 2
- ppm: 1000
speed: 3
temperature:
hysteresis: 0.5
elica_assist:
enabled: false
speed_map:
4: 1
5: 2
6: 3
"""
def main():
with TemporaryDirectory() as directory:
path = (
Path(directory)
/ "auto.yaml"
)
path.write_text(
BROKEN_CO2_CONFIG,
encoding="utf-8",
)
config = (
load_auto_config_components(
path
)
)
# ----------------------------------------------
# CO2 должен быть отключён.
# ----------------------------------------------
assert config.co2 is None
assert "co2" in config.errors
assert (
"First threshold speed must be "
"greater than base_speed"
in config.errors["co2"]
)
# ----------------------------------------------
# Temperature должна остаться рабочей.
# ----------------------------------------------
assert config.temperature is not None
assert (
config.temperature.hysteresis
== 0.5
)
temperature_policy = (
TemperaturePolicy(
config.temperature
)
)
assert (
temperature_policy.heater_required(
temperature=20,
target_temp=24,
heater_on=False,
)
is True
)
# ----------------------------------------------
# Elica Assist тоже не должна пострадать.
# ----------------------------------------------
assert (
config.elica_assist
is not None
)
elica_assist = (
ElicaAutoAssistState(
config.elica_assist
)
)
assert elica_assist is not None
# Ошибка должна быть только в CO2.
assert set(config.errors) == {
"co2",
}
print(
"AUTO CONFIG ISOLATION TEST PASSED"
)
if __name__ == "__main__":
main()
-304
View File
@@ -1,304 +0,0 @@
import asyncio
from types import SimpleNamespace
from app.auto.config import (
TemperatureConfig,
)
from app.auto.controller import (
AutoController,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
class FakeQingpingService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
temperature=19.4,
)
class FakeTionController:
def __init__(self):
self.calls = []
async def heater_on(self):
self.calls.append(
("heater_on", None)
)
async def heater_off(self):
self.calls.append(
("heater_off", None)
)
class FakeTionService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=18,
)
self.controller = (
FakeTionController()
)
async def execute(
self,
operation,
):
return await operation(
self.controller
)
def make_resolution(
target_temp=20.0,
):
return SimpleNamespace(
scheduled_settings=(
SimpleNamespace(
target_temp=target_temp,
)
)
)
def make_controller():
qingping = (
FakeQingpingService()
)
tion = FakeTionService()
policy = TemperaturePolicy(
TemperatureConfig(
hysteresis=0.5,
)
)
controller = AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
temperature_policy=policy,
)
return (
controller,
qingping,
tion,
)
async def test_qingping_heating():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
# 19.4 < 19.5
# Heater должен включиться.
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_on", None)
]
assert (
controller._auto_heater
is True
)
assert (
controller._temperature
== 19.4
)
assert (
controller._temperature_source
== "qingping"
)
tion.controller.calls.clear()
# ----------------------------------------------
# 19.8
#
# Heater уже ON.
# До 20 градусов ещё не дошли.
# Продолжаем греть.
#
# Новую команду отправлять не нужно.
# ----------------------------------------------
qingping.state.temperature = 19.8
await controller._process_heater(
resolution
)
assert tion.controller.calls == []
assert (
controller._auto_heater
is True
)
# ----------------------------------------------
# 20.0
#
# Цель достигнута.
# ----------------------------------------------
qingping.state.temperature = 20.0
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
async def test_tion_temperature_fallback():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
# Qingping отключился.
qingping.online = False
# Используем Tion.
tion.state.in_temp = 19
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_on", None)
]
assert (
controller._temperature
== 19
)
assert (
controller._temperature_source
== "tion"
)
assert (
controller._auto_heater
is True
)
async def test_no_temperature():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
qingping.online = False
tion.online = False
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._temperature
is None
)
assert (
controller._temperature_source
is None
)
assert (
controller._auto_heater
is False
)
async def test_target_temperature_missing():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution(
target_temp=None
)
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
async def main():
await test_qingping_heating()
await test_tion_temperature_fallback()
await test_no_temperature()
await test_target_temperature_missing()
print()
print("=" * 70)
print(
"ALL AUTO HEATER PROCESS "
"TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
@@ -1,138 +0,0 @@
import asyncio
from types import SimpleNamespace
from app.auto.config import (
TemperatureConfig,
)
from app.auto.controller import (
AutoController,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
class FakeQingpingService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
temperature=19.5,
)
class FakeTionController:
def __init__(self):
self.calls = []
async def heater_on(self):
self.calls.append(
("heater_on", None)
)
async def heater_off(self):
self.calls.append(
("heater_off", None)
)
class FakeTionService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=19,
)
self.controller = (
FakeTionController()
)
async def execute(
self,
operation,
):
return await operation(
self.controller
)
async def test_auto_uses_auto_target_temperature():
qingping = FakeQingpingService()
tion = FakeTionService()
policy = TemperaturePolicy(
TemperatureConfig(
hysteresis=0.5,
)
)
controller = AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
temperature_policy=policy,
)
resolution = SimpleNamespace(
# Последний SET хотел 23°C.
scheduled_settings=SimpleNamespace(
target_temp=23,
),
# Но текущий AUTO явно хочет 20°C.
auto_target_temp=20,
)
await controller._process_heater(
resolution
)
# При 19.5°C и target=20°C:
#
# heater был OFF,
# нижняя граница = 19.5°C.
#
# Поэтому heater должен остаться OFF.
#
# Если бы контроллер ошибочно использовал
# SET target_temp=23, он бы включил heater.
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
assert (
controller._temperature
== 19.5
)
assert (
controller._temperature_source
== "qingping"
)
async def main():
await test_auto_uses_auto_target_temperature()
print()
print("=" * 70)
print(
"ALL AUTO HEATER TARGET "
"TEMPERATURE TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
-169
View File
@@ -1,169 +0,0 @@
from types import SimpleNamespace
from app.auto.controller import AutoController
class FakeQingpingService:
def __init__(
self,
online: bool,
temperature,
):
self.online = online
self.state = SimpleNamespace(
temperature=temperature,
)
class FakeTionService:
def __init__(
self,
online: bool,
in_temp,
):
self.online = online
self.state = SimpleNamespace(
in_temp=in_temp,
)
def make_controller(
*,
qingping_online: bool,
qingping_temperature,
tion_online: bool,
tion_temperature,
):
qingping = FakeQingpingService(
online=qingping_online,
temperature=qingping_temperature,
)
tion = FakeTionService(
online=tion_online,
in_temp=tion_temperature,
)
return AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
)
def test_qingping_priority():
controller = make_controller(
qingping_online=True,
qingping_temperature=19.7,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 19.7
assert source == "qingping"
def test_tion_fallback():
controller = make_controller(
qingping_online=False,
qingping_temperature=19.7,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 18
assert source == "tion"
def test_tion_fallback_when_qingping_temperature_missing():
controller = make_controller(
qingping_online=True,
qingping_temperature=None,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 18
assert source == "tion"
def test_offline_tion_is_not_used():
controller = make_controller(
qingping_online=False,
qingping_temperature=None,
tion_online=False,
# Значение специально оставляем.
# Оно имитирует старый state Tion.
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature is None
assert source is None
def test_missing_tion_temperature():
controller = make_controller(
qingping_online=False,
qingping_temperature=None,
tion_online=True,
tion_temperature=None,
)
temperature, source = (
controller._get_temperature()
)
assert temperature is None
assert source is None
def main():
test_qingping_priority()
test_tion_fallback()
test_tion_fallback_when_qingping_temperature_missing()
test_offline_tion_is_not_used()
test_missing_tion_temperature()
print()
print("=" * 70)
print(
"ALL AUTO TEMPERATURE SOURCE "
"TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
main()
+18 -11
View File
@@ -134,7 +134,7 @@ def load_test_schedule():
return temp_dir, config return temp_dir, config
def heater_calls(calls): def temperature_calls(calls):
return [ return [
call call
for call in calls for call in calls
@@ -142,6 +142,7 @@ def heater_calls(calls):
"heater_on", "heater_on",
"heater_off", "heater_off",
"set_heater", "set_heater",
"set_target_temperature",
} }
] ]
@@ -178,7 +179,12 @@ async def test_auto_does_not_control_heater():
# 09:30 # 09:30
# #
# Обычный SET. # Обычный SET.
# heater=on должен принадлежать ScheduleService. #
# ScheduleService хранит желаемое heater=on,
# но физически heater управлять НЕ должен.
#
# Физический heater будет принадлежать
# единому температурному регулятору.
# -------------------------------------------------- # --------------------------------------------------
await process_at( await process_at(
@@ -198,12 +204,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = heater_calls( calls = temperature_calls(
tion.controller.calls tion.controller.calls
) )
assert calls != [], ( assert calls == [], (
"SET must control heater" "ScheduleService must not control "
"heater or target temperature during SET"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -263,13 +270,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = heater_calls( calls = temperature_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls == [], (
"ScheduleService must not control " "ScheduleService must not control "
"heater during AUTO" "heater or target temperature during AUTO"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -298,13 +305,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = heater_calls( calls = temperature_calls(
tion.controller.calls tion.controller.calls
) )
assert calls != [], ( assert calls == [], (
"ScheduleService must regain heater " "ScheduleService must not control "
"control after AUTO" "heater or target temperature after AUTO"
) )
finally: finally:
+384
View File
@@ -0,0 +1,384 @@
import asyncio
from types import SimpleNamespace
import app.api as api
class FakeTionState:
def __init__(self):
# Физическое состояние Tion.
#
# Специально ставим техническую уставку 30,
# чтобы проверить, что API её не покажет.
self.heater = False
self.heating = False
self.target_temp = 30
self.in_temp = 14
self.fan_speed = 2
def to_dict(self):
return {
"heater": self.heater,
"heating": self.heating,
"target_temp": self.target_temp,
"in_temp": self.in_temp,
"fan_speed": self.fan_speed,
}
class FakeTionService:
def __init__(self):
self.state = FakeTionState()
self.online = True
self.running = True
self.last_seen = None
self.last_error = None
self.execute_calls = []
async def execute(self, operation):
# При активном расписании температурные команды
# НЕ должны идти напрямую сюда.
self.execute_calls.append(operation)
class FakeSchedule:
def __init__(self):
self.running = True
self.paused = False
self.config = SimpleNamespace(
enabled=True,
)
self.override_active = False
self.override_settings = SimpleNamespace(
heater=None,
target_temp=None,
speed=None,
)
self.apply_override_calls = []
def resolve(self):
return SimpleNamespace(
enabled=True,
scheduled_settings=SimpleNamespace(
heater=True,
target_temp=24,
),
auto_active=False,
auto_target_temp=None,
)
async def apply_override(self, settings):
self.apply_override_calls.append(
settings
)
if settings.heater is not None:
self.override_settings.heater = (
settings.heater
)
if settings.target_temp is not None:
self.override_settings.target_temp = (
settings.target_temp
)
self.override_active = True
async def clear_override(self):
self.override_active = False
self.override_settings = SimpleNamespace(
heater=None,
target_temp=None,
speed=None,
)
async def pause(self):
self.paused = True
async def resume(self):
self.paused = False
class FakeAutoController:
def __init__(self, schedule):
self.schedule = schedule
self.manual_heater_enabled = None
self.manual_target_temperature = None
self.reconcile_calls = 0
def effective_temperature_config(self):
if self.schedule.paused:
return SimpleNamespace(
heater_enabled=(
self.manual_heater_enabled
),
target_temp=(
self.manual_target_temperature
),
)
heater = True
target = 24
if self.schedule.override_active:
override = (
self.schedule.override_settings
)
if override.heater is not None:
heater = override.heater
if override.target_temp is not None:
target = override.target_temp
return SimpleNamespace(
heater_enabled=heater,
target_temp=target,
)
def set_manual_heater_enabled(
self,
enabled,
):
self.manual_heater_enabled = enabled
def set_manual_target_temperature(
self,
temperature,
):
self.manual_target_temperature = (
temperature
)
def clear_manual_heater_control(self):
self.manual_heater_enabled = None
self.manual_target_temperature = None
async def reconcile_temperature(self):
self.reconcile_calls += 1
def status(self):
return {
"state": "test",
}
class FakeQingping:
def status(self):
return {
"online": True,
"temperature": 25.5,
}
def prepare():
schedule = FakeSchedule()
auto = FakeAutoController(schedule)
tion = FakeTionService()
api.schedule_service = schedule
api.auto_controller = auto
api.service = tion
api.qingping_service = FakeQingping()
# Чтобы тест не зависел от Elica.
api.get_elica_status = lambda: {
"online": True,
}
# Нам здесь не нужна внутренняя структура
# schedule-status.
api.get_schedule_status = lambda: {
"available": True,
"paused": schedule.paused,
}
return schedule, auto, tion
def test_status_uses_logical_temperature():
schedule, auto, tion = prepare()
status = api.get_status()
# Физически Tion:
assert tion.state.target_temp == 30
assert tion.state.heater is False
# Но пользователь должен видеть:
assert status["tion"]["target_temp"] == 24
assert status["tion"]["heater"] is True
# heating остаётся физическим.
assert status["tion"]["heating"] is False
async def test_temperature_creates_override():
schedule, auto, tion = prepare()
await api.set_temperature(26)
assert schedule.override_active is True
assert (
schedule.override_settings.target_temp
== 26
)
# Изменение только температуры
# не должно само задавать heater.
assert (
schedule.override_settings.heater
is None
)
# Tion напрямую не вызывается.
assert tion.execute_calls == []
# Новый температурный контур
# применяется сразу.
assert auto.reconcile_calls == 1
async def test_heater_creates_override():
schedule, auto, tion = prepare()
await api.set_heater("off")
assert schedule.override_active is True
assert (
schedule.override_settings.heater
is False
)
assert tion.execute_calls == []
assert auto.reconcile_calls == 1
async def test_pause_uses_logical_state():
schedule, auto, tion = prepare()
# Физический heater выключен.
assert tion.state.heater is False
# Но логически отопление разрешено:
config = (
auto.effective_temperature_config()
)
assert config.heater_enabled is True
assert config.target_temp == 24
await api.pause_schedule()
assert schedule.paused is True
# PAUSE должен запомнить ЛОГИЧЕСКОЕ
# состояние, а не физический heater=False.
assert (
auto.manual_heater_enabled
is True
)
assert (
auto.manual_target_temperature
== 24
)
assert auto.reconcile_calls == 1
async def test_resume_clears_manual_state():
schedule, auto, tion = prepare()
schedule.paused = True
auto.manual_heater_enabled = True
auto.manual_target_temperature = 25
await api.resume_schedule()
assert schedule.paused is False
assert (
auto.manual_heater_enabled
is None
)
assert (
auto.manual_target_temperature
is None
)
assert auto.reconcile_calls == 1
def test_temperature_routes():
paths = [
route.path
for route in api.app.routes
]
# increase мы решили удалить полностью.
assert (
"/api/tion/temperature/increase"
not in paths
)
# Основной endpoint должен существовать
# ровно один раз.
assert (
paths.count(
"/api/tion/temperature/{temperature}"
)
== 1
)
async def main():
test_status_uses_logical_temperature()
await test_temperature_creates_override()
await test_heater_creates_override()
await test_pause_uses_logical_state()
await test_resume_clears_manual_state()
test_temperature_routes()
print(
"ALL TEMPERATURE API TESTS PASSED"
)
if __name__ == "__main__":
asyncio.run(main())
+395
View File
@@ -0,0 +1,395 @@
import asyncio
import inspect
from types import SimpleNamespace
from app.auto.controller import AutoController
from app.my_dataclasses import MAX_TARGET_TEMP
class FakeTionController:
def __init__(self):
self.heater = None
self.target_temp = None
self.speed = None
def heater_on(self):
self.heater = True
def heater_off(self):
self.heater = False
def set_target_temperature(
self,
temperature,
):
self.target_temp = temperature
def set_speed(self, speed):
self.speed = speed
class FakeTion:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=14,
)
self.controller = (
FakeTionController()
)
async def execute(self, operation):
result = operation(
self.controller
)
if inspect.isawaitable(result):
await result
class FakeQingping:
def __init__(
self,
*,
online=True,
temperature=25,
):
self.online = online
self.state = SimpleNamespace(
temperature=temperature,
co2=None,
)
class FakeTemperaturePolicy:
def heater_required(
self,
temperature,
target_temp,
heater_on,
):
return temperature < target_temp
class FakeSchedule:
def __init__(
self,
*,
heater=True,
target_temp=24,
auto=False,
auto_target=None,
paused=False,
override=None,
):
self.paused = paused
self.override_active = (
override is not None
)
self.override_settings = (
override
or SimpleNamespace(
heater=None,
target_temp=None,
)
)
self.resolution = SimpleNamespace(
enabled=True,
scheduled_settings=(
SimpleNamespace(
heater=heater,
target_temp=target_temp,
)
),
auto_active=auto,
auto_target_temp=auto_target,
auto_fallback_speed=2,
)
def resolve(self, now=None):
return self.resolution
def make_controller(
schedule,
qingping,
):
tion = FakeTion()
controller = AutoController(
schedule_service=schedule,
qingping_service=qingping,
tion_service=tion,
temperature_policy=(
FakeTemperaturePolicy()
),
)
return controller, tion
async def test_set_online():
schedule = FakeSchedule(
heater=True,
target_temp=24,
)
qingping = FakeQingping(
online=True,
temperature=25.9,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is False
async def test_set_offline():
schedule = FakeSchedule(
heater=True,
target_temp=24,
)
qingping = FakeQingping(
online=False,
temperature=None,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == 24
assert tion.controller.heater is True
async def test_auto_online():
schedule = FakeSchedule(
heater=True,
target_temp=24,
auto=True,
auto_target=22,
)
qingping = FakeQingping(
online=True,
temperature=21,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is True
async def test_auto_offline():
schedule = FakeSchedule(
heater=True,
target_temp=24,
auto=True,
auto_target=22,
)
qingping = FakeQingping(
online=False,
temperature=None,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == 22
assert tion.controller.heater is True
async def test_override_temperature_only():
schedule = FakeSchedule(
heater=False,
target_temp=24,
override=SimpleNamespace(
heater=None,
target_temp=26,
),
)
qingping = FakeQingping(
online=True,
temperature=20,
)
controller, tion = make_controller(
schedule,
qingping,
)
config = (
controller
._get_effective_temperature_config(
schedule.resolve()
)
)
assert config.heater_enabled is False
assert config.target_temp == 26
await controller._process()
# Изменение только температуры
# НЕ включает heater.
assert tion.controller.heater is False
async def test_override_heater_only():
schedule = FakeSchedule(
heater=False,
target_temp=24,
override=SimpleNamespace(
heater=True,
target_temp=None,
),
)
qingping = FakeQingping(
online=True,
temperature=23,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is True
async def test_pause():
schedule = FakeSchedule(
paused=True,
)
qingping = FakeQingping(
online=True,
temperature=25,
)
controller, tion = make_controller(
schedule,
qingping,
)
controller.set_manual_heater_enabled(
True
)
controller.set_manual_target_temperature(
24
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is False
async def test_heater_false_priority():
schedule = FakeSchedule(
heater=False,
target_temp=30,
)
qingping = FakeQingping(
online=True,
temperature=10,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.heater is False
async def main():
await test_set_online()
await test_set_offline()
await test_auto_online()
await test_auto_offline()
await test_override_temperature_only()
await test_override_heater_only()
await test_pause()
await test_heater_false_priority()
print(
"ALL UNIFIED TEMPERATURE "
"TESTS PASSED"
)
if __name__ == "__main__":
asyncio.run(main())
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; }
}
+85
View File
@@ -0,0 +1,85 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<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?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>
<main class="widget exhaust-widget" aria-live="polite">
<header class="widget-header exhaust-widget-header">
<div class="identity">
<span class="brand-icon hood-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none"><path d="M5 4h14M8 4v5l-3 4h14l-3-4V4M9 17c0 1.3-1 2-1 3M12 17c0 1.3-1 2-1 3M15 17c0 1.3-1 2-1 3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
</span>
<span class="identity-copy">
<span class="title-row"><h1>Elica</h1><span id="connection" class="pill muted">Загрузка</span></span>
<small id="header-detail">Вытяжная вентиляция</small>
</span>
</div>
<button id="theme-button" class="theme-button" type="button" title="Сменить тему">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
</button>
</header>
<section class="widget-tile control-card speed-card exhaust-widget-speed" aria-labelledby="speed-title">
<div class="card-title">
<svg class="ui-icon feature-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2 id="speed-title">Скорость вытяжки</h2><p id="speed-note">Фактическая ступень Elica</p></span>
</div>
<div class="hero-control exhaust-widget-hero">
<span class="hero-spacer" aria-hidden="true"></span>
<strong id="speed" class="hero-value value skeleton">0</strong>
<span class="hero-spacer" aria-hidden="true"></span>
</div>
<div class="speed-segments exhaust-widget-segments" role="group" aria-label="Выбор скорости">
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
</div>
<div class="scale-labels exhaust-widget-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span></div>
</section>
<section class="switch-grid exhaust-switch-grid" aria-label="Управление вентиляцией">
<article class="widget-tile switch-card power-card">
<div class="switch-title">
<svg class="ui-icon switch-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
<span><h2>Вытяжка</h2><small id="power-detail">Выключена</small></span>
</div>
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article id="external-fan-card" class="widget-tile switch-card external-fan-card" data-on="false">
<div class="switch-title">
<svg class="ui-icon switch-icon fan-glyph" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2>Внешний</h2><small id="external-fan-detail">OUT5 · NC</small></span>
</div>
<button id="external-fan-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
</section>
<section class="widget-tile info-card exhaust-actions" aria-label="Таймер и свет">
<div class="exhaust-action-row">
<span class="exhaust-action-copy"><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg><span><b>Таймер</b><small id="timer-detail">Выключен</small></span></span>
<button id="timer-toggle" class="glass-switch compact green" type="button" aria-pressed="false">OFF</button>
</div>
<i class="exhaust-divider" aria-hidden="true"></i>
<div class="exhaust-action-row">
<span class="exhaust-action-copy"><svg class="bulb-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 18h6M10 21h4M8.5 14.5A6 6 0 1 1 15.5 14.5c-.9.7-1.5 1.5-1.7 2.5h-3.6c-.2-1-.8-1.8-1.7-2.5Z" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg><span><b>Подсветка</b><small>Импульсное управление</small></span></span>
<button id="light-toggle" class="glass-action" type="button">Переключить</button>
</div>
</section>
<button id="open-panel" class="open-panel" type="button">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 4h14M8 4v5l-3 4h14l-3-4V4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>Открыть панель вытяжки</span><b aria-hidden="true">↗</b>
</button>
</main>
<script type="module" src="/ui/static/js/elica-widget.js?v=20260927-1"></script>
</body>
</html>
+118
View File
@@ -0,0 +1,118 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<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?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>
<main class="climate-panel exhaust-panel" aria-live="polite">
<header class="panel-header exhaust-header">
<div class="identity exhaust-identity">
<span class="hood-mark glass-tile" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M5 4h14M8 4v5l-3 4h14l-3-4V4M9 17c0 1.3-1 2-1 3M12 17c0 1.3-1 2-1 3M15 17c0 1.3-1 2-1 3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
<span class="identity-copy">
<span class="title-row"><h1>Elica</h1><span id="connection" class="pill muted">Загрузка</span></span>
<small>Кухонная вытяжка и внешний вытяжной вентилятор</small>
</span>
</div>
<div class="header-tools">
<div class="ventilation-badge glass-tile exhaust-badge">
<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/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="Обновить данные">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M20 11a8 8 0 1 0-2.34 5.66M20 5v6h-6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<button id="theme-button" class="icon-button" type="button" title="Сменить тему">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
</button>
</div>
</header>
<section class="primary-controls exhaust-primary" aria-label="Основное управление">
<article class="control-card glass-tile speed-card exhaust-speed-card">
<div class="card-title">
<svg class="ui-icon feature-icon fan-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2>Скорость вытяжки</h2><p id="speed-caption">Скорость определяется по индикаторам Elica</p></span>
</div>
<div class="hero-control exhaust-hero-control">
<span class="hero-spacer" aria-hidden="true"></span>
<strong id="speed-value" class="hero-value">—</strong>
<span class="hero-spacer" aria-hidden="true"></span>
</div>
<div class="speed-segments exhaust-speed-segments" role="group" aria-label="Выбор скорости">
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
</div>
<div class="speed-labels exhaust-speed-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span></div>
</article>
<article class="switch-card glass-tile power-card exhaust-switch-card">
<div class="card-title compact">
<svg class="ui-icon feature-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
<span><h2>Питание</h2><p id="power-caption">Ожидаем состояние панели</p></span>
</div>
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article id="external-fan-card" class="switch-card glass-tile exhaust-fan-card exhaust-switch-card" data-on="false">
<div class="card-title compact">
<svg class="ui-icon feature-icon fan-glyph" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2>Внешний вентилятор</h2><p id="external-fan-caption">Ожидаем состояние OUT5</p></span>
</div>
<button id="external-fan-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article class="control-card glass-tile action-card exhaust-action-card">
<div class="action-row">
<div class="action-copy">
<svg class="ui-icon feature-icon orange" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg>
<div><h2>Таймер</h2><p id="timer-caption">По миганию индикатора скорости</p></div>
</div>
<button id="timer-toggle" class="glass-switch orange compact-switch" type="button" aria-pressed="false">OFF</button>
</div>
<div class="glass-divider"></div>
<div class="action-row">
<div class="action-copy">
<svg class="bulb-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 18h6M10 21h4M8.5 14.5A6 6 0 1 1 15.5 14.5c-.9.7-1.5 1.5-1.7 2.5h-3.6c-.2-1-.8-1.8-1.7-2.5Z" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
<div><h2>Подсветка</h2><p>Без обратной связи по состоянию</p></div>
</div>
<button id="light-toggle" class="aero-button" type="button">Переключить</button>
</div>
</article>
</section>
<section class="content-section glass-section exhaust-status-section" aria-labelledby="status-title">
<div class="section-title">
<div><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#settings"></use></svg><h2 id="status-title">Связь с контроллером</h2></div>
<span id="updated-at" class="updated">—</span>
</div>
<div class="status-grid">
<article class="status-item glass-tile"><span>MQTT</span><strong id="mqtt-status">—</strong></article>
<article class="status-item glass-tile"><span>ESP32</span><strong id="device-status">—</strong></article>
<article class="status-item glass-tile"><span>Панель Elica</span><strong id="feedback-status">—</strong></article>
<article class="status-item glass-tile"><span>OUT5 физически</span><strong id="relay5-status">—</strong></article>
</div>
<p id="diagnostic-note" class="diagnostic-note">Получаем данные…</p>
</section>
</main>
<script type="module" src="/ui/static/js/elica.js?v=20260927-1"></script>
</body>
</html>
+5 -3
View File
@@ -179,7 +179,9 @@ export const api = {
export function configureTheme(button) { export function configureTheme(button) {
const allowed = ["auto", "light", "dark"]; const allowed = ["auto", "light", "dark"];
const explicit = query.get("theme"); 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 apply = () => {
const dark = mode === "dark" || (mode === "auto" && matchMedia("(prefers-color-scheme: dark)").matches); 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", () => { if (button) button.addEventListener("click", () => {
mode = allowed[(allowed.indexOf(mode) + 1) % allowed.length]; mode = allowed[(allowed.indexOf(mode) + 1) % allowed.length];
localStorage.setItem("tion-theme", mode); localStorage.setItem("climate-theme", mode);
apply(); apply();
}); });
@@ -295,7 +297,7 @@ export function showToast(message, error = false) {
} }
export function panelUrl(themeMode = "auto", hash = "") { export function panelUrl(themeMode = "auto", hash = "") {
const url = new URL("/ui/panel", window.location.origin); const url = new URL("/ui/tion", window.location.origin);
url.searchParams.set("theme", themeMode); url.searchParams.set("theme", themeMode);
if (isDemo) url.searchParams.set("demo", "1"); if (isDemo) url.searchParams.set("demo", "1");
url.hash = hash; url.hash = hash;
+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-color", airPalette.color);
airCard.style.setProperty("--air-glow", airPalette.glow); airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`; $("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setText("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1)); setText("#room-temp", numberOrDash(sensor.temperature, 1));
setText("#humidity", numberOrDash(sensor.humidity)); setText("#humidity", numberOrDash(sensor.humidity));
setText("#current-time", schedule.current_time || tion.device_time || "—"); setText("#current-time", schedule.current_time || tion.device_time || "—");
setText("#next-time", schedule.next_time || "—"); setText("#next-time", schedule.next_time || "—");
+2 -2
View File
@@ -74,7 +74,7 @@ function renderAir(sensor, tion) {
airCard.style.setProperty("--air-glow", airPalette.glow); airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`; $("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad"); setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad");
text("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1)); text("#room-temp", numberOrDash(sensor.temperature, 1));
text("#humidity", numberOrDash(sensor.humidity)); text("#humidity", numberOrDash(sensor.humidity));
text("#pm25", numberOrDash(sensor.pm25)); text("#pm25", numberOrDash(sensor.pm25));
text("#pm10", numberOrDash(sensor.pm10)); text("#pm10", numberOrDash(sensor.pm10));
@@ -122,7 +122,7 @@ function render(status) {
$("#mode-outside").classList.toggle("active", tion.mode === "outside"); $("#mode-outside").classList.toggle("active", tion.mode === "outside");
$("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation"); $("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation");
text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция"); text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция");
text("#outside-temp", numberOrDash(tion.out_temp)); text("#outside-temp", numberOrDash(tion.in_temp));
text("#filter-remain", numberOrDash(tion.filter_remain)); text("#filter-remain", numberOrDash(tion.filter_remain));
const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2)); const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2));
$("#filter-progress").style.width = `${filterPercent}%`; $("#filter-progress").style.width = `${filterPercent}%`;
+3 -3
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark"> <meta name="color-scheme" content="light dark">
<title>Tion 4S — виджет</title> <title>Tion 4S — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css"> <link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/widget.css"> <link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1">
</head> </head>
<body> <body>
<div class="ambient" aria-hidden="true"></div> <div class="ambient" aria-hidden="true"></div>
@@ -124,6 +124,6 @@
</button> </button>
<span id="demo-note" class="demo-note" hidden>Демонстрационный режим — команды не отправляются устройству</span> <span id="demo-note" class="demo-note" hidden>Демонстрационный режим — команды не отправляются устройству</span>
</main> </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> </body>
</html> </html>
+3 -3
View File
@@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark"> <meta name="color-scheme" content="light dark">
<title>Tion 4S — панель управления</title> <title>Tion 4S — панель управления</title>
<link rel="stylesheet" href="/ui/static/css/base.css"> <link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1">
<link rel="stylesheet" href="/ui/static/css/panel.css"> <link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1">
</head> </head>
<body> <body>
<div class="ambient"></div> <div class="ambient"></div>
@@ -158,6 +158,6 @@
</footer> </footer>
</form> </form>
</dialog> </dialog>
<script type="module" src="/ui/static/js/panel.js"></script> <script type="module" src="/ui/static/js/tion.js?v=2"></script>
</body> </body>
</html> </html>