26 Commits
Author SHA1 Message Date
Dmitriy 536435aac2 Merge branch 'release' into dev_fedorov 2026-09-27 00:11:34 +03:00
Dmitriy 869c826774 work: добавил фалйы форм в отслеживание 2026-09-27 00:10:43 +03:00
Dmitriy c6607a75ab Merge branch 'release' into dev_fedorov 2026-09-27 00:00:46 +03:00
Dmitriy bf832ac86b work: функционал для работы с вятяжкой
* Добавил полный функционал управления elica через esp32 по MQTT
* Добавил в прошивку принудительную блокировку внешнего винтелятора при работающей вытяжке
* Добавил веб-панели для управления вытяжкой
2026-09-26 23:59:01 +03:00
Dmitriy 3b3c7a3f13 work: Добавил защиту от постоянного нажатия кнопки. В случае исключения всегда отправится команда на отжатие. Также добавил синхронизацию начального состояния вытяжки. 2026-09-22 23:07:40 +03:00
Dmitriy 75950a7eae work: Добавил высокоуровневый контроллер для работы с вытяжкой. 2026-09-22 22:45:33 +03:00
Dmitriy 4169b0c3e5 work: Низкий уровень работы с Элика завершен. Добавил логику для отслеживания состояния вытяжки. 2026-09-22 22:01:57 +03:00
Dmitriy 8ece9ba131 work: Добавил интерфейс для управления кнопками вытяжки. 2026-09-22 21:36:39 +03:00
Dmitriy f6e00842d8 work: Добавил функционал пульсирующего включения. Т.е. вкл\выкл. 2026-09-22 21:35:10 +03:00
Dmitriy 5e04013e2d work: Добавил функционал проверки состояний входов 2026-09-22 21:23:05 +03:00
Dmitriy 8d61712642 work: Изменил конфиг сервиса вытяжки для реальной платы. Добавил yaml конфигурацию платы. Сейчас доступны MQTT -прием статуса и управление реле. 2026-09-22 21:16:14 +03:00
Dmitriy 32f3fc754f work: добавил каркас под управление вытяжкой! 2026-09-20 18:24:17 +03:00
Dmitriy 9fd1b3976d Merge branch 'release' into dev_fedorov 2026-09-20 14:19:52 +03:00
Dmitriy 3754bbc380 work : добавил экспорт метрик для Prometheus 2026-09-20 14:18:40 +03:00
Dmitriy a000fb6c44 work : изменил расписание на реальное. 2026-09-20 13:42:34 +03:00
Dmitriy be4c2c403c work : переименовал проект 2026-09-20 12:55:06 +03:00
Fedorov Dmitriy e636bc53ca Merge branch 'release' into dev_fedorov 2026-09-20 11:29:58 +03:00
Fedorov Dmitriy fdb798a430 work : виджет стал более "горизонтальным" 2026-09-20 11:28:48 +03:00
Fedorov Dmitriy 33cdb205b3 Merge branch 'release' into dev_fedorov 2026-09-20 02:02:34 +03:00
Fedorov Dmitriy 8069ab65f2 work : добавил web в отслеживание 2026-09-20 02:01:44 +03:00
Fedorov Dmitriy 455d191ea1 Merge branch 'release' into dev_fedorov 2026-09-20 02:00:40 +03:00
Fedorov Dmitriy 0172b6bcf2 work: добавлин web интерфейс. 2026-09-20 01:59:36 +03:00
Fedorov Dmitriy 65cf547c6c Merge branch 'release' into dev_fedorov 2026-09-19 23:05:03 +03:00
Fedorov Dmitriy 741be479a6 work: исправил порядок объявления классов в app/auto/config TemperatureConfig объявлялся после AutoConfig в котором использовался. 2026-09-19 22:51:36 +03:00
Fedorov Dmitriy 958691a481 doc: поправил зависимости и расписание 2026-09-19 19:14:08 +03:00
Fedorov Dmitriy c22e8bc71d work: добавил режим ручного управления. Теперь можно отключать расписание! 2026-09-19 19:04:45 +03:00
53 changed files with 1073 additions and 8292 deletions
+4 -4
View File
@@ -1,8 +1,8 @@
[version] [version]
major = 1 major = 1
minor = 5 minor = 4
patch = 9 patch = 0
[build] [build]
date = "2026-09-29" date = "2026-09-26"
time = "23:38:58" time = "23:54:18"
+116 -285
View File
@@ -11,7 +11,6 @@ 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.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,
@@ -33,7 +32,7 @@ from app.my_dataclasses import (
from app.auto import ( from app.auto import (
AutoController, AutoController,
Co2SpeedPolicy, Co2SpeedPolicy,
load_auto_config_components, load_auto_config,
) )
from app.auto.temperature_policy import TemperaturePolicy from app.auto.temperature_policy import TemperaturePolicy
@@ -138,126 +137,44 @@ async def lifespan(app: FastAPI):
schedule_load_error = None schedule_load_error = None
try: try:
auto_config = load_auto_config_components(AUTO_CONFIG_FILE) auto_config = load_auto_config(AUTO_CONFIG_FILE)
auto_interval = auto_config.check_interval auto_policy = Co2SpeedPolicy(
base_speed=(
auto_config.co2.base_speed
),
thresholds=(
auto_config.co2.thresholds
),
hysteresis=(
auto_config.co2.hysteresis
),
)
auto_errors = dict(auto_config.errors) temperature_policy = TemperaturePolicy(auto_config.temperature)
# -------------------------------------------------- auto_interval = (auto_config.check_interval)
# CO2 policy
# --------------------------------------------------
auto_policy = None
if auto_config.co2 is not None:
try: auto_load_error = None
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
if (
auto_config.temperature
is not None
):
try:
temperature_policy = TemperaturePolicy(auto_config.temperature)
except Exception as exc:
auto_errors[
"temperature_policy"
] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Elica Assist
# --------------------------------------------------
elica_assist = None
if (
auto_config.elica_assist
is not None
):
try:
elica_assist = ElicaAutoAssistState(auto_config.elica_assist)
except Exception as exc:
auto_errors[
"elica_assist"
] = (
f"{type(exc).__name__}: {exc}"
)
# --------------------------------------------------
# Общая диагностика
# --------------------------------------------------
if auto_errors:
auto_load_error = "; ".join(
(
f"{name}: {error}"
)
for name, error
in auto_errors.items()
)
else:
auto_load_error = None
except Exception as exc: except Exception as exc:
# Здесь остаются только ошибки,
# из-за которых невозможно разобрать
# auto.yaml вообще.
auto_policy = None auto_policy = None
temperature_policy = None temperature_policy = None
elica_assist = None
# Безопасный встроенный интервал нужен,
# потому что auto.yaml сейчас недоступен.
auto_interval = 5.0 auto_interval = 5.0
auto_load_error = ( auto_load_error = (
f"{type(exc).__name__}: {exc}" f"{type(exc).__name__}: {exc}"
) )
# --------------------------------------------------
# AutoController создаётся даже если, например,
# CO2 policy не загрузилась.
#
# policy=None даст fallback скорости,
# но TemperaturePolicy при этом может работать.
# --------------------------------------------------
auto_controller = AutoController( auto_controller = AutoController(
schedule_service=schedule_service, schedule_service=schedule_service,
qingping_service=qingping_service, qingping_service=qingping_service,
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,
) )
@@ -333,47 +250,43 @@ async def ui_root():
# controllers/widgets without overloading generic "panel"/"widget" names. # controllers/widgets without overloading generic "panel"/"widget" names.
@app.get("/ui/tion", include_in_schema=False) @app.get("/ui/tion", include_in_schema=False)
async def ui_tion(): async def ui_tion():
return FileResponse(WEB_ROOT / "tion.html", headers={"Cache-Control": "no-store"}) return FileResponse(WEB_ROOT / "tion.html")
@app.get("/ui/tion-widget", include_in_schema=False) @app.get("/ui/tion-widget", include_in_schema=False)
async def ui_tion_widget(): async def ui_tion_widget():
return FileResponse(WEB_ROOT / "tion-widget.html", headers={"Cache-Control": "no-store"}) return FileResponse(WEB_ROOT / "tion-widget.html")
@app.get("/ui/elica", include_in_schema=False) @app.get("/ui/elica", include_in_schema=False)
async def ui_elica(): async def ui_elica():
return FileResponse(WEB_ROOT / "elica.html", headers={"Cache-Control": "no-store"}) return FileResponse(WEB_ROOT / "elica.html")
@app.get("/ui/elica-widget", include_in_schema=False) @app.get("/ui/elica-widget", include_in_schema=False)
async def ui_elica_widget(): async def ui_elica_widget():
return FileResponse(WEB_ROOT / "elica-widget.html", headers={"Cache-Control": "no-store"}) return FileResponse(WEB_ROOT / "elica-widget.html")
# Backward-compatible aliases for existing bookmarks/Homarr embeds. # Backward-compatible aliases for existing bookmarks/Homarr embeds.
@app.get("/ui/panel", include_in_schema=False) @app.get("/ui/panel", include_in_schema=False)
async def ui_panel_legacy(request: Request): async def ui_panel_legacy():
suffix = f"?{request.url.query}" if request.url.query else "" return RedirectResponse(url="/ui/tion")
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_legacy(request: Request): async def ui_widget_legacy():
suffix = f"?{request.url.query}" if request.url.query else "" return RedirectResponse(url="/ui/tion-widget")
return RedirectResponse(url=f"/ui/tion-widget{suffix}")
@app.get("/ui/exhaust", include_in_schema=False) @app.get("/ui/exhaust", include_in_schema=False)
async def ui_exhaust_legacy(request: Request): async def ui_exhaust_legacy():
suffix = f"?{request.url.query}" if request.url.query else "" return RedirectResponse(url="/ui/elica")
return RedirectResponse(url=f"/ui/elica{suffix}")
@app.get("/ui/exhaust-widget", include_in_schema=False) @app.get("/ui/exhaust-widget", include_in_schema=False)
async def ui_exhaust_widget_legacy(request: Request): async def ui_exhaust_widget_legacy():
suffix = f"?{request.url.query}" if request.url.query else "" return RedirectResponse(url="/ui/elica-widget")
return RedirectResponse(url=f"/ui/elica-widget{suffix}")
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
@@ -403,42 +316,6 @@ def get_status() -> dict:
state = service.state state = service.state
tion_status = (
state.to_dict()
if state is not None
else None
)
# --------------------------------------------------
# В ручном режиме UI должен видеть желание
# пользователя, а не техническое состояние
# внешнего регулятора.
# --------------------------------------------------
if (
tion_status is not None
and auto_controller is not None
):
temperature_config = (auto_controller.effective_temperature_config())
if (
temperature_config.heater_enabled
is not None
):
tion_status["heater"] = (
temperature_config.heater_enabled
)
if (
temperature_config.target_temp
is not None
):
tion_status["target_temp"] = (
temperature_config.target_temp
)
return { return {
"online": service.online, "online": service.online,
"running": service.running, "running": service.running,
@@ -451,8 +328,11 @@ def get_status() -> dict:
"last_error": service.last_error, "last_error": service.last_error,
"tion": tion_status, "tion": (
state.to_dict()
if state is not None
else None
),
"auto": get_auto_status(), "auto": get_auto_status(),
"qingping": qingping_service.status(), "qingping": qingping_service.status(),
@@ -505,16 +385,17 @@ def get_effective_speed() -> int:
def get_effective_temperature() -> int: def get_effective_temperature() -> int:
if auto_controller is not None: if (
schedule_service is not None
config = ( and schedule_service.override_active
auto_controller and schedule_service.override_settings.target_temp is not None
.effective_temperature_config() ):
return (
schedule_service
.override_settings
.target_temp
) )
if config.target_temp is not None:
return config.target_temp
state = service.state state = service.state
if state is None: if state is None:
@@ -565,60 +446,6 @@ async def execute_command(operation, override: ScheduledSettings | None = None):
return get_status() return get_status()
async def execute_temperature_command(
operation,
settings: ScheduledSettings,
):
try:
if (
auto_controller is not None
and schedule_service is not None
and schedule_service.running
and schedule_service.config.enabled
):
# ------------------------------------------
# PAUSE = полноценный ручной режим.
# ------------------------------------------
if schedule_service.paused:
if settings.heater is not None:
auto_controller.set_manual_heater_enabled(settings.heater)
if settings.target_temp is not None:
auto_controller.set_manual_target_temperature(settings.target_temp)
# ------------------------------------------
# SET / AUTO = temporary override.
# ------------------------------------------
else:
await schedule_service.apply_override(settings)
# Не ждём следующего 5-секундного цикла.
await auto_controller.reconcile_temperature()
else:
# Fallback, если расписание/AutoController
# вообще не работают.
await service.execute(operation)
except Exception as exc:
raise HTTPException(
status_code=503,
detail={
"message": "Tion unavailable",
"error": (
f"{type(exc).__name__}: {exc}"
),
},
) from exc
return get_status()
def occurrence_to_dict(occurrence) -> dict | None: def occurrence_to_dict(occurrence) -> dict | None:
@@ -766,6 +593,7 @@ def get_auto_status() -> dict:
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Status # Status
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/status") @app.get("/api/status")
async def status(): async def status():
return get_status() return get_status()
@@ -774,6 +602,7 @@ async def status():
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Elica / exhaust # Elica / exhaust
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/elica/status") @app.get("/api/elica/status")
async def elica_status(): async def elica_status():
return get_elica_status() return get_elica_status()
@@ -822,6 +651,7 @@ async def set_external_fan(state: Literal["on", "off"]):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Power # Power
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/power/{state}") @app.post("/api/tion/power/{state}")
async def set_power(state: Literal["on", "off"]): async def set_power(state: Literal["on", "off"]):
@@ -841,6 +671,7 @@ async def set_power(state: Literal["on", "off"]):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Fan speed increase / decrease # Fan speed increase / decrease
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/speed/increase") @app.post("/api/tion/speed/increase")
async def increase_speed(): async def increase_speed():
@@ -902,57 +733,96 @@ async def set_speed(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Heater # Heater
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/heater/{state}") @app.post("/api/tion/heater/{state}")
async def set_heater( async def set_heater(state: Literal["on", "off"]):
state: Literal["on", "off"],
):
enabled = state == "on" enabled = state == "on"
operation = ( if enabled:
(lambda tion: tion.heater_on()) operation = lambda tion: tion.heater_on()
if enabled else:
else operation = lambda tion: tion.heater_off()
(lambda tion: tion.heater_off())
return await execute_command(
operation,
ScheduledSettings(heater=enabled),
) )
return await execute_temperature_command( # ----------------------------------------------------------------------
operation, # Target temperature increase / decrease
# ----------------------------------------------------------------------
@app.post("/api/tion/temperature/increase")
async def increase_temperature():
current_temperature = get_effective_temperature()
new_temperature = min(current_temperature + 1, MAX_TARGET_TEMP)
if new_temperature == current_temperature:
return get_status()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings( ScheduledSettings(
heater=enabled, target_temp=new_temperature,
), ),
) )
@app.post("/api/tion/temperature/decrease")
async def decrease_temperature():
current_temperature = get_effective_temperature()
new_temperature = max(current_temperature - 1, MIN_TARGET_TEMP)
if new_temperature == current_temperature:
return get_status()
return await execute_command(
lambda tion:
tion.set_target_temperature(
new_temperature
),
ScheduledSettings(
target_temp=new_temperature,
),
)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Target temperature # Target temperature
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/temperature/{temperature}") @app.post("/api/tion/temperature/{temperature}")
async def set_temperature( async def set_temperature(
temperature: Annotated[ temperature: Annotated[
int, int,
Path( Path(
ge=MIN_TARGET_TEMP, ge=MIN_TARGET_TEMP,
le=MAX_TARGET_TEMP, le=MAX_TARGET_TEMP,
), ),
], ],):
):
return await execute_temperature_command( return await execute_command(
lambda tion: lambda tion:
tion.set_target_temperature( tion.set_target_temperature(temperature),
temperature ScheduledSettings(target_temp=temperature),
),
ScheduledSettings(
target_temp=temperature,
),
) )
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Air mode # Air mode
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/mode/{mode}") @app.post("/api/tion/mode/{mode}")
async def set_mode( async def set_mode(
mode: str, mode: str,
@@ -984,6 +854,7 @@ async def set_mode(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Sound # Sound
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/sound/{value}") @app.post("/api/tion/sound/{value}")
async def set_sound( async def set_sound(
value: Literal["on", "off"], value: Literal["on", "off"],
@@ -1006,6 +877,7 @@ async def set_sound(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Light # Light
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.post("/api/tion/light/{value}") @app.post("/api/tion/light/{value}")
async def set_light( async def set_light(
value: Literal["on", "off"], value: Literal["on", "off"],
@@ -1027,6 +899,7 @@ async def set_light(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Переход в auto # Переход в auto
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/schedule/config") @app.get("/api/schedule/config")
async def get_schedule_config(): async def get_schedule_config():
try: try:
@@ -1116,9 +989,6 @@ async def clear_schedule_override():
await schedule_service.clear_override() await schedule_service.clear_override()
if auto_controller is not None:
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -1137,42 +1007,8 @@ async def pause_schedule():
detail="Schedule service unavailable", detail="Schedule service unavailable",
) )
# ВАЖНО:
# получаем логические настройки ДО pause(),
# потому что там ещё действует SET/AUTO/override.
temperature_config = None
if auto_controller is not None:
temperature_config = (
auto_controller
.effective_temperature_config()
)
await schedule_service.pause() await schedule_service.pause()
if (
auto_controller is not None
and temperature_config is not None
):
if (
temperature_config.heater_enabled
is not None
):
auto_controller.set_manual_heater_enabled(
temperature_config.heater_enabled
)
if (
temperature_config.target_temp
is not None
):
auto_controller.set_manual_target_temperature(
temperature_config.target_temp
)
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
@@ -1192,11 +1028,6 @@ async def resume_schedule():
await schedule_service.resume() await schedule_service.resume()
if auto_controller is not None:
auto_controller.clear_manual_heater_control()
await auto_controller.reconcile_temperature()
return { return {
"ok": True, "ok": True,
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
-4
View File
@@ -1,9 +1,7 @@
from .config import ( from .config import (
AutoConfig, AutoConfig,
AutoConfigComponents,
Co2Config, Co2Config,
load_auto_config, load_auto_config,
load_auto_config_components,
) )
from .co2_policy import ( from .co2_policy import (
@@ -21,6 +19,4 @@ __all__ = [
"load_auto_config", "load_auto_config",
"Co2SpeedPolicy", "Co2SpeedPolicy",
"AutoController", "AutoController",
"AutoConfigComponents",
"load_auto_config_components",
] ]
+70 -277
View File
@@ -30,21 +30,6 @@ 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,
@@ -54,23 +39,8 @@ 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):
@@ -276,155 +246,14 @@ def _parse_co2(value: Any) -> Co2Config:
thresholds=thresholds, thresholds=thresholds,
) )
def _parse_temperature(value: Any) -> TemperatureConfig:
data = _require_dict( def load_auto_config(path: str | Path) -> AutoConfig:
"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)
@@ -438,7 +267,6 @@ def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
"check_interval", "check_interval",
"co2", "co2",
"temperature", "temperature",
"elica_assist",
} }
if unknown: if unknown:
@@ -460,8 +288,10 @@ def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
) )
if ( if (
type(check_interval) type(check_interval) not in {
not in {int,float,} int,
float,
}
): ):
raise ValueError( raise ValueError(
"check_interval must be a number" "check_interval must be a number"
@@ -472,125 +302,88 @@ def _load_auto_root(path: str | Path) -> tuple[dict, int, float]:
"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("co2 config is required") raise ValueError(
co2 = _parse_co2(data["co2"]) "co2 config is required"
)
co2 = _parse_co2(
data["co2"]
)
# -------------------------------------------------- # --------------------------------------------------
# Temperature # Temperature
# -------------------------------------------------- # --------------------------------------------------
if "temperature" not in data: if "temperature" not in data:
raise ValueError("temperature config is required") raise ValueError(
"temperature config is required"
)
temperature = _parse_temperature(data["temperature"]) temperature_data = _require_dict(
"temperature",
data["temperature"],
)
unknown_temperature = (
set(temperature_data)
- {
"hysteresis",
}
)
if unknown_temperature:
raise ValueError(
f"Unknown temperature config fields: "
f"{sorted(unknown_temperature)}"
)
temperature_hysteresis = (
temperature_data.get(
"hysteresis"
)
)
if (
type(temperature_hysteresis)
not in {
int,
float,
}
):
raise ValueError(
"temperature.hysteresis "
"must be a number"
)
temperature_hysteresis = float(
temperature_hysteresis
)
if temperature_hysteresis < 0:
raise ValueError(
"temperature.hysteresis "
"must be >= 0"
)
temperature = TemperatureConfig(
hysteresis=temperature_hysteresis,
)
# -------------------------------------------------- # --------------------------------------------------
# Elica Auto Assist # Result
# -------------------------------------------------- # --------------------------------------------------
if "elica_assist" not in data:
raise ValueError("elica_assist config is required")
elica_assist = _parse_elica_assist(data["elica_assist"])
return AutoConfig( return AutoConfig(
version=version, version=version,
check_interval=check_interval, check_interval=float(
check_interval
),
co2=co2, co2=co2,
temperature=temperature, temperature=temperature,
elica_assist=elica_assist,
) )
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,
)
+182 -667
View File
File diff suppressed because it is too large Load Diff
-181
View File
@@ -1,181 +0,0 @@
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"
)
+17 -40
View File
@@ -20,13 +20,11 @@ class ElicaController:
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, 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._speed_inter_press_delay = max(0.0, speed_inter_press_delay)
self._last_speed_press_finished_at: float | None = None
# Не допускаем одновременное выполнение нескольких # Не допускаем одновременное выполнение нескольких
# последовательностей нажатий кнопок. # последовательностей нажатий кнопок.
@@ -113,6 +111,7 @@ 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()
@@ -121,45 +120,10 @@ 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.
@@ -181,12 +145,20 @@ class ElicaController:
# У Elica кнопка Speed сама включает вытяжку. Первое # У Elica кнопка Speed сама включает вытяжку. Первое
# нажатие из состояния OFF запускает её на скорости 1. # нажатие из состояния OFF запускает её на скорости 1.
# Поэтому при выборе скорости Power здесь не нажимаем. # Поэтому при выборе скорости Power здесь не нажимаем.
await self._press_speed_locked() await self._service.press_speed()
state = await self._wait_state( state = await self._wait_state(
lambda value: value.power and value.speed == 1, lambda value: value.power and value.speed == 1,
"speed 1", "speed 1",
) )
# После физического отпускания кнопки Elica нужен
# небольшой гарантированный интервал до следующего
# нажатия. Иначе при быстром наборе 2/3/4 контроллер
# вытяжки иногда воспринимает два импульса как одно
# длинное нажатие или просто игнорирует следующий.
if speed != 1 and self._speed_inter_press_delay > 0:
await asyncio.sleep(self._speed_inter_press_delay)
# Если питание уже было включено, но индикатор скорости ещё # Если питание уже было включено, но индикатор скорости ещё
# не успел синхронизироваться, ждём корректное значение 1-4. # не успел синхронизироваться, ждём корректное значение 1-4.
if not 1 <= state.speed <= 4: if not 1 <= state.speed <= 4:
@@ -201,7 +173,7 @@ class ElicaController:
for _ in range(presses): for _ in range(presses):
expected_speed = current_speed % 4 + 1 expected_speed = current_speed % 4 + 1
await self._press_speed_locked() await self._service.press_speed()
state = await self._wait_state( state = await self._wait_state(
lambda value, expected=expected_speed: ( lambda value, expected=expected_speed: (
@@ -212,6 +184,11 @@ class ElicaController:
current_speed = expected_speed current_speed = expected_speed
# Не нажимаем Speed повторно сразу после отпускания
# предыдущего импульса. Это особенно важно для переходов
# на 4-ю скорость, где требуется несколько нажатий подряд.
if current_speed != speed and self._speed_inter_press_delay > 0:
await asyncio.sleep(self._speed_inter_press_delay)
return state return state
+8 -50
View File
@@ -524,68 +524,26 @@ class ElicaService:
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: if not 1 <= relay <= 8:
raise ValueError( raise ValueError("Relay number must be between 1 and 8")
"Relay number must be between 1 and 8"
)
duration_ms = ( duration_ms = pulse_ms if pulse_ms is not None else self._config.pulse_ms
pulse_ms
if pulse_ms is not None
else self._config.pulse_ms
)
# -------------------------------------------------- self.set_relay(relay, True)
# ВАЖНО:
# после MQTT connect состояния входов панели
# и состояний реле приходят независимо.
#
# Нельзя начинать импульс, пока мы не получили
# хотя бы первое достоверное состояние именно
# этого OUT.
# --------------------------------------------------
await self.wait_relay_feedback_ready(relay)
# --------------------------------------------------
# Перед новым импульсом реле обязано быть OFF.
#
# Это дополнительно восстанавливает состояние,
# если предыдущая операция была аварийно
# прервана на включённом реле.
# --------------------------------------------------
if self.relay_state(relay):
self.set_relay(relay,False)
await self.wait_relay_state(relay,False)
# --------------------------------------------------
# Нажатие
# --------------------------------------------------
self.set_relay(relay,True)
try: try:
await self.wait_relay_state(relay,True) await self.wait_relay_state(relay, True)
await asyncio.sleep(duration_ms / 1000) await asyncio.sleep(duration_ms / 1000)
finally: finally:
# Relay обязательно пытаемся отпустить,
# даже если подтверждение ON не пришло.
try: try:
self.set_relay(relay,False) self.set_relay(relay, False)
except Exception: except Exception:
logger.exception("Failed to release Elica relay %s",relay) logger.exception("Failed to release Elica relay %s", relay)
# И ждём подтверждённого отпускания. await self.wait_relay_state(relay, False)
await self.wait_relay_state(relay,False)
+1 -1
View File
@@ -10,7 +10,7 @@ from typing import Any, Mapping
TION_MAC = "d1:74:9b:eb:ee:a6" TION_MAC = "d1:74:9b:eb:ee:a6"
QINGPING_MAC = "CCB5D131BA93" QINGPING_MAC = "CCB5D131BA93"
QINGPING_MQTT_HOST = "192.168.7.100" QINGPING_MQTT_HOST = "192.168.7.3"
QINGPING_MQTT_PORT = 1883 QINGPING_MQTT_PORT = 1883
# ESP32-контроллер вытяжки Elica подключён к Mosquitto на mini-PC/NAS. # ESP32-контроллер вытяжки Elica подключён к Mosquitto на mini-PC/NAS.
+2 -90
View File
@@ -1,7 +1,4 @@
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
@@ -10,7 +7,6 @@ from .models import TionState
from app.my_dataclasses import * from app.my_dataclasses import *
logger = logging.getLogger(__name__)
class TionController: class TionController:
""" """
@@ -92,23 +88,12 @@ 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"
@@ -165,18 +150,8 @@ 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:
@@ -298,66 +273,3 @@ class TionController:
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)
@@ -24,12 +24,3 @@ co2:
temperature: temperature:
hysteresis: 0.5 hysteresis: 0.5
elica_assist:
enabled: true
speed_map:
4: 1
5: 2
6: 3
@@ -36,6 +36,7 @@ templates:
weekend: weekend:
- time: "10:00" - time: "10:00"
action: action:
power: on power: on
@@ -61,12 +62,16 @@ templates:
speed: 1 speed: 1
days: days:
mon: workday mon: workday
tue: workday tue: workday
wed: workday wed: workday
thu: workday thu: workday
fri: workday fri: workday
sat: weekend sat: weekend
sun: weekend sun: weekend
@@ -1,425 +0,0 @@
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())
@@ -1,355 +0,0 @@
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())
@@ -1,422 +0,0 @@
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())
@@ -1,555 +0,0 @@
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())
@@ -1,314 +0,0 @@
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())
@@ -1,341 +0,0 @@
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
@@ -1,368 +0,0 @@
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())
@@ -1,335 +0,0 @@
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())
@@ -1,375 +0,0 @@
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())
@@ -1,316 +0,0 @@
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())
@@ -1,448 +0,0 @@
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,9 +561,15 @@ class ScheduleService:
if resolution.auto_active: if resolution.auto_active:
# В режиме AUTO скорость принадлежит # В режиме AUTO скорость принадлежит
# AutoController. # AutoController.
#
# Остальные параметры расписания
# (power, heater, temperature, mode...)
# должны продолжать работать.
settings = replace( settings = replace(
settings, settings,
speed=None, speed=None,
heater=None,
target_temp=None,
) )
await self._apply_settings(settings) await self._apply_settings(settings)
@@ -592,6 +598,24 @@ class ScheduleService:
tion.set_air_mode(settings.mode) tion.set_air_mode(settings.mode)
) )
if settings.target_temp is not None:
await self._tion.execute(
lambda tion:
tion.set_target_temperature(
settings.target_temp
)
)
if settings.heater is not None:
if settings.heater:
await self._tion.execute(
lambda tion: tion.heater_on()
)
else:
await self._tion.execute(
lambda tion: tion.heater_off()
)
if settings.speed is not None: if settings.speed is not None:
await self._tion.execute( await self._tion.execute(
lambda tion: lambda tion:
-134
View File
@@ -1,134 +0,0 @@
from pathlib import Path
from tempfile import TemporaryDirectory
from app.auto.config import (
load_auto_config_components,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
from app.auto.elica_assist import (
ElicaAutoAssistState,
)
BROKEN_CO2_CONFIG = """
version: 1
check_interval: 5.0
co2:
base_speed: 2
hysteresis: 100
thresholds:
- ppm: 700
speed: 2
- ppm: 1000
speed: 3
temperature:
hysteresis: 0.5
elica_assist:
enabled: false
speed_map:
4: 1
5: 2
6: 3
"""
def main():
with TemporaryDirectory() as directory:
path = (
Path(directory)
/ "auto.yaml"
)
path.write_text(
BROKEN_CO2_CONFIG,
encoding="utf-8",
)
config = (
load_auto_config_components(
path
)
)
# ----------------------------------------------
# CO2 должен быть отключён.
# ----------------------------------------------
assert config.co2 is None
assert "co2" in config.errors
assert (
"First threshold speed must be "
"greater than base_speed"
in config.errors["co2"]
)
# ----------------------------------------------
# Temperature должна остаться рабочей.
# ----------------------------------------------
assert config.temperature is not None
assert (
config.temperature.hysteresis
== 0.5
)
temperature_policy = (
TemperaturePolicy(
config.temperature
)
)
assert (
temperature_policy.heater_required(
temperature=20,
target_temp=24,
heater_on=False,
)
is True
)
# ----------------------------------------------
# Elica Assist тоже не должна пострадать.
# ----------------------------------------------
assert (
config.elica_assist
is not None
)
elica_assist = (
ElicaAutoAssistState(
config.elica_assist
)
)
assert elica_assist is not None
# Ошибка должна быть только в CO2.
assert set(config.errors) == {
"co2",
}
print(
"AUTO CONFIG ISOLATION TEST PASSED"
)
if __name__ == "__main__":
main()
+304
View File
@@ -0,0 +1,304 @@
import asyncio
from types import SimpleNamespace
from app.auto.config import (
TemperatureConfig,
)
from app.auto.controller import (
AutoController,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
class FakeQingpingService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
temperature=19.4,
)
class FakeTionController:
def __init__(self):
self.calls = []
async def heater_on(self):
self.calls.append(
("heater_on", None)
)
async def heater_off(self):
self.calls.append(
("heater_off", None)
)
class FakeTionService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=18,
)
self.controller = (
FakeTionController()
)
async def execute(
self,
operation,
):
return await operation(
self.controller
)
def make_resolution(
target_temp=20.0,
):
return SimpleNamespace(
scheduled_settings=(
SimpleNamespace(
target_temp=target_temp,
)
)
)
def make_controller():
qingping = (
FakeQingpingService()
)
tion = FakeTionService()
policy = TemperaturePolicy(
TemperatureConfig(
hysteresis=0.5,
)
)
controller = AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
temperature_policy=policy,
)
return (
controller,
qingping,
tion,
)
async def test_qingping_heating():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
# 19.4 < 19.5
# Heater должен включиться.
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_on", None)
]
assert (
controller._auto_heater
is True
)
assert (
controller._temperature
== 19.4
)
assert (
controller._temperature_source
== "qingping"
)
tion.controller.calls.clear()
# ----------------------------------------------
# 19.8
#
# Heater уже ON.
# До 20 градусов ещё не дошли.
# Продолжаем греть.
#
# Новую команду отправлять не нужно.
# ----------------------------------------------
qingping.state.temperature = 19.8
await controller._process_heater(
resolution
)
assert tion.controller.calls == []
assert (
controller._auto_heater
is True
)
# ----------------------------------------------
# 20.0
#
# Цель достигнута.
# ----------------------------------------------
qingping.state.temperature = 20.0
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
async def test_tion_temperature_fallback():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
# Qingping отключился.
qingping.online = False
# Используем Tion.
tion.state.in_temp = 19
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_on", None)
]
assert (
controller._temperature
== 19
)
assert (
controller._temperature_source
== "tion"
)
assert (
controller._auto_heater
is True
)
async def test_no_temperature():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution()
qingping.online = False
tion.online = False
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._temperature
is None
)
assert (
controller._temperature_source
is None
)
assert (
controller._auto_heater
is False
)
async def test_target_temperature_missing():
controller, qingping, tion = (
make_controller()
)
resolution = make_resolution(
target_temp=None
)
await controller._process_heater(
resolution
)
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
async def main():
await test_qingping_heating()
await test_tion_temperature_fallback()
await test_no_temperature()
await test_target_temperature_missing()
print()
print("=" * 70)
print(
"ALL AUTO HEATER PROCESS "
"TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,138 @@
import asyncio
from types import SimpleNamespace
from app.auto.config import (
TemperatureConfig,
)
from app.auto.controller import (
AutoController,
)
from app.auto.temperature_policy import (
TemperaturePolicy,
)
class FakeQingpingService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
temperature=19.5,
)
class FakeTionController:
def __init__(self):
self.calls = []
async def heater_on(self):
self.calls.append(
("heater_on", None)
)
async def heater_off(self):
self.calls.append(
("heater_off", None)
)
class FakeTionService:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=19,
)
self.controller = (
FakeTionController()
)
async def execute(
self,
operation,
):
return await operation(
self.controller
)
async def test_auto_uses_auto_target_temperature():
qingping = FakeQingpingService()
tion = FakeTionService()
policy = TemperaturePolicy(
TemperatureConfig(
hysteresis=0.5,
)
)
controller = AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
temperature_policy=policy,
)
resolution = SimpleNamespace(
# Последний SET хотел 23°C.
scheduled_settings=SimpleNamespace(
target_temp=23,
),
# Но текущий AUTO явно хочет 20°C.
auto_target_temp=20,
)
await controller._process_heater(
resolution
)
# При 19.5°C и target=20°C:
#
# heater был OFF,
# нижняя граница = 19.5°C.
#
# Поэтому heater должен остаться OFF.
#
# Если бы контроллер ошибочно использовал
# SET target_temp=23, он бы включил heater.
assert tion.controller.calls == [
("heater_off", None)
]
assert (
controller._auto_heater
is False
)
assert (
controller._temperature
== 19.5
)
assert (
controller._temperature_source
== "qingping"
)
async def main():
await test_auto_uses_auto_target_temperature()
print()
print("=" * 70)
print(
"ALL AUTO HEATER TARGET "
"TEMPERATURE TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
asyncio.run(main())
+169
View File
@@ -0,0 +1,169 @@
from types import SimpleNamespace
from app.auto.controller import AutoController
class FakeQingpingService:
def __init__(
self,
online: bool,
temperature,
):
self.online = online
self.state = SimpleNamespace(
temperature=temperature,
)
class FakeTionService:
def __init__(
self,
online: bool,
in_temp,
):
self.online = online
self.state = SimpleNamespace(
in_temp=in_temp,
)
def make_controller(
*,
qingping_online: bool,
qingping_temperature,
tion_online: bool,
tion_temperature,
):
qingping = FakeQingpingService(
online=qingping_online,
temperature=qingping_temperature,
)
tion = FakeTionService(
online=tion_online,
in_temp=tion_temperature,
)
return AutoController(
schedule_service=None,
qingping_service=qingping,
tion_service=tion,
)
def test_qingping_priority():
controller = make_controller(
qingping_online=True,
qingping_temperature=19.7,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 19.7
assert source == "qingping"
def test_tion_fallback():
controller = make_controller(
qingping_online=False,
qingping_temperature=19.7,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 18
assert source == "tion"
def test_tion_fallback_when_qingping_temperature_missing():
controller = make_controller(
qingping_online=True,
qingping_temperature=None,
tion_online=True,
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature == 18
assert source == "tion"
def test_offline_tion_is_not_used():
controller = make_controller(
qingping_online=False,
qingping_temperature=None,
tion_online=False,
# Значение специально оставляем.
# Оно имитирует старый state Tion.
tion_temperature=18,
)
temperature, source = (
controller._get_temperature()
)
assert temperature is None
assert source is None
def test_missing_tion_temperature():
controller = make_controller(
qingping_online=False,
qingping_temperature=None,
tion_online=True,
tion_temperature=None,
)
temperature, source = (
controller._get_temperature()
)
assert temperature is None
assert source is None
def main():
test_qingping_priority()
test_tion_fallback()
test_tion_fallback_when_qingping_temperature_missing()
test_offline_tion_is_not_used()
test_missing_tion_temperature()
print()
print("=" * 70)
print(
"ALL AUTO TEMPERATURE SOURCE "
"TESTS PASSED"
)
print("=" * 70)
if __name__ == "__main__":
main()
+11 -18
View File
@@ -134,7 +134,7 @@ def load_test_schedule():
return temp_dir, config return temp_dir, config
def temperature_calls(calls): def heater_calls(calls):
return [ return [
call call
for call in calls for call in calls
@@ -142,7 +142,6 @@ def temperature_calls(calls):
"heater_on", "heater_on",
"heater_off", "heater_off",
"set_heater", "set_heater",
"set_target_temperature",
} }
] ]
@@ -179,12 +178,7 @@ async def test_auto_does_not_control_heater():
# 09:30 # 09:30
# #
# Обычный SET. # Обычный SET.
# # heater=on должен принадлежать ScheduleService.
# ScheduleService хранит желаемое heater=on,
# но физически heater управлять НЕ должен.
#
# Физический heater будет принадлежать
# единому температурному регулятору.
# -------------------------------------------------- # --------------------------------------------------
await process_at( await process_at(
@@ -204,13 +198,12 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = temperature_calls( calls = heater_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls != [], (
"ScheduleService must not control " "SET must control heater"
"heater or target temperature during SET"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -270,13 +263,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = temperature_calls( calls = heater_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls == [], (
"ScheduleService must not control " "ScheduleService must not control "
"heater or target temperature during AUTO" "heater during AUTO"
) )
tion.controller.calls.clear() tion.controller.calls.clear()
@@ -305,13 +298,13 @@ async def test_auto_does_not_control_heater():
tion.controller.calls, tion.controller.calls,
) )
calls = temperature_calls( calls = heater_calls(
tion.controller.calls tion.controller.calls
) )
assert calls == [], ( assert calls != [], (
"ScheduleService must not control " "ScheduleService must regain heater "
"heater or target temperature after AUTO" "control after AUTO"
) )
finally: finally:
-384
View File
@@ -1,384 +0,0 @@
import asyncio
from types import SimpleNamespace
import app.api as api
class FakeTionState:
def __init__(self):
# Физическое состояние Tion.
#
# Специально ставим техническую уставку 30,
# чтобы проверить, что API её не покажет.
self.heater = False
self.heating = False
self.target_temp = 30
self.in_temp = 14
self.fan_speed = 2
def to_dict(self):
return {
"heater": self.heater,
"heating": self.heating,
"target_temp": self.target_temp,
"in_temp": self.in_temp,
"fan_speed": self.fan_speed,
}
class FakeTionService:
def __init__(self):
self.state = FakeTionState()
self.online = True
self.running = True
self.last_seen = None
self.last_error = None
self.execute_calls = []
async def execute(self, operation):
# При активном расписании температурные команды
# НЕ должны идти напрямую сюда.
self.execute_calls.append(operation)
class FakeSchedule:
def __init__(self):
self.running = True
self.paused = False
self.config = SimpleNamespace(
enabled=True,
)
self.override_active = False
self.override_settings = SimpleNamespace(
heater=None,
target_temp=None,
speed=None,
)
self.apply_override_calls = []
def resolve(self):
return SimpleNamespace(
enabled=True,
scheduled_settings=SimpleNamespace(
heater=True,
target_temp=24,
),
auto_active=False,
auto_target_temp=None,
)
async def apply_override(self, settings):
self.apply_override_calls.append(
settings
)
if settings.heater is not None:
self.override_settings.heater = (
settings.heater
)
if settings.target_temp is not None:
self.override_settings.target_temp = (
settings.target_temp
)
self.override_active = True
async def clear_override(self):
self.override_active = False
self.override_settings = SimpleNamespace(
heater=None,
target_temp=None,
speed=None,
)
async def pause(self):
self.paused = True
async def resume(self):
self.paused = False
class FakeAutoController:
def __init__(self, schedule):
self.schedule = schedule
self.manual_heater_enabled = None
self.manual_target_temperature = None
self.reconcile_calls = 0
def effective_temperature_config(self):
if self.schedule.paused:
return SimpleNamespace(
heater_enabled=(
self.manual_heater_enabled
),
target_temp=(
self.manual_target_temperature
),
)
heater = True
target = 24
if self.schedule.override_active:
override = (
self.schedule.override_settings
)
if override.heater is not None:
heater = override.heater
if override.target_temp is not None:
target = override.target_temp
return SimpleNamespace(
heater_enabled=heater,
target_temp=target,
)
def set_manual_heater_enabled(
self,
enabled,
):
self.manual_heater_enabled = enabled
def set_manual_target_temperature(
self,
temperature,
):
self.manual_target_temperature = (
temperature
)
def clear_manual_heater_control(self):
self.manual_heater_enabled = None
self.manual_target_temperature = None
async def reconcile_temperature(self):
self.reconcile_calls += 1
def status(self):
return {
"state": "test",
}
class FakeQingping:
def status(self):
return {
"online": True,
"temperature": 25.5,
}
def prepare():
schedule = FakeSchedule()
auto = FakeAutoController(schedule)
tion = FakeTionService()
api.schedule_service = schedule
api.auto_controller = auto
api.service = tion
api.qingping_service = FakeQingping()
# Чтобы тест не зависел от Elica.
api.get_elica_status = lambda: {
"online": True,
}
# Нам здесь не нужна внутренняя структура
# schedule-status.
api.get_schedule_status = lambda: {
"available": True,
"paused": schedule.paused,
}
return schedule, auto, tion
def test_status_uses_logical_temperature():
schedule, auto, tion = prepare()
status = api.get_status()
# Физически Tion:
assert tion.state.target_temp == 30
assert tion.state.heater is False
# Но пользователь должен видеть:
assert status["tion"]["target_temp"] == 24
assert status["tion"]["heater"] is True
# heating остаётся физическим.
assert status["tion"]["heating"] is False
async def test_temperature_creates_override():
schedule, auto, tion = prepare()
await api.set_temperature(26)
assert schedule.override_active is True
assert (
schedule.override_settings.target_temp
== 26
)
# Изменение только температуры
# не должно само задавать heater.
assert (
schedule.override_settings.heater
is None
)
# Tion напрямую не вызывается.
assert tion.execute_calls == []
# Новый температурный контур
# применяется сразу.
assert auto.reconcile_calls == 1
async def test_heater_creates_override():
schedule, auto, tion = prepare()
await api.set_heater("off")
assert schedule.override_active is True
assert (
schedule.override_settings.heater
is False
)
assert tion.execute_calls == []
assert auto.reconcile_calls == 1
async def test_pause_uses_logical_state():
schedule, auto, tion = prepare()
# Физический heater выключен.
assert tion.state.heater is False
# Но логически отопление разрешено:
config = (
auto.effective_temperature_config()
)
assert config.heater_enabled is True
assert config.target_temp == 24
await api.pause_schedule()
assert schedule.paused is True
# PAUSE должен запомнить ЛОГИЧЕСКОЕ
# состояние, а не физический heater=False.
assert (
auto.manual_heater_enabled
is True
)
assert (
auto.manual_target_temperature
== 24
)
assert auto.reconcile_calls == 1
async def test_resume_clears_manual_state():
schedule, auto, tion = prepare()
schedule.paused = True
auto.manual_heater_enabled = True
auto.manual_target_temperature = 25
await api.resume_schedule()
assert schedule.paused is False
assert (
auto.manual_heater_enabled
is None
)
assert (
auto.manual_target_temperature
is None
)
assert auto.reconcile_calls == 1
def test_temperature_routes():
paths = [
route.path
for route in api.app.routes
]
# increase мы решили удалить полностью.
assert (
"/api/tion/temperature/increase"
not in paths
)
# Основной endpoint должен существовать
# ровно один раз.
assert (
paths.count(
"/api/tion/temperature/{temperature}"
)
== 1
)
async def main():
test_status_uses_logical_temperature()
await test_temperature_creates_override()
await test_heater_creates_override()
await test_pause_uses_logical_state()
await test_resume_clears_manual_state()
test_temperature_routes()
print(
"ALL TEMPERATURE API TESTS PASSED"
)
if __name__ == "__main__":
asyncio.run(main())
-395
View File
@@ -1,395 +0,0 @@
import asyncio
import inspect
from types import SimpleNamespace
from app.auto.controller import AutoController
from app.my_dataclasses import MAX_TARGET_TEMP
class FakeTionController:
def __init__(self):
self.heater = None
self.target_temp = None
self.speed = None
def heater_on(self):
self.heater = True
def heater_off(self):
self.heater = False
def set_target_temperature(
self,
temperature,
):
self.target_temp = temperature
def set_speed(self, speed):
self.speed = speed
class FakeTion:
def __init__(self):
self.online = True
self.state = SimpleNamespace(
in_temp=14,
)
self.controller = (
FakeTionController()
)
async def execute(self, operation):
result = operation(
self.controller
)
if inspect.isawaitable(result):
await result
class FakeQingping:
def __init__(
self,
*,
online=True,
temperature=25,
):
self.online = online
self.state = SimpleNamespace(
temperature=temperature,
co2=None,
)
class FakeTemperaturePolicy:
def heater_required(
self,
temperature,
target_temp,
heater_on,
):
return temperature < target_temp
class FakeSchedule:
def __init__(
self,
*,
heater=True,
target_temp=24,
auto=False,
auto_target=None,
paused=False,
override=None,
):
self.paused = paused
self.override_active = (
override is not None
)
self.override_settings = (
override
or SimpleNamespace(
heater=None,
target_temp=None,
)
)
self.resolution = SimpleNamespace(
enabled=True,
scheduled_settings=(
SimpleNamespace(
heater=heater,
target_temp=target_temp,
)
),
auto_active=auto,
auto_target_temp=auto_target,
auto_fallback_speed=2,
)
def resolve(self, now=None):
return self.resolution
def make_controller(
schedule,
qingping,
):
tion = FakeTion()
controller = AutoController(
schedule_service=schedule,
qingping_service=qingping,
tion_service=tion,
temperature_policy=(
FakeTemperaturePolicy()
),
)
return controller, tion
async def test_set_online():
schedule = FakeSchedule(
heater=True,
target_temp=24,
)
qingping = FakeQingping(
online=True,
temperature=25.9,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is False
async def test_set_offline():
schedule = FakeSchedule(
heater=True,
target_temp=24,
)
qingping = FakeQingping(
online=False,
temperature=None,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == 24
assert tion.controller.heater is True
async def test_auto_online():
schedule = FakeSchedule(
heater=True,
target_temp=24,
auto=True,
auto_target=22,
)
qingping = FakeQingping(
online=True,
temperature=21,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is True
async def test_auto_offline():
schedule = FakeSchedule(
heater=True,
target_temp=24,
auto=True,
auto_target=22,
)
qingping = FakeQingping(
online=False,
temperature=None,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == 22
assert tion.controller.heater is True
async def test_override_temperature_only():
schedule = FakeSchedule(
heater=False,
target_temp=24,
override=SimpleNamespace(
heater=None,
target_temp=26,
),
)
qingping = FakeQingping(
online=True,
temperature=20,
)
controller, tion = make_controller(
schedule,
qingping,
)
config = (
controller
._get_effective_temperature_config(
schedule.resolve()
)
)
assert config.heater_enabled is False
assert config.target_temp == 26
await controller._process()
# Изменение только температуры
# НЕ включает heater.
assert tion.controller.heater is False
async def test_override_heater_only():
schedule = FakeSchedule(
heater=False,
target_temp=24,
override=SimpleNamespace(
heater=True,
target_temp=None,
),
)
qingping = FakeQingping(
online=True,
temperature=23,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is True
async def test_pause():
schedule = FakeSchedule(
paused=True,
)
qingping = FakeQingping(
online=True,
temperature=25,
)
controller, tion = make_controller(
schedule,
qingping,
)
controller.set_manual_heater_enabled(
True
)
controller.set_manual_target_temperature(
24
)
await controller._process()
assert tion.controller.target_temp == (
MAX_TARGET_TEMP
)
assert tion.controller.heater is False
async def test_heater_false_priority():
schedule = FakeSchedule(
heater=False,
target_temp=30,
)
qingping = FakeQingping(
online=True,
temperature=10,
)
controller, tion = make_controller(
schedule,
qingping,
)
await controller._process()
assert tion.controller.heater is False
async def main():
await test_set_online()
await test_set_offline()
await test_auto_online()
await test_auto_offline()
await test_override_temperature_only()
await test_override_heater_only()
await test_pause()
await test_heater_false_priority()
print(
"ALL UNIFIED TEMPERATURE "
"TESTS PASSED"
)
if __name__ == "__main__":
asyncio.run(main())
-872
View File
@@ -1,872 +0,0 @@
:root {
--panel-ink: #08265d;
--panel-muted: #315d91;
--tile: rgba(219, 241, 253, 0.22);
--tile-strong: rgba(244, 251, 255, 0.4);
--tile-line: rgba(255, 255, 255, 0.9);
--tile-line-soft: rgba(193, 226, 244, 0.5);
--tile-shadow: 0 14px 32px rgba(23, 75, 111, 0.16), inset 0 1px 0 rgba(255,255,255,0.92), inset 1px 0 0 rgba(255,255,255,0.36);
--panel-glass: rgba(211, 235, 248, 0.35);
--panel-edge: rgba(255, 255, 255, 0.92);
--blue-halo: rgba(25, 139, 255, 0.34);
--green-halo: rgba(30, 205, 120, 0.34);
--orange-halo: rgba(255, 126, 46, 0.3);
}
:root[data-theme="dark"] {
--panel-ink: #edf8ff;
--panel-muted: #9fc5df;
--tile: rgba(28, 48, 65, 0.46);
--tile-strong: rgba(45, 71, 89, 0.54);
--tile-line: rgba(194, 229, 247, 0.3);
--tile-line-soft: rgba(114, 176, 207, 0.22);
--tile-shadow: 0 16px 38px rgba(0, 0, 0, 0.34), inset 0 1px 0 rgba(235,249,255,0.14), inset 1px 0 0 rgba(190,228,247,0.08);
--panel-glass: rgba(13, 29, 41, 0.58);
--panel-edge: rgba(187, 225, 244, 0.32);
--blue-halo: rgba(30, 161, 255, 0.42);
--green-halo: rgba(25, 225, 129, 0.35);
--orange-halo: rgba(255, 126, 39, 0.34);
}
html { min-width: 320px; }
body {
min-height: 100vh;
padding: clamp(0.7rem, 2vw, 2rem);
color: var(--panel-ink);
background:
radial-gradient(ellipse at 8% 10%, rgba(244,253,255,.95) 0 7%, transparent 24%),
radial-gradient(ellipse at 73% -8%, rgba(255,249,239,.85) 0 10%, transparent 29%),
radial-gradient(ellipse at 93% 32%, rgba(90,152,125,.52) 0 10%, transparent 28%),
radial-gradient(ellipse at 12% 80%, rgba(65,132,170,.46) 0 12%, transparent 31%),
linear-gradient(115deg, rgba(184,222,239,.94), rgba(213,236,247,.82) 37%, rgba(239,232,217,.82) 66%, rgba(129,181,183,.88));
background-attachment: fixed;
overflow-x: hidden;
isolation: isolate;
}
:root[data-theme="dark"] body {
background:
radial-gradient(ellipse at 6% 2%, rgba(54,112,145,.44) 0 8%, transparent 28%),
radial-gradient(ellipse at 78% -5%, rgba(138,103,60,.31) 0 9%, transparent 28%),
radial-gradient(ellipse at 94% 36%, rgba(28,91,78,.44) 0 12%, transparent 31%),
radial-gradient(ellipse at 15% 87%, rgba(17,84,122,.42) 0 13%, transparent 33%),
linear-gradient(118deg, #081723, #122d3d 40%, #292c30 68%, #0c262c);
}
body::before {
content: "";
position: fixed;
inset: -7rem;
z-index: -3;
background:
linear-gradient(90deg, transparent 0 13%, rgba(255,255,255,.55) 13% 16%, transparent 16% 34%, rgba(255,255,255,.35) 34% 37%, transparent 37% 68%, rgba(255,255,255,.42) 68% 71%, transparent 71%),
linear-gradient(0deg, transparent 0 58%, rgba(228,244,251,.48) 58% 61%, transparent 61%),
radial-gradient(ellipse at 50% 114%, rgba(36,111,68,.48) 0 17%, transparent 47%);
filter: blur(26px);
transform: scale(1.05);
}
body::after {
content: "";
position: fixed;
inset: 0;
z-index: -2;
pointer-events: none;
background:
radial-gradient(circle at 4% 22%, rgba(255,255,255,.88) 0 .8%, transparent 5%),
radial-gradient(circle at 19% 74%, rgba(246,253,255,.68) 0 1.2%, transparent 7%),
radial-gradient(circle at 62% 34%, rgba(255,241,210,.63) 0 1.3%, transparent 8%),
radial-gradient(circle at 89% 13%, rgba(244,253,255,.66) 0 1%, transparent 6%),
radial-gradient(circle at 82% 82%, rgba(209,238,228,.48) 0 1.5%, transparent 8%);
filter: blur(8px);
opacity: .86;
}
.ambient::before { width: 42rem; height: 42rem; left: -14rem; top: -18rem; background: #c9f2ff; opacity: .58; filter: blur(54px); }
.ambient::after { width: 46rem; height: 46rem; right: -14rem; bottom: -21rem; background: #ebd5a7; opacity: .38; filter: blur(64px); }
:root[data-theme="dark"] .ambient::before { background: #147db5; opacity: .24; }
:root[data-theme="dark"] .ambient::after { background: #846630; opacity: .2; }
.climate-panel {
position: relative;
isolation: isolate;
overflow: hidden;
width: min(100%, 104rem);
min-height: calc(100vh - clamp(1.4rem, 4vw, 4rem));
margin: 0 auto;
padding: clamp(0.65rem, 1.25vw, 1.25rem);
border: 1px solid var(--panel-edge);
outline: 1px solid rgba(255,255,255,.5);
outline-offset: -5px;
border-radius: 1.5rem;
background:
linear-gradient(125deg, rgba(255,255,255,.34), transparent 29%, rgba(255,255,255,.11) 67%, rgba(214,235,247,.2)),
var(--panel-glass);
box-shadow: 0 32px 90px rgba(20,60,89,.3), 0 2px 10px rgba(255,255,255,.35), inset 0 1px 0 rgba(255,255,255,.95), inset 0 -1px 0 rgba(114,162,192,.23);
backdrop-filter: blur(34px) saturate(148%);
-webkit-backdrop-filter: blur(34px) saturate(148%);
}
:root[data-theme="dark"] .climate-panel { outline-color: rgba(203,235,250,.12); box-shadow: 0 38px 100px rgba(0,0,0,.48), 0 0 42px rgba(21,120,171,.1), inset 0 1px 0 rgba(224,246,255,.2), inset 0 -1px 0 rgba(0,0,0,.35); }
.climate-panel::before {
content: "";
position: absolute;
inset: 0;
z-index: 0;
pointer-events: none;
border-radius: inherit;
background:
linear-gradient(112deg, rgba(255,255,255,.44) 0, rgba(255,255,255,.08) 17%, transparent 38%),
radial-gradient(ellipse at 52% -16%, rgba(255,255,255,.54), transparent 48%),
radial-gradient(ellipse at 100% 100%, rgba(102,178,219,.13), transparent 42%);
}
.climate-panel::after {
content: "";
position: absolute;
inset: 0;
z-index: 0;
pointer-events: none;
opacity: .2;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.16'/%3E%3C/svg%3E");
mix-blend-mode: soft-light;
}
.climate-panel > * { position: relative; z-index: 1; }
.glass-tile, .glass-section {
position: relative;
isolation: isolate;
overflow: hidden;
border: 1px solid var(--tile-line);
outline: 1px solid var(--tile-line-soft);
outline-offset: -3px;
background:
linear-gradient(132deg, rgba(255,255,255,.38), rgba(255,255,255,.06) 35%, transparent 63%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
backdrop-filter: blur(23px) saturate(145%);
-webkit-backdrop-filter: blur(23px) saturate(145%);
}
.glass-tile::before, .glass-section::before {
content: "";
position: absolute;
inset: 0;
z-index: 0;
pointer-events: none;
border-radius: inherit;
background: linear-gradient(115deg, rgba(255,255,255,.35), transparent 25%, transparent 72%, rgba(255,255,255,.08));
}
.glass-tile > *, .glass-section > * { position: relative; z-index: 1; }
.speed-card::after, .temperature-card::after, .power-card::after, .heater-card::after {
content: "";
position: absolute;
z-index: 0;
width: 13rem;
height: 13rem;
right: -5rem;
bottom: -7rem;
border-radius: 50%;
pointer-events: none;
filter: blur(17px);
}
.speed-card::after { background: var(--blue-halo); }
.temperature-card::after { width: 18rem; background: linear-gradient(90deg, var(--blue-halo), var(--orange-halo)); }
.power-card::after { background: var(--green-halo); opacity: .64; }
.heater-card::after { background: var(--orange-halo); opacity: .58; }
.panel-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 0 0.65rem 0.7rem; }
.identity, .header-tools { display: flex; align-items: center; gap: 0.65rem; }
.identity h1 { margin: 0 0.35rem 0 0; font-size: clamp(1.8rem, 3.1vw, 3rem); line-height: 1; letter-spacing: -0.045em; }
.climate-panel .pill { min-height: 2.05rem; padding: .38rem .82rem; border-color: rgba(255,255,255,.62); box-shadow: inset 0 1px 0 rgba(255,255,255,.72), 0 6px 18px rgba(26,75,108,.1); backdrop-filter: blur(14px); }
.climate-panel .pill.good { box-shadow: 0 0 21px rgba(28,204,117,.18), inset 0 1px 0 rgba(255,255,255,.74); }
.climate-panel .pill.warn { box-shadow: 0 0 21px rgba(242,145,56,.17), inset 0 1px 0 rgba(255,255,255,.74); }
.climate-panel .pill.info { box-shadow: 0 0 21px rgba(31,145,236,.16), inset 0 1px 0 rgba(255,255,255,.74); }
.climate-panel .icon-button { border-color: var(--tile-line); background: linear-gradient(145deg, var(--tile-strong), var(--tile)); box-shadow: var(--tile-shadow); backdrop-filter: blur(16px); }
.header-tools { justify-content: flex-end; }
.ventilation-badge { display: flex; align-items: center; gap: 0.7rem; min-width: 22rem; padding: 0.55rem 1rem; border-radius: 1rem; }
.ventilation-badge svg { width: 2.5rem; color: #1977d2; filter: drop-shadow(0 0 9px rgba(26,128,226,.34)); }
.ventilation-badge strong, .ventilation-badge small { display: block; }
.ventilation-badge strong { font-size: 0.9rem; }
.ventilation-badge small { margin-top: 0.1rem; color: var(--panel-muted); font-size: 0.68rem; }
.primary-controls { display: grid; grid-template-columns: 2.05fr 2.05fr .95fr .95fr; gap: 0.75rem; }
.control-card, .switch-card { min-height: 17.6rem; border-radius: 1.15rem; padding: 1rem; }
.control-card { display: flex; flex-direction: column; }
.card-title { display: flex; align-items: flex-start; gap: 0.72rem; }
.card-title.compact { align-items: center; }
.card-title h2 { margin: 0; font-size: clamp(1rem, 1.55vw, 1.28rem); letter-spacing: -0.02em; }
.card-title p { margin: 0.18rem 0 0; color: var(--panel-muted); font-size: 0.72rem; }
.feature-icon { display: grid; place-items: center; flex: 0 0 auto; width: 2.1rem; height: 2.1rem; color: #1389f4; font-size: 1.75rem; font-weight: 800; line-height: 1; text-shadow: 0 0 16px rgba(20,139,244,.46); }
.feature-icon.green { color: #08a95a; text-shadow: 0 0 20px rgba(20,210,112,.62); }
.feature-icon.orange { color: #f06419; text-shadow: 0 0 18px rgba(255,105,29,.46); }
.fan-icon { font-size: 2.2rem; }
.hero-control { display: grid; grid-template-columns: 4.3rem 1fr 4.3rem; align-items: center; gap: 1rem; margin: auto 0 0.75rem; }
.hero-value { text-align: center; font-size: clamp(3.2rem, 5vw, 4.35rem); line-height: 1; letter-spacing: -0.06em; font-variant-numeric: tabular-nums; }
.hero-step {
display: grid;
place-items: center;
width: 4.3rem;
height: 4.3rem;
border: 1.5px solid rgba(255,255,255,.85);
border-radius: 1rem;
color: #176dbb;
background: linear-gradient(145deg, rgba(245,252,255,.42), rgba(191,224,244,.2));
box-shadow: 0 10px 24px rgba(35,92,132,.15), inset 0 1px 0 rgba(255,255,255,.9), 0 0 0 1px rgba(185,226,248,.24);
cursor: pointer;
font-size: 2.3rem;
font-weight: 500;
transition: transform .15s ease, filter .15s ease;
}
.hero-step.primary { color: white; background: linear-gradient(145deg, #57b5ff, #1376e4 76%); box-shadow: 0 12px 28px rgba(16,103,220,.35), 0 0 26px var(--blue-halo), inset 0 1px 0 rgba(255,255,255,.8), inset 0 -2px 5px rgba(0,67,156,.24); }
.hero-step:hover { transform: translateY(-2px); filter: brightness(1.08); box-shadow: 0 14px 32px rgba(25,112,219,.35), 0 0 32px var(--blue-halo), inset 0 1px 0 rgba(255,255,255,.78); }
.hero-step:active { transform: scale(.98); }
.speed-range { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); clip-path: inset(50%); white-space: nowrap; }
.speed-segments { display: grid; grid-template-columns: repeat(6, 1fr); gap: 0.16rem; }
.speed-segments button { height: 1.12rem; padding: 0; border: 1px solid rgba(255,255,255,.88); border-radius: .55rem; background: linear-gradient(180deg, rgba(173,207,229,.32), rgba(98,151,190,.2)); box-shadow: inset 0 1px 2px rgba(27,70,105,.08), 0 2px 5px rgba(32,86,126,.08); cursor: pointer; transition: background .12s ease, box-shadow .12s ease, transform .12s ease; }
.speed-segments button:hover { transform: translateY(-1px); }
.speed-segments button.active { background: linear-gradient(90deg, #0e82ed, #37b8ff); box-shadow: 0 0 17px rgba(25,143,247,.56), inset 0 1px 0 rgba(255,255,255,.74), inset 0 -2px 4px rgba(0,84,182,.22); }
.speed-labels, .temperature-labels { display: flex; justify-content: space-between; margin-top: 0.45rem; padding: 0 .55rem; color: var(--panel-muted); font-size: 0.68rem; }
.temperature-range { height: 1.45rem; }
.temperature-range::-webkit-slider-runnable-track { height: .78rem; background: linear-gradient(90deg, #0878ed, #53c7f5 38%, #f3c26e 72%, #ff6b31); border: 1px solid rgba(255,255,255,.92); box-shadow: 0 0 16px rgba(37,153,239,.24), 0 0 14px rgba(255,114,41,.14), inset 0 1px 2px rgba(255,255,255,.5); }
.temperature-range::-webkit-slider-thumb { width: 1.9rem; height: 1.9rem; margin-top: -.58rem; border-width: .28rem; box-shadow: 0 0 0 2px rgba(255,255,255,.55), 0 0 22px rgba(29,139,241,.58), 0 5px 13px rgba(17,79,143,.3); }
.temperature-range::-moz-range-track { height: .78rem; background: linear-gradient(90deg, #0878ed, #53c7f5 38%, #f3c26e 72%, #ff6b31); }
.temperature-range::-moz-range-progress { background: transparent; }
.switch-card { display: flex; flex-direction: column; justify-content: space-between; }
.glass-switch {
width: 100%; min-height: 6rem; border: 1.5px solid rgba(255,255,255,.9); border-radius: 1rem; color: var(--panel-ink); background: rgba(199,222,235,.28); box-shadow: var(--tile-shadow); cursor: pointer; font-size: 1.75rem; font-weight: 850;
text-shadow: 0 1px 0 rgba(255,255,255,.35);
transition: transform .15s ease, background .2s ease, box-shadow .2s ease, filter .2s ease;
}
.glass-switch:hover { transform: translateY(-2px); filter: brightness(1.06); }
.glass-switch[aria-pressed="true"].green { background: linear-gradient(145deg, rgba(145,255,198,.9), rgba(38,194,113,.62)); border-color: rgba(213,255,232,.96); box-shadow: 0 14px 32px rgba(11,153,81,.3), 0 0 32px var(--green-halo), inset 0 1px 0 rgba(255,255,255,.9), inset 0 -4px 10px rgba(0,125,62,.18); }
.glass-switch[aria-pressed="true"].orange { background: linear-gradient(145deg, rgba(255,202,130,.88), rgba(245,112,40,.58)); border-color: rgba(255,236,213,.95); box-shadow: 0 14px 32px rgba(210,91,25,.3), 0 0 30px var(--orange-halo), inset 0 1px 0 rgba(255,255,255,.88), inset 0 -4px 10px rgba(168,54,0,.17); }
.content-section { margin-top: 0.75rem; padding: 0.7rem; border-radius: 1.15rem; }
.section-title { display: flex; align-items: center; gap: 0.65rem; min-height: 2.35rem; padding: 0 0.35rem 0.5rem; }
.section-title > div { display: flex; align-items: center; gap: 0.55rem; }
.section-title h2 { margin: 0; font-size: clamp(1rem, 1.55vw, 1.28rem); }
.section-icon { display: grid; place-items: center; width: 1.8rem; height: 1.8rem; color: #207bcc; font-size: 1.55rem; text-shadow: 0 0 14px rgba(26,124,210,.38); }
.section-icon.leaf { color: #069c51; transform: rotate(-18deg); text-shadow: 0 0 15px rgba(8,173,88,.42); }
.section-title .updated { margin-left: auto; color: var(--panel-muted); font-size: 0.7rem; }
.air-grid { display: grid; grid-template-columns: 1.55fr 1fr .9fr 1fr 1fr 1.28fr; gap: 0.55rem; }
.metric-card { min-width: 0; min-height: 9.4rem; padding: 0.85rem; border-radius: 1rem; }
.metric-head, .metric-heading { display: flex; align-items: center; gap: 0.55rem; color: var(--panel-muted); font-size: 0.76rem; }
.metric-head { justify-content: space-between; }
.metric-icon { color: #137edc; font-size: 1.7rem; line-height: 1; text-shadow: 0 0 14px rgba(20,124,221,.34); }
.metric-icon.dots { letter-spacing: -.2rem; }
.metric-card > strong { display: block; margin-top: 0.75rem; font-size: clamp(1.55rem, 2.4vw, 2.2rem); line-height: 1; font-variant-numeric: tabular-nums; white-space: nowrap; }
.metric-card strong small { color: var(--panel-muted); font-size: .63rem; font-weight: 600; }
.quality-chip { display: inline-flex; justify-content: center; padding: .35rem .72rem; border: 1px solid rgba(109,237,167,.82); border-radius: 999px; color: #076d3d; background: linear-gradient(145deg, rgba(179,255,214,.7), rgba(92,218,151,.48)); box-shadow: 0 0 17px rgba(33,203,116,.24), inset 0 1px 0 rgba(255,255,255,.88); font-size: .66rem; font-weight: 750; }
:root[data-theme="dark"] .quality-chip { color: #b9ffda; }
.quality-chip.small { margin-top: .8rem; min-width: 5.5rem; }
.co2-card > p { height: 1rem; margin: .2rem 0 .55rem; color: var(--panel-muted); font-size: .58rem; overflow: hidden; }
.meter { height: .82rem; border: 1px solid rgba(255,255,255,.8); border-radius: 999px; background: rgba(91,145,181,.18); overflow: hidden; }
.meter i { display: block; height: 100%; width: 0; border-radius: inherit; background: linear-gradient(90deg, #08a350, #36dc83); box-shadow: 0 0 18px rgba(18,199,104,.58), inset 0 1px 0 rgba(255,255,255,.64); transition: width .35s ease; }
.meter-labels { display: flex; justify-content: space-between; margin-top: .27rem; color: rgba(22,69,108,.78); font-size: .6rem; font-weight: 650; text-shadow: 0 1px 0 rgba(255,255,255,.48); }
:root[data-theme="dark"] .meter-labels { color: rgba(211,235,248,.76); text-shadow: 0 1px 2px rgba(0,0,0,.58); }
.filter-line { display: flex; align-items: center; gap: .45rem; margin-top: 1rem; }
.filter-meter { flex: 1; }
.filter-meter i { background: linear-gradient(90deg, #176dec, #36c1ff); box-shadow: 0 0 18px rgba(31,144,247,.55), inset 0 1px 0 rgba(255,255,255,.58); }
.filter-line > span { font-size: .65rem; font-weight: 750; }
.bottom-grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 0.75rem; }
.schedule-layout { display: grid; grid-template-columns: 1.35fr 1fr; gap: 0.7rem; }
.schedule-times { display: grid; grid-template-columns: 1fr 1px 1fr; gap: 1rem; align-items: center; min-height: 8.2rem; padding: 1rem 1.3rem; border-radius: 1rem; }
.schedule-times > i { width: 1px; height: 80%; background: rgba(49,93,145,.25); }
.schedule-times div { display: grid; gap: .22rem; }
.schedule-times span, .schedule-times small { color: var(--panel-muted); font-size: .68rem; }
.schedule-times strong { font-size: clamp(1.65rem, 2.8vw, 2.3rem); font-variant-numeric: tabular-nums; }
.schedule-buttons { display: grid; gap: .55rem; }
.schedule-button { display: grid; grid-template-columns: 2.4rem 1fr; align-items: center; gap: .65rem; min-height: 3.8rem; padding: .55rem .8rem; border: 1.5px solid; border-radius: .9rem; text-align: left; cursor: pointer; }
.schedule-button strong, .schedule-button small { display: block; }
.schedule-button strong { font-size: .84rem; }
.schedule-button small { margin-top: .12rem; font-size: .62rem; }
.schedule-button.auto { color: #096bda; border-color: rgba(83,176,255,.9); background: linear-gradient(145deg, rgba(224,244,255,.67), rgba(133,201,250,.26)); box-shadow: 0 9px 24px rgba(23,113,212,.19), 0 0 20px rgba(42,153,243,.13), inset 0 1px 0 rgba(255,255,255,.92); }
.schedule-button.pause { color: #a73512; border-color: rgba(250,174,102,.9); background: linear-gradient(145deg, rgba(255,240,217,.72), rgba(246,177,107,.28)); box-shadow: 0 9px 24px rgba(202,104,44,.17), 0 0 20px rgba(244,131,50,.12), inset 0 1px 0 rgba(255,255,255,.92); }
.schedule-button:hover { filter: brightness(1.06); transform: translateY(-1px); }
.action-symbol { font-size: 2rem; font-weight: 800; text-align: center; }
.mode-banner { display: flex; gap: .4rem; align-items: center; margin-top: .5rem; padding: .45rem .7rem; border-radius: .65rem; color: var(--panel-muted); background: rgba(255,255,255,.14); font-size: .62rem; }
.mode-banner small::before { content: "· "; }
.extras-grid { display: grid; grid-template-columns: .9fr 1.3fr; gap: .55rem; }
.extra-card { display: flex; align-items: center; gap: .8rem; min-height: 8.2rem; padding: 1rem; border-radius: 1rem; }
.extra-icon { color: #267fd3; font-size: 3.4rem; line-height: 1; text-shadow: 0 0 19px rgba(33,126,211,.32); }
.extra-icon.wind { font-size: 3.8rem; transform: rotate(90deg); }
.extra-card small, .extra-card strong, .extra-card em { display: block; }
.extra-card small { color: var(--panel-muted); font-size: .7rem; }
.extra-card strong { margin-top: .18rem; font-size: clamp(1.3rem, 2.2vw, 2rem); font-style: normal; }
.extra-card em { margin-top: .18rem; color: var(--panel-muted); font-size: .62rem; font-style: normal; }
.mode-card { display: grid; grid-template-columns: auto 1fr; }
.mode-card strong { font-size: .85rem; }
.segments { grid-column: 1 / -1; display: flex; gap: .3rem; }
.segment { flex: 1; padding: .42rem; border: 1px solid rgba(255,255,255,.55); border-radius: .55rem; color: var(--panel-muted); background: rgba(255,255,255,.14); cursor: pointer; font-size: .58rem; }
.segment.active { color: white; background: linear-gradient(145deg, #45a7f4, #1976d2); }
.micro-settings { display: flex; align-items: center; gap: .65rem; margin-top: .55rem; padding: 0 .25rem; color: var(--panel-muted); font-size: .58rem; }
.micro-settings > span:nth-child(2) { margin-right: auto; }
.micro-toggle { padding: .32rem .55rem; border: 1px solid var(--tile-line); border-radius: 999px; color: var(--panel-muted); background: var(--tile); cursor: pointer; font-size: .56rem; }
.micro-toggle[aria-pressed="true"] { color: #087848; background: rgba(105,222,160,.38); }
.demo-note { display: block; margin-top: .55rem; color: var(--panel-muted); text-align: center; font-size: .62rem; }
/* Dark aeroglass keeps the same optical depth, with colder edges and
brighter local halos so active controls do not disappear into the glass. */
:root[data-theme="dark"] body::after { opacity: .42; mix-blend-mode: screen; }
:root[data-theme="dark"] .climate-panel::before {
background:
linear-gradient(112deg, rgba(205,239,255,.14), rgba(255,255,255,.025) 21%, transparent 42%),
radial-gradient(ellipse at 52% -16%, rgba(112,202,244,.13), transparent 50%),
radial-gradient(ellipse at 100% 100%, rgba(23,139,186,.12), transparent 44%);
}
:root[data-theme="dark"] .glass-tile,
:root[data-theme="dark"] .glass-section {
background:
linear-gradient(132deg, rgba(211,240,253,.105), rgba(255,255,255,.018) 38%, transparent 65%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
}
:root[data-theme="dark"] .glass-tile::before,
:root[data-theme="dark"] .glass-section::before {
background: linear-gradient(115deg, rgba(218,243,255,.12), transparent 26%, transparent 74%, rgba(80,181,222,.045));
}
:root[data-theme="dark"] .hero-step {
color: #8ed3ff;
border-color: rgba(184,226,247,.28);
background: linear-gradient(145deg, rgba(89,137,166,.2), rgba(20,48,67,.23));
box-shadow: 0 12px 28px rgba(0,0,0,.28), inset 0 1px 0 rgba(224,246,255,.14), 0 0 0 1px rgba(60,157,205,.08);
}
:root[data-theme="dark"] .hero-step.primary {
color: white;
background: linear-gradient(145deg, #42b8ff, #096bd3 78%);
box-shadow: 0 13px 32px rgba(0,65,139,.5), 0 0 30px var(--blue-halo), inset 0 1px 0 rgba(220,248,255,.52), inset 0 -3px 7px rgba(0,27,91,.38);
}
:root[data-theme="dark"] .speed-segments button { border-color: rgba(192,226,244,.25); background: linear-gradient(180deg, rgba(91,136,162,.23), rgba(24,55,74,.28)); }
:root[data-theme="dark"] .speed-segments button.active { border-color: rgba(117,207,255,.55); background: linear-gradient(90deg, #0877df, #20b7ff); box-shadow: 0 0 20px rgba(24,156,255,.66), inset 0 1px 0 rgba(223,248,255,.42); }
:root[data-theme="dark"] .glass-switch { color: #ddecf4; border-color: rgba(193,228,245,.25); background: linear-gradient(145deg, rgba(77,112,133,.23), rgba(20,44,59,.28)); text-shadow: 0 1px 2px rgba(0,0,0,.4); }
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].green { color: #eafff4; border-color: rgba(118,255,185,.54); background: linear-gradient(145deg, rgba(56,221,137,.76), rgba(8,120,69,.67)); box-shadow: 0 15px 36px rgba(0,0,0,.3), 0 0 38px var(--green-halo), inset 0 1px 0 rgba(218,255,236,.48); }
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].orange { color: #fff5e9; border-color: rgba(255,185,118,.53); background: linear-gradient(145deg, rgba(244,145,61,.76), rgba(143,58,14,.68)); box-shadow: 0 15px 36px rgba(0,0,0,.3), 0 0 36px var(--orange-halo), inset 0 1px 0 rgba(255,237,216,.48); }
:root[data-theme="dark"] .quality-chip { color: #caffdf; border-color: rgba(89,232,158,.42); background: linear-gradient(145deg, rgba(45,186,113,.35), rgba(11,101,60,.3)); box-shadow: 0 0 20px rgba(20,218,118,.18), inset 0 1px 0 rgba(210,255,232,.16); }
:root[data-theme="dark"] .schedule-button.auto { color: #a8ddff; border-color: rgba(76,176,241,.48); background: linear-gradient(145deg, rgba(38,125,187,.29), rgba(15,61,91,.28)); box-shadow: 0 10px 27px rgba(0,0,0,.23), 0 0 24px rgba(27,150,237,.13), inset 0 1px 0 rgba(211,241,255,.13); }
:root[data-theme="dark"] .schedule-button.pause { color: #ffc18c; border-color: rgba(242,147,70,.48); background: linear-gradient(145deg, rgba(167,82,27,.3), rgba(73,40,25,.27)); box-shadow: 0 10px 27px rgba(0,0,0,.23), 0 0 24px rgba(244,117,35,.12), inset 0 1px 0 rgba(255,230,207,.12); }
:root[data-theme="dark"] .meter { border-color: rgba(200,232,247,.24); background: rgba(3,22,34,.34); box-shadow: inset 0 2px 5px rgba(0,0,0,.2); }
:root[data-theme="dark"] .micro-toggle { border-color: rgba(190,226,244,.2); background: rgba(76,117,141,.15); }
:root[data-theme="dark"] .micro-toggle[aria-pressed="true"] { color: #b8ffda; border-color: rgba(67,213,139,.35); background: rgba(21,149,85,.26); box-shadow: 0 0 15px rgba(20,208,114,.12); }
/* Photographic aeroglass refinement. The backdrop already contains optical
blur, so the UI only adds a restrained haze instead of whitening the scene. */
:root {
--tile: rgba(214, 238, 251, 0.14);
--tile-strong: rgba(247, 252, 255, 0.27);
--tile-line: rgba(255, 255, 255, 0.82);
--tile-line-soft: rgba(206, 235, 249, 0.43);
--panel-glass: rgba(200, 228, 244, 0.2);
--blue-halo: rgba(23, 137, 248, 0.16);
--green-halo: rgba(28, 196, 113, 0.16);
--orange-halo: rgba(246, 126, 50, 0.14);
}
:root[data-theme="dark"] {
--tile: rgba(16, 37, 51, 0.28);
--tile-strong: rgba(52, 78, 96, 0.31);
--tile-line: rgba(203, 234, 248, 0.25);
--tile-line-soft: rgba(114, 176, 207, 0.16);
--panel-glass: rgba(7, 22, 33, 0.48);
--blue-halo: rgba(29, 153, 245, 0.22);
--green-halo: rgba(27, 210, 121, 0.19);
--orange-halo: rgba(246, 125, 46, 0.18);
}
body {
background-color: #b7d5e3;
background-image: none;
}
:root[data-theme="dark"] body {
background-color: #091722;
background-image: none;
}
body::before {
inset: -1.25rem;
background-image:
linear-gradient(118deg, rgba(180,220,239,.15), rgba(238,247,251,.025) 45%, rgba(247,226,204,.09)),
url("../assets/mountain-lake-light.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
filter: blur(6px) saturate(108%);
transform: scale(1.025);
opacity: 1;
pointer-events: none;
}
:root[data-theme="dark"] body::before {
background-image:
linear-gradient(118deg, rgba(2,15,25,.66), rgba(8,27,40,.57) 48%, rgba(20,25,29,.64)),
url("../assets/mountain-lake-dark.jpg");
background-position: center;
background-size: cover;
filter: blur(7px) saturate(106%);
opacity: 1;
}
body::after {
background:
radial-gradient(circle at 11% 18%, rgba(255,255,255,.33) 0 .5%, transparent 5%),
radial-gradient(circle at 64% 23%, rgba(255,244,218,.28) 0 .6%, transparent 6%),
radial-gradient(circle at 91% 79%, rgba(225,250,237,.22) 0 .8%, transparent 7%);
filter: blur(11px);
opacity: .5;
}
:root[data-theme="dark"] body::after { opacity: .26; }
.ambient::before { opacity: .14; filter: blur(76px); }
.ambient::after { opacity: .11; filter: blur(82px); }
:root[data-theme="dark"] .ambient::before { opacity: .12; }
:root[data-theme="dark"] .ambient::after { opacity: .08; }
.climate-panel {
background:
linear-gradient(125deg, rgba(255,255,255,.22), transparent 31%, rgba(255,255,255,.055) 69%, rgba(196,224,240,.1)),
var(--panel-glass);
box-shadow: 0 27px 68px rgba(22,66,95,.24), 0 2px 8px rgba(255,255,255,.28), inset 0 1px 0 rgba(255,255,255,.88), inset 0 -1px 0 rgba(113,163,192,.17);
backdrop-filter: blur(13px) saturate(124%);
-webkit-backdrop-filter: blur(13px) saturate(124%);
}
.climate-panel::before {
background:
linear-gradient(112deg, rgba(255,255,255,.25), rgba(255,255,255,.035) 18%, transparent 39%),
radial-gradient(ellipse at 50% -20%, rgba(255,255,255,.25), transparent 47%);
}
.climate-panel::after { opacity: .1; }
:root[data-theme="dark"] .climate-panel { box-shadow: 0 33px 78px rgba(0,0,0,.43), 0 0 28px rgba(19,112,158,.06), inset 0 1px 0 rgba(221,243,252,.17), inset 0 -1px 0 rgba(0,0,0,.28); }
:root[data-theme="dark"] .climate-panel::before { background: linear-gradient(112deg, rgba(203,238,253,.1), transparent 24%, transparent 72%, rgba(71,163,202,.035)); }
.glass-tile, .glass-section {
background:
linear-gradient(132deg, rgba(255,255,255,.25), rgba(255,255,255,.035) 35%, transparent 64%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: 0 10px 25px rgba(24,72,105,.12), inset 0 1px 0 rgba(255,255,255,.78), inset 1px 0 0 rgba(255,255,255,.24);
backdrop-filter: blur(16px) saturate(127%);
-webkit-backdrop-filter: blur(16px) saturate(127%);
}
.glass-tile::before, .glass-section::before { opacity: .62; }
:root[data-theme="dark"] .glass-tile,
:root[data-theme="dark"] .glass-section {
background:
linear-gradient(132deg, rgba(213,240,252,.075), rgba(255,255,255,.012) 38%, transparent 65%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: 0 13px 29px rgba(0,0,0,.26), inset 0 1px 0 rgba(226,246,255,.11), inset 1px 0 0 rgba(186,226,245,.055);
}
.speed-card::after, .temperature-card::after, .power-card::after, .heater-card::after { filter: blur(32px); opacity: .48; }
.power-card::after { opacity: .38; }
.heater-card::after { opacity: .34; }
.hero-step.primary { box-shadow: 0 10px 23px rgba(16,103,220,.25), 0 0 15px var(--blue-halo), inset 0 1px 0 rgba(255,255,255,.76), inset 0 -2px 5px rgba(0,67,156,.2); }
.hero-step:hover { box-shadow: 0 12px 27px rgba(25,112,219,.27), 0 0 19px var(--blue-halo), inset 0 1px 0 rgba(255,255,255,.75); }
.speed-segments button.active { box-shadow: 0 0 9px rgba(25,143,247,.34), inset 0 1px 0 rgba(255,255,255,.66), inset 0 -2px 4px rgba(0,84,182,.18); }
.temperature-range::-webkit-slider-runnable-track { box-shadow: 0 0 8px rgba(37,153,239,.15), 0 0 7px rgba(255,114,41,.09), inset 0 1px 2px rgba(255,255,255,.46); }
.temperature-range::-webkit-slider-thumb { box-shadow: 0 0 0 2px rgba(255,255,255,.48), 0 0 12px rgba(29,139,241,.34), 0 4px 10px rgba(17,79,143,.24); }
.glass-switch[aria-pressed="true"].green { box-shadow: 0 12px 27px rgba(11,153,81,.22), 0 0 19px var(--green-halo), inset 0 1px 0 rgba(255,255,255,.84), inset 0 -4px 10px rgba(0,125,62,.14); }
.glass-switch[aria-pressed="true"].orange { box-shadow: 0 12px 27px rgba(210,91,25,.2), 0 0 18px var(--orange-halo), inset 0 1px 0 rgba(255,255,255,.83), inset 0 -4px 10px rgba(168,54,0,.13); }
.quality-chip { box-shadow: 0 0 10px rgba(33,203,116,.13), inset 0 1px 0 rgba(255,255,255,.83); }
.meter i { box-shadow: 0 0 10px rgba(18,199,104,.35), inset 0 1px 0 rgba(255,255,255,.58); }
.filter-meter i { box-shadow: 0 0 10px rgba(31,144,247,.32), inset 0 1px 0 rgba(255,255,255,.54); }
.schedule-button.auto, .schedule-button.pause { box-shadow: 0 7px 18px rgba(31,83,119,.12), inset 0 1px 0 rgba(255,255,255,.82); }
:root[data-theme="dark"] .hero-step.primary { box-shadow: 0 11px 27px rgba(0,65,139,.4), 0 0 18px var(--blue-halo), inset 0 1px 0 rgba(220,248,255,.42), inset 0 -3px 7px rgba(0,27,91,.3); }
:root[data-theme="dark"] .speed-segments button.active { box-shadow: 0 0 12px rgba(24,156,255,.4), inset 0 1px 0 rgba(223,248,255,.36); }
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].green { box-shadow: 0 12px 28px rgba(0,0,0,.28), 0 0 20px var(--green-halo), inset 0 1px 0 rgba(218,255,236,.4); }
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].orange { box-shadow: 0 12px 28px rgba(0,0,0,.28), 0 0 20px var(--orange-halo), inset 0 1px 0 rgba(255,237,216,.4); }
/* Natural highlights: state colors tint the glass, but do not paint opaque
neon blocks over the photographic background. Heater ON is a healthy green
state too; its orange icon still communicates heat. */
.speed-card::after, .temperature-card::after { opacity: .18; filter: blur(42px); }
.power-card::after, .heater-card::after { background: var(--green-halo); opacity: .16; filter: blur(44px); }
.hero-step.primary { box-shadow: 0 9px 20px rgba(15,92,183,.22), 0 0 9px rgba(48,151,239,.14), inset 0 1px 0 rgba(255,255,255,.78), inset 0 -2px 5px rgba(0,67,156,.18); }
.hero-step:hover { box-shadow: 0 11px 23px rgba(20,101,190,.24), 0 0 12px rgba(48,151,239,.16), inset 0 1px 0 rgba(255,255,255,.76); }
.speed-segments button.active { box-shadow: 0 0 6px rgba(25,143,247,.24), inset 0 1px 0 rgba(255,255,255,.68), inset 0 -2px 4px rgba(0,84,182,.16); }
.glass-switch[aria-pressed="true"].green,
.glass-switch[aria-pressed="true"].orange {
background: linear-gradient(145deg, rgba(139,244,190,.72), rgba(55,194,122,.48));
border-color: rgba(218,255,235,.84);
box-shadow: 0 10px 23px rgba(18,143,80,.18), 0 0 11px rgba(38,199,116,.13), inset 0 1px 0 rgba(255,255,255,.82), inset 0 -3px 8px rgba(0,114,57,.1);
}
:root[data-theme="dark"] .speed-card::after,
:root[data-theme="dark"] .temperature-card::after { opacity: .2; }
:root[data-theme="dark"] .power-card::after,
:root[data-theme="dark"] .heater-card::after { opacity: .18; }
:root[data-theme="dark"] .hero-step.primary { box-shadow: 0 10px 24px rgba(0,53,119,.38), 0 0 11px rgba(41,162,244,.19), inset 0 1px 0 rgba(220,248,255,.4), inset 0 -3px 7px rgba(0,27,91,.27); }
:root[data-theme="dark"] .speed-segments button.active { box-shadow: 0 0 7px rgba(24,156,255,.27), inset 0 1px 0 rgba(223,248,255,.34); }
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].green,
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].orange {
color: #effff6;
border-color: rgba(127,242,182,.4);
background: linear-gradient(145deg, rgba(51,190,119,.58), rgba(9,102,59,.55));
box-shadow: 0 11px 25px rgba(0,0,0,.25), 0 0 12px rgba(37,207,121,.15), inset 0 1px 0 rgba(218,255,236,.34);
}
/* Final material and icon polish. */
.ui-icon {
display: block;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.feature-icon { padding: .08rem; filter: drop-shadow(0 0 6px rgba(20,139,244,.2)); text-shadow: none; }
.feature-icon.green { filter: drop-shadow(0 0 6px rgba(20,190,104,.24)); }
.feature-icon.orange { filter: drop-shadow(0 0 6px rgba(244,105,31,.22)); }
.fan-icon { font-size: inherit; }
.section-icon { padding: .06rem; filter: drop-shadow(0 0 5px rgba(26,124,210,.17)); text-shadow: none; }
.section-icon.leaf { filter: drop-shadow(0 0 5px rgba(8,160,81,.2)); }
.metric-icon { width: 1.7rem; height: 1.7rem; flex: 0 0 auto; filter: drop-shadow(0 0 4px rgba(20,124,221,.15)); text-shadow: none; }
.metric-icon.particles { padding: .05rem; }
.action-symbol { width: 2rem; height: 2rem; font-size: inherit; }
.extra-icon { width: 3.4rem; height: 3.4rem; flex: 0 0 auto; filter: drop-shadow(0 0 7px rgba(33,126,211,.17)); text-shadow: none; }
.extra-icon.wind { width: 3.8rem; height: 3.8rem; font-size: inherit; transform: none; }
:root[data-theme="light"] {
--tile: rgba(104, 126, 139, 0.16);
--tile-strong: rgba(214, 226, 232, 0.2);
--tile-line-soft: rgba(189, 211, 221, 0.38);
}
:root[data-theme="light"] .glass-tile,
:root[data-theme="light"] .glass-section {
background:
linear-gradient(132deg, rgba(244,248,250,.22), rgba(159,178,188,.055) 38%, transparent 66%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
backdrop-filter: blur(14px) saturate(116%);
-webkit-backdrop-filter: blur(14px) saturate(116%);
}
.metric-card:not(.co2-card) {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
.metric-card:not(.co2-card) .metric-heading { width: 100%; justify-content: center; text-align: left; }
.metric-card:not(.co2-card) > strong { margin-top: .7rem; }
.metric-card:not(.co2-card) .quality-chip { align-self: center; }
.filter-card .filter-line { width: 100%; }
.hero-step.primary {
background:
radial-gradient(circle at 24% 5%, rgba(255,255,255,.55), transparent 38%),
linear-gradient(135deg, rgba(255,255,255,.16), transparent 42%, rgba(0,73,170,.1)),
linear-gradient(145deg, #55b4ff, #1479e8 72%);
box-shadow: 0 8px 18px rgba(15,92,183,.18), 0 0 7px rgba(48,151,239,.1), inset 0 1px 0 rgba(255,255,255,.86), inset 0 -3px 7px rgba(0,67,156,.16);
}
.hero-step.primary:hover { box-shadow: 0 10px 21px rgba(20,101,190,.21), 0 0 9px rgba(48,151,239,.12), inset 0 1px 0 rgba(255,255,255,.88); }
.speed-segments button.active {
background:
linear-gradient(180deg, rgba(255,255,255,.32), transparent 48%),
linear-gradient(90deg, #1685ec, #35afff);
box-shadow: 0 0 5px rgba(25,143,247,.19), inset 0 1px 0 rgba(255,255,255,.75), inset 0 -2px 4px rgba(0,84,182,.13);
}
.glass-switch { overflow: hidden; }
.glass-switch[aria-pressed="true"].green,
.glass-switch[aria-pressed="true"].orange {
background:
radial-gradient(circle at 25% -8%, rgba(255,255,255,.67), transparent 42%),
linear-gradient(132deg, rgba(255,255,255,.15), transparent 40%, rgba(0,125,62,.06)),
linear-gradient(145deg, rgba(139,244,190,.67), rgba(55,194,122,.43));
box-shadow: 0 8px 19px rgba(18,143,80,.14), 0 0 8px rgba(38,199,116,.09), inset 0 1px 0 rgba(255,255,255,.9), inset 0 -4px 9px rgba(0,114,57,.08);
}
.schedule-button.auto {
background:
radial-gradient(circle at 19% -30%, rgba(255,255,255,.55), transparent 44%),
linear-gradient(135deg, rgba(255,255,255,.13), transparent 43%),
linear-gradient(145deg, rgba(211,239,255,.52), rgba(100,179,235,.18));
}
.schedule-button.pause {
background:
radial-gradient(circle at 19% -30%, rgba(255,255,255,.58), transparent 44%),
linear-gradient(135deg, rgba(255,255,255,.13), transparent 43%),
linear-gradient(145deg, rgba(255,231,199,.55), rgba(235,151,76,.18));
}
:root[data-theme="dark"] .hero-step.primary {
background:
radial-gradient(circle at 24% 5%, rgba(214,246,255,.32), transparent 38%),
linear-gradient(135deg, rgba(255,255,255,.08), transparent 42%, rgba(0,32,95,.17)),
linear-gradient(145deg, #33aaf4, #0869d0 74%);
}
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].green,
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].orange {
background:
radial-gradient(circle at 25% -8%, rgba(218,255,236,.3), transparent 42%),
linear-gradient(132deg, rgba(255,255,255,.07), transparent 40%, rgba(0,45,23,.12)),
linear-gradient(145deg, rgba(51,190,119,.52), rgba(9,102,59,.49));
box-shadow: 0 9px 21px rgba(0,0,0,.22), 0 0 9px rgba(37,207,121,.1), inset 0 1px 0 rgba(218,255,236,.32), inset 0 -3px 8px rgba(0,31,16,.16);
}
:root[data-theme="dark"] .schedule-button.auto {
background:
radial-gradient(circle at 19% -30%, rgba(208,243,255,.17), transparent 45%),
linear-gradient(145deg, rgba(38,125,187,.26), rgba(15,61,91,.25));
}
:root[data-theme="dark"] .schedule-button.pause {
background:
radial-gradient(circle at 19% -30%, rgba(255,226,199,.16), transparent 45%),
linear-gradient(145deg, rgba(167,82,27,.27), rgba(73,40,25,.25));
}
@media (min-width: 1300px) and (min-height: 760px) {
.climate-panel {
width: 100%;
max-width: none;
display: grid;
grid-template-rows: auto minmax(18rem, 1.4fr) minmax(11rem, .78fr) minmax(13rem, .9fr) auto;
gap: .75rem;
}
.panel-header { padding-bottom: 0; }
.primary-controls, .bottom-grid { min-height: 0; height: 100%; }
.control-card, .switch-card { min-height: 0; height: 100%; }
.content-section { min-height: 0; height: 100%; margin-top: 0; display: flex; flex-direction: column; }
.air-grid { min-height: 0; flex: 1; }
.metric-card { min-height: 0; height: 100%; }
.schedule-layout, .extras-grid { min-height: 0; flex: 1; }
.schedule-times, .extra-card { min-height: 0; height: 100%; }
}
@media (min-width: 1700px) {
html { font-size: 18px; }
.climate-panel { padding: 1.2rem; }
}
@media (max-width: 1120px) {
.primary-controls { grid-template-columns: 1fr 1fr; }
.switch-card { min-height: 9rem; }
.glass-switch { min-height: 3.8rem; }
.air-grid { grid-template-columns: repeat(3, 1fr); }
.bottom-grid { grid-template-columns: 1fr; }
}
@media (max-width: 760px) {
body { padding: .5rem; }
.climate-panel { border-radius: 1.1rem; }
.panel-header, .identity, .header-tools { flex-wrap: wrap; }
.panel-header { align-items: flex-start; }
.header-tools { width: 100%; justify-content: flex-start; }
.ventilation-badge { min-width: 0; flex: 1; }
.primary-controls { grid-template-columns: 1fr; }
.control-card, .switch-card { min-height: auto; }
.hero-control { margin: 1.4rem 0 .75rem; }
.air-grid { grid-template-columns: 1fr 1fr; }
.co2-card, .filter-card { grid-column: 1 / -1; }
.schedule-layout { grid-template-columns: 1fr; }
}
@media (max-width: 480px) {
.identity h1 { width: 100%; }
.ventilation-badge small { display: none; }
.air-grid, .extras-grid { grid-template-columns: 1fr; }
.co2-card, .filter-card { grid-column: auto; }
.schedule-times { grid-template-columns: 1fr; }
.schedule-times > i { width: 100%; height: 1px; }
.micro-settings { flex-wrap: wrap; }
}
@media (prefers-reduced-motion: reduce) { .hero-step:hover { transform: none; } }
/* Schedule controls and editor. */
.schedule-title-tools { margin-left: auto; }
.schedule-edit-button {
display: inline-flex;
align-items: center;
gap: .4rem;
min-height: 2.05rem;
padding: .36rem .68rem;
border: 1px solid var(--tile-line);
border-radius: .7rem;
color: #126fc4;
background:
radial-gradient(circle at 20% -35%, rgba(255,255,255,.48), transparent 48%),
linear-gradient(145deg, rgba(220,241,253,.42), rgba(100,173,220,.13));
box-shadow: 0 6px 15px rgba(27,91,135,.1), inset 0 1px 0 rgba(255,255,255,.76);
cursor: pointer;
font-size: .65rem;
font-weight: 750;
transition: transform .15s ease, filter .15s ease;
}
.schedule-edit-button svg { width: 1rem; height: 1rem; }
.schedule-edit-button:hover { transform: translateY(-1px); filter: brightness(1.06); }
.schedule-button:disabled { cursor: not-allowed; opacity: .5; filter: saturate(.38); box-shadow: none; }
.schedule-button:disabled:hover { transform: none; filter: saturate(.38); }
.schedule-button[aria-busy="true"] { cursor: wait; }
#schedule-state.warn {
color: #8d3b00;
border-color: rgba(247,162,73,.78);
background: linear-gradient(145deg, rgba(255,232,190,.82), rgba(240,157,69,.42));
box-shadow: 0 0 12px rgba(237,130,39,.13), inset 0 1px 0 rgba(255,255,255,.86);
font-size: .66rem;
letter-spacing: .07em;
}
:root[data-theme="dark"] #schedule-state.warn {
color: #ffe2b8;
border-color: rgba(255,166,83,.57);
background: linear-gradient(145deg, rgba(177,87,24,.52), rgba(95,45,17,.48));
box-shadow: 0 0 13px rgba(242,129,38,.15), inset 0 1px 0 rgba(255,228,198,.18);
}
.schedule-dialog {
width: min(72rem, calc(100vw - 2rem));
max-width: none;
max-height: calc(100vh - 2rem);
padding: 0;
border: 1px solid var(--panel-edge);
border-radius: 1.35rem;
color: var(--panel-ink);
background:
linear-gradient(125deg, rgba(255,255,255,.28), transparent 32%, rgba(255,255,255,.06) 72%),
rgba(201,229,244,.72);
box-shadow: 0 28px 90px rgba(8,45,70,.42), inset 0 1px 0 rgba(255,255,255,.9);
backdrop-filter: blur(28px) saturate(135%);
-webkit-backdrop-filter: blur(28px) saturate(135%);
overflow: hidden;
}
.schedule-dialog::backdrop { background: rgba(5,20,31,.46); backdrop-filter: blur(9px); -webkit-backdrop-filter: blur(9px); }
:root[data-theme="dark"] .schedule-dialog { background: linear-gradient(125deg, rgba(205,239,255,.1), transparent 34%), rgba(7,24,36,.88); box-shadow: 0 30px 100px rgba(0,0,0,.64), inset 0 1px 0 rgba(221,243,252,.15); }
.schedule-editor { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; max-height: calc(100vh - 2rem); }
.editor-header, .editor-footer { display: flex; align-items: center; gap: .7rem; padding: .8rem 1rem; }
.editor-header { justify-content: space-between; border-bottom: 1px solid var(--tile-line-soft); }
.editor-heading { display: flex; align-items: center; gap: .65rem; }
.editor-heading > svg { width: 2rem; height: 2rem; color: #1883df; filter: drop-shadow(0 0 5px rgba(24,131,223,.2)); }
.editor-heading h2 { margin: 0; font-size: 1.15rem; }
.editor-heading small { display: block; margin-top: .15rem; color: var(--panel-muted); font-size: .63rem; }
.editor-close { width: 2.2rem; height: 2.2rem; padding: 0; border: 1px solid var(--tile-line); border-radius: .75rem; color: var(--panel-muted); background: var(--tile); cursor: pointer; font-size: 1.45rem; line-height: 1; }
.editor-scroll { display: grid; gap: .7rem; padding: .85rem 1rem 1rem; overflow: auto; }
.schedule-enabled { display: flex; align-items: center; gap: .7rem; padding: .72rem .82rem; border: 1px solid var(--tile-line); border-radius: .9rem; background: linear-gradient(145deg, rgba(255,255,255,.22), rgba(120,169,195,.08)); cursor: pointer; }
.schedule-enabled input { width: 1.1rem; height: 1.1rem; accent-color: var(--blue); }
.schedule-enabled span { display: grid; gap: .12rem; }
.schedule-enabled strong { font-size: .76rem; }
.schedule-enabled small { color: var(--panel-muted); font-size: .61rem; }
.editor-section { padding: .8rem; border: 1px solid var(--tile-line); border-radius: 1rem; background: linear-gradient(145deg, rgba(255,255,255,.19), rgba(94,148,179,.075)); box-shadow: inset 0 1px 0 rgba(255,255,255,.48); }
:root[data-theme="dark"] .editor-section, :root[data-theme="dark"] .schedule-enabled { background: linear-gradient(145deg, rgba(205,236,249,.055), rgba(2,19,30,.12)); box-shadow: inset 0 1px 0 rgba(224,246,255,.07); }
.editor-section-title { display: flex; align-items: end; justify-content: space-between; gap: .75rem; margin-bottom: .65rem; }
.editor-section-title h3 { margin: 0; font-size: .86rem; }
.editor-section-title small { display: block; margin-top: .13rem; color: var(--panel-muted); font-size: .6rem; }
.day-assignments { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: .42rem; }
.day-assignment { display: grid; gap: .3rem; color: var(--panel-muted); font-size: .58rem; font-weight: 700; }
.day-assignment select, .template-toolbar select, .point-editor input, .point-editor select {
min-width: 0;
height: 2.25rem;
padding: .38rem .48rem;
border: 1px solid var(--tile-line);
border-radius: .62rem;
color: var(--panel-ink);
background: rgba(245,251,253,.48);
outline: none;
font-size: .66rem;
}
:root[data-theme="dark"] .day-assignment select,
:root[data-theme="dark"] .template-toolbar select,
:root[data-theme="dark"] .point-editor input,
:root[data-theme="dark"] .point-editor select { background: rgba(16,38,52,.72); }
.day-assignment select:focus, .template-toolbar select:focus, .point-editor input:focus, .point-editor select:focus { border-color: rgba(45,151,230,.7); box-shadow: 0 0 0 3px rgba(34,145,226,.11); }
.template-toolbar > label { display: grid; gap: .25rem; min-width: 10rem; color: var(--panel-muted); font-size: .57rem; font-weight: 700; }
.template-actions { display: flex; align-items: end; gap: .35rem; }
.template-actions button { min-height: 2.25rem; padding: .4rem .65rem; border: 1px solid var(--tile-line); border-radius: .62rem; color: #126fc4; background: rgba(52,150,220,.08); cursor: pointer; font-size: .61rem; font-weight: 700; }
.template-actions #delete-template { color: var(--red); border-color: rgba(223,91,105,.28); background: var(--red-soft); }
.template-actions button:disabled { cursor: not-allowed; opacity: .45; }
.schedule-points { display: grid; gap: .55rem; }
.point-editor { padding: .68rem; border: 1px solid var(--tile-line); border-radius: .85rem; background: linear-gradient(145deg, rgba(255,255,255,.22), rgba(116,160,183,.065)); box-shadow: inset 0 1px 0 rgba(255,255,255,.45); }
:root[data-theme="dark"] .point-editor { background: linear-gradient(145deg, rgba(197,231,247,.055), rgba(2,18,29,.13)); box-shadow: inset 0 1px 0 rgba(224,246,255,.06); }
.point-header { display: grid; grid-template-columns: auto minmax(7rem, .7fr) minmax(9rem, 1fr) auto; align-items: end; gap: .55rem; }
.point-number { align-self: center; display: grid; place-items: center; width: 1.85rem; height: 1.85rem; border-radius: 50%; color: #1478cc; background: var(--blue-soft); font-size: .62rem; font-weight: 800; }
.point-header label, .point-setting { display: grid; gap: .25rem; color: var(--panel-muted); font-size: .56rem; font-weight: 700; }
.remove-point { width: 2.25rem; height: 2.25rem; padding: 0; border: 1px solid rgba(223,91,105,.32); border-radius: .62rem; color: var(--red); background: var(--red-soft); cursor: pointer; font-size: 1.1rem; }
.point-settings { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: .48rem; margin-top: .55rem; }
.point-editor.auto [data-set-only] { display: none; }
.point-editor.auto .point-settings { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.empty-points { padding: 1.4rem; border: 1px dashed var(--tile-line); border-radius: .8rem; color: var(--panel-muted); text-align: center; font-size: .68rem; }
.add-schedule-point { width: 100%; min-height: 2.55rem; margin-top: .6rem; border: 1px dashed rgba(37,131,205,.55); border-radius: .75rem; color: #126fc4; background: rgba(52,150,220,.08); cursor: pointer; font-size: .68rem; font-weight: 750; }
.editor-footer { border-top: 1px solid var(--tile-line-soft); justify-content: flex-end; }
.editor-status { margin-right: auto; color: var(--panel-muted); font-size: .63rem; }
.editor-status.error { color: var(--red); }
.editor-button { min-height: 2.5rem; padding: .58rem .9rem; border-radius: .75rem; cursor: pointer; font-size: .69rem; font-weight: 750; }
.editor-button.secondary { border: 1px solid var(--tile-line); color: var(--panel-ink); background: var(--tile); }
.editor-button.primary { border: 1px solid rgba(182,226,255,.76); color: white; background: radial-gradient(circle at 20% -30%, rgba(255,255,255,.5), transparent 48%), linear-gradient(145deg, #3aa9eb, #1476c9); box-shadow: 0 7px 17px rgba(18,102,170,.2), inset 0 1px 0 rgba(255,255,255,.75); }
@media (max-width: 900px) {
.day-assignments { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.point-settings { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (max-width: 600px) {
.schedule-dialog { width: calc(100vw - .7rem); max-height: calc(100vh - .7rem); border-radius: 1rem; }
.schedule-editor { max-height: calc(100vh - .7rem); }
.editor-header, .editor-footer { padding: .7rem; }
.editor-scroll { padding: .7rem; }
.day-assignments { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.editor-section-title { align-items: stretch; flex-direction: column; }
.template-toolbar > label { min-width: 0; }
.template-actions { align-items: stretch; }
.template-actions button { flex: 1; }
.point-header { grid-template-columns: auto 1fr auto; }
.point-header .point-action { grid-column: 2 / -1; }
.point-settings, .point-editor.auto .point-settings { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.editor-footer { flex-wrap: wrap; }
.editor-status { width: 100%; }
.schedule-edit-button span { display: none; }
}
/* CO2 state drives both the label and the meter, so the visual state cannot
disagree with the air-quality text returned by airQuality(). */
.co2-card {
--air-color: #7896ac;
--air-glow: rgba(93, 140, 171, .22);
--air-track: rgba(181, 203, 200, .28);
}
.co2-card[data-air-tone="good"] {
--air-color: #1fbd69;
--air-glow: rgba(18, 199, 104, .34);
}
.co2-card[data-air-tone="warn"] {
--air-color: #efa12b;
--air-glow: rgba(244, 161, 42, .35);
}
.co2-card[data-air-tone="bad"] {
--air-color: #e8495c;
--air-glow: rgba(235, 74, 83, .36);
}
.co2-card .co2-meter {
height: .84rem;
border-color: rgba(255,255,255,.82);
background-color: var(--air-track);
background-image: linear-gradient(180deg, rgba(255,255,255,.15), transparent 52%, rgba(0,20,36,.045));
box-shadow: inset 0 1px 3px rgba(20,61,78,.14), 0 1px 4px rgba(8,43,72,.07);
transition: background-color .65s ease;
}
.co2-card .co2-meter i {
background-color: var(--air-color);
background-image: linear-gradient(180deg, rgba(255,255,255,.28), rgba(255,255,255,.045) 48%, rgba(0,35,20,.1));
box-shadow: 0 0 8px var(--air-glow), inset 0 1px 0 rgba(255,255,255,.58), inset 0 -1px 2px rgba(0,34,19,.1);
transition: width .35s ease, background-color .65s ease, box-shadow .65s ease;
}
:root[data-theme="dark"] .co2-card .co2-meter { border-color: rgba(205,235,248,.3); box-shadow: inset 0 1px 4px rgba(0,0,0,.27), 0 1px 5px rgba(0,0,0,.12); }
.co2-card .quality-chip.muted {
color: var(--panel-muted);
border-color: var(--tile-line-soft);
background: rgba(199,222,235,.2);
box-shadow: inset 0 1px 0 rgba(255,255,255,.55);
}
.co2-card .quality-chip.good {
color: #076d3d;
border-color: rgba(109,237,167,.65);
background: linear-gradient(145deg, rgba(179,255,214,.58), rgba(92,218,151,.39));
box-shadow: 0 0 9px rgba(33,203,116,.12), inset 0 1px 0 rgba(255,255,255,.82);
}
.co2-card .quality-chip.warn {
color: #9c5513;
border-color: rgba(244,183,106,.67);
background: linear-gradient(145deg, rgba(255,232,188,.56), rgba(239,168,80,.34));
box-shadow: 0 0 9px rgba(235,153,53,.11), inset 0 1px 0 rgba(255,255,255,.8);
}
.co2-card .quality-chip.bad {
color: #a62f3d;
border-color: rgba(242,135,147,.62);
background: linear-gradient(145deg, rgba(255,209,216,.53), rgba(225,105,120,.3));
box-shadow: 0 0 9px rgba(224,83,101,.12), inset 0 1px 0 rgba(255,255,255,.78);
}
:root[data-theme="dark"] .co2-card { --air-track: rgba(8,28,39,.38); }
:root[data-theme="dark"] .co2-card[data-air-tone="good"] { --air-glow: rgba(30,224,128,.3); }
:root[data-theme="dark"] .co2-card[data-air-tone="warn"] { --air-glow: rgba(255,176,49,.3); }
:root[data-theme="dark"] .co2-card[data-air-tone="bad"] { --air-glow: rgba(255,82,102,.32); }
:root[data-theme="dark"] .co2-card .quality-chip.good { color: #b9ffda; background: linear-gradient(145deg, rgba(45,186,113,.35), rgba(11,101,60,.3)); }
:root[data-theme="dark"] .co2-card .quality-chip.warn { color: #ffd59e; background: linear-gradient(145deg, rgba(176,115,30,.34), rgba(91,58,15,.3)); }
:root[data-theme="dark"] .co2-card .quality-chip.bad { color: #ffc0c8; background: linear-gradient(145deg, rgba(174,58,75,.34), rgba(91,25,37,.31)); }
:root[data-theme="dark"] .co2-card .quality-chip.muted { color: var(--panel-muted); background: rgba(42,70,88,.25); }
-601
View File
@@ -1,601 +0,0 @@
:root {
--widget-ink: #08265d;
--widget-muted: #315d91;
--widget-glass: rgba(200, 228, 244, 0.21);
--widget-edge: rgba(255, 255, 255, 0.9);
--tile: rgba(104, 126, 139, 0.16);
--tile-strong: rgba(214, 226, 232, 0.2);
--tile-edge: rgba(255, 255, 255, 0.82);
--tile-edge-soft: rgba(189, 211, 221, 0.38);
--tile-shadow: 0 10px 25px rgba(24, 72, 105, 0.12), inset 0 1px 0 rgba(255,255,255,.78), inset 1px 0 0 rgba(255,255,255,.24);
--blue-halo: rgba(23, 137, 248, 0.16);
--green-halo: rgba(28, 196, 113, 0.16);
--orange-halo: rgba(246, 126, 50, 0.14);
}
:root[data-theme="dark"] {
--widget-ink: #edf8ff;
--widget-muted: #9fc5df;
--widget-glass: rgba(7, 22, 33, 0.49);
--widget-edge: rgba(187, 225, 244, 0.3);
--tile: rgba(16, 37, 51, 0.3);
--tile-strong: rgba(52, 78, 96, 0.33);
--tile-edge: rgba(203, 234, 248, 0.25);
--tile-edge-soft: rgba(114, 176, 207, 0.16);
--tile-shadow: 0 13px 29px rgba(0,0,0,.26), inset 0 1px 0 rgba(226,246,255,.11), inset 1px 0 0 rgba(186,226,245,.055);
--blue-halo: rgba(29, 153, 245, 0.22);
--green-halo: rgba(27, 210, 121, 0.19);
--orange-halo: rgba(246, 125, 46, 0.18);
}
html { min-width: 280px; }
body {
min-height: 100vh;
margin: 0;
padding: clamp(.5rem, 2.2vw, 1rem);
display: flex;
align-items: flex-start;
justify-content: center;
color: var(--widget-ink);
background-color: #b7d5e3;
overflow-x: hidden;
isolation: isolate;
}
:root[data-theme="dark"] body {
background-color: #091722;
}
body::before,
body::after {
content: "";
position: fixed;
pointer-events: none;
}
body::before {
inset: -1.25rem;
z-index: -2;
background-image:
linear-gradient(118deg, rgba(180,220,239,.15), rgba(238,247,251,.025) 45%, rgba(247,226,204,.09)),
url("../assets/mountain-lake-light.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
filter: blur(6px) saturate(108%);
transform: scale(1.025);
}
body::after {
inset: 0;
z-index: -1;
background:
radial-gradient(circle at 11% 18%, rgba(255,255,255,.32) 0 .5%, transparent 5%),
radial-gradient(circle at 64% 23%, rgba(255,244,218,.27) 0 .6%, transparent 6%),
radial-gradient(circle at 91% 79%, rgba(225,250,237,.21) 0 .8%, transparent 7%);
filter: blur(11px);
opacity: .5;
}
:root[data-theme="dark"] body::before {
background-image:
linear-gradient(118deg, rgba(2,15,25,.66), rgba(8,27,40,.57) 48%, rgba(20,25,29,.64)),
url("../assets/mountain-lake-dark.jpg");
filter: blur(7px) saturate(106%);
}
:root[data-theme="dark"] body::after { opacity: .25; }
.ambient::before { width: 32rem; height: 32rem; left: -13rem; top: -14rem; background: #c9f2ff; opacity: .14; filter: blur(76px); }
.ambient::after { width: 34rem; height: 34rem; right: -14rem; bottom: -16rem; background: #ebd5a7; opacity: .11; filter: blur(82px); }
:root[data-theme="dark"] .ambient::before { background: #147db5; opacity: .12; }
:root[data-theme="dark"] .ambient::after { background: #846630; opacity: .08; }
.widget {
position: relative;
isolation: isolate;
width: min(100%, 31.5rem);
display: grid;
gap: .65rem;
padding: clamp(.65rem, 2.2vw, .9rem);
overflow: hidden;
border: 1px solid var(--widget-edge);
outline: 1px solid rgba(255,255,255,.48);
outline-offset: -5px;
border-radius: 1.55rem;
background:
linear-gradient(125deg, rgba(255,255,255,.22), transparent 31%, rgba(255,255,255,.055) 69%, rgba(196,224,240,.1)),
var(--widget-glass);
box-shadow: 0 27px 68px rgba(22,66,95,.24), 0 2px 8px rgba(255,255,255,.28), inset 0 1px 0 rgba(255,255,255,.88), inset 0 -1px 0 rgba(113,163,192,.17);
backdrop-filter: blur(13px) saturate(124%);
-webkit-backdrop-filter: blur(13px) saturate(124%);
}
.widget::before,
.widget::after {
content: "";
position: absolute;
inset: 0;
z-index: 0;
border-radius: inherit;
pointer-events: none;
}
.widget::before {
background:
linear-gradient(112deg, rgba(255,255,255,.25), rgba(255,255,255,.035) 18%, transparent 39%),
radial-gradient(ellipse at 50% -20%, rgba(255,255,255,.25), transparent 47%);
}
.widget::after {
opacity: .1;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.16'/%3E%3C/svg%3E");
mix-blend-mode: soft-light;
}
.widget > * { position: relative; z-index: 1; }
:root[data-theme="dark"] .widget { outline-color: rgba(203,235,250,.11); box-shadow: 0 33px 78px rgba(0,0,0,.43), 0 0 28px rgba(19,112,158,.06), inset 0 1px 0 rgba(221,243,252,.17), inset 0 -1px 0 rgba(0,0,0,.28); }
:root[data-theme="dark"] .widget::before { background: linear-gradient(112deg, rgba(203,238,253,.1), transparent 24%, transparent 72%, rgba(71,163,202,.035)); }
.widget-header {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: .55rem .7rem;
padding: .15rem .25rem .05rem;
}
.identity { min-width: 0; display: flex; align-items: center; gap: .7rem; }
.brand-icon {
display: grid;
place-items: center;
width: 2.9rem;
height: 2.9rem;
flex: 0 0 auto;
border: 1px solid rgba(255,255,255,.82);
border-radius: 1rem;
color: #147bd5;
background:
radial-gradient(circle at 25% 2%, rgba(255,255,255,.62), transparent 43%),
linear-gradient(145deg, rgba(217,242,255,.58), rgba(73,159,222,.2));
box-shadow: 0 8px 19px rgba(19,101,160,.13), inset 0 1px 0 rgba(255,255,255,.88);
}
.brand-icon svg { width: 1.75rem; height: 1.75rem; filter: drop-shadow(0 0 5px rgba(20,123,213,.18)); }
.identity-copy { min-width: 0; display: block; }
.title-row { display: flex; align-items: center; gap: .55rem; min-width: 0; }
.identity h1 { margin: 0; font-size: 1.62rem; line-height: 1; letter-spacing: -.045em; white-space: nowrap; }
.identity-copy > small { display: block; margin-top: .28rem; color: var(--widget-muted); font-size: .7rem; }
.widget .pill { min-height: 1.75rem; padding: .27rem .58rem; border-color: rgba(255,255,255,.56); font-size: .59rem; box-shadow: inset 0 1px 0 rgba(255,255,255,.62), 0 5px 14px rgba(26,75,108,.08); backdrop-filter: blur(12px); }
.widget .pill::before { width: .36rem; height: .36rem; box-shadow: 0 0 7px currentColor; }
.theme-button,
.open-section {
display: grid;
place-items: center;
border: 1px solid var(--tile-edge);
color: var(--widget-ink);
background: linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
cursor: pointer;
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
transition: transform .15s ease, filter .15s ease;
}
.theme-button { width: 2.55rem; height: 2.55rem; border-radius: .9rem; }
.theme-button svg { width: 1.18rem; height: 1.18rem; }
.theme-button:hover, .open-section:hover { transform: translateY(-1px); filter: brightness(1.07); }
.theme-button:active, .open-section:active { transform: scale(.97); }
.status-row { grid-column: 1 / -1; display: flex; align-items: center; gap: .55rem; min-width: 0; }
.mode-detail { min-width: 0; color: var(--widget-muted); font-size: .66rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.widget-tile {
position: relative;
isolation: isolate;
overflow: hidden;
border: 1px solid var(--tile-edge);
outline: 1px solid var(--tile-edge-soft);
outline-offset: -3px;
border-radius: 1.15rem;
background:
linear-gradient(132deg, rgba(244,248,250,.22), rgba(159,178,188,.055) 38%, transparent 66%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
backdrop-filter: blur(14px) saturate(116%);
-webkit-backdrop-filter: blur(14px) saturate(116%);
}
.widget-tile::before {
content: "";
position: absolute;
inset: 0;
z-index: 0;
border-radius: inherit;
pointer-events: none;
opacity: .62;
background: linear-gradient(115deg, rgba(255,255,255,.35), transparent 25%, transparent 72%, rgba(255,255,255,.08));
}
.widget-tile > * { position: relative; z-index: 1; }
:root[data-theme="dark"] .widget-tile { background: linear-gradient(132deg, rgba(213,240,252,.075), rgba(255,255,255,.012) 38%, transparent 65%), linear-gradient(145deg, var(--tile-strong), var(--tile)); backdrop-filter: blur(16px) saturate(127%); -webkit-backdrop-filter: blur(16px) saturate(127%); }
.control-card { min-height: 11.4rem; padding: .9rem 1rem .85rem; display: flex; flex-direction: column; }
.control-card::after,
.switch-card::after {
content: "";
position: absolute;
z-index: 0;
width: 12rem;
height: 12rem;
right: -5rem;
bottom: -7rem;
border-radius: 50%;
pointer-events: none;
filter: blur(42px);
opacity: .18;
}
.speed-card::after { background: var(--blue-halo); }
.temperature-card::after { width: 17rem; background: linear-gradient(90deg, var(--blue-halo), var(--orange-halo)); }
.power-card::after, .heater-card::after { background: var(--green-halo); opacity: .16; }
.card-title { display: flex; align-items: flex-start; gap: .65rem; }
.card-title h2, .switch-title h2, .section-title h2 { margin: 0; font-size: .96rem; line-height: 1.2; letter-spacing: -.015em; }
.card-title p { margin: .16rem 0 0; color: var(--widget-muted); font-size: .66rem; }
.ui-icon { display: block; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.feature-icon { width: 1.95rem; height: 1.95rem; flex: 0 0 auto; padding: .06rem; color: #1389f4; filter: drop-shadow(0 0 5px rgba(20,139,244,.2)); }
.hero-control { display: grid; grid-template-columns: 3.45rem 1fr 3.45rem; align-items: center; gap: .8rem; margin: 1rem 0 .72rem; }
.hero-value { text-align: center; font-size: 3rem; line-height: 1; letter-spacing: -.065em; font-variant-numeric: tabular-nums; }
.hero-step {
display: grid;
place-items: center;
width: 3.45rem;
height: 3.45rem;
padding: 0;
border: 1.5px solid rgba(255,255,255,.84);
border-radius: .95rem;
color: #176dbb;
background:
radial-gradient(circle at 24% 5%, rgba(255,255,255,.48), transparent 40%),
linear-gradient(145deg, rgba(245,252,255,.4), rgba(191,224,244,.18));
box-shadow: 0 8px 19px rgba(35,92,132,.13), inset 0 1px 0 rgba(255,255,255,.88), 0 0 0 1px rgba(185,226,248,.2);
cursor: pointer;
font-size: 1.8rem;
line-height: 1;
transition: transform .15s ease, filter .15s ease, box-shadow .15s ease;
}
.hero-step.primary {
color: white;
background:
radial-gradient(circle at 24% 5%, rgba(255,255,255,.55), transparent 38%),
linear-gradient(135deg, rgba(255,255,255,.16), transparent 42%, rgba(0,73,170,.1)),
linear-gradient(145deg, #55b4ff, #1479e8 72%);
box-shadow: 0 8px 18px rgba(15,92,183,.18), 0 0 7px rgba(48,151,239,.1), inset 0 1px 0 rgba(255,255,255,.86), inset 0 -3px 7px rgba(0,67,156,.16);
}
.hero-step:hover { transform: translateY(-1px); filter: brightness(1.07); box-shadow: 0 10px 21px rgba(20,101,190,.2), 0 0 9px rgba(48,151,239,.12), inset 0 1px 0 rgba(255,255,255,.88); }
.hero-step:active { transform: scale(.97); }
.speed-segments { display: grid; grid-template-columns: repeat(6, 1fr); gap: .18rem; }
.speed-segments button {
height: .9rem;
padding: 0;
border: 1px solid rgba(255,255,255,.82);
border-radius: .5rem;
background: linear-gradient(180deg, rgba(173,207,229,.3), rgba(98,151,190,.18));
box-shadow: inset 0 1px 2px rgba(27,70,105,.07), 0 2px 5px rgba(32,86,126,.07);
cursor: pointer;
transition: background .12s ease, box-shadow .12s ease, transform .12s ease;
}
.speed-segments button:hover { transform: translateY(-1px); }
.speed-segments button.active {
background: linear-gradient(180deg, rgba(255,255,255,.32), transparent 48%), linear-gradient(90deg, #1685ec, #35afff);
box-shadow: 0 0 5px rgba(25,143,247,.19), inset 0 1px 0 rgba(255,255,255,.75), inset 0 -2px 4px rgba(0,84,182,.13);
}
.scale-labels, .temperature-labels { display: flex; justify-content: space-between; margin-top: .34rem; padding: 0 .3rem; color: var(--widget-muted); font-size: .62rem; }
.temperature-range { width: 100%; height: 1.45rem; margin: 0; appearance: none; background: transparent; cursor: pointer; }
.temperature-range::-webkit-slider-runnable-track { height: .68rem; border: 1px solid rgba(255,255,255,.88); border-radius: 999px; background: linear-gradient(90deg, #0878ed, #53c7f5 38%, #f3c26e 72%, #ff6b31); box-shadow: 0 0 8px rgba(37,153,239,.15), 0 0 7px rgba(255,114,41,.09), inset 0 1px 2px rgba(255,255,255,.46); }
.temperature-range::-moz-range-track { height: .68rem; border: 1px solid rgba(255,255,255,.88); border-radius: 999px; background: linear-gradient(90deg, #0878ed, #53c7f5 38%, #f3c26e 72%, #ff6b31); }
.temperature-range::-moz-range-progress { background: transparent; }
.temperature-range::-webkit-slider-thumb { width: 1.6rem; height: 1.6rem; margin-top: -.49rem; appearance: none; border: .25rem solid rgba(244,252,255,.9); border-radius: 50%; background: #238feb; box-shadow: 0 0 0 2px rgba(255,255,255,.45), 0 0 11px rgba(29,139,241,.31), 0 4px 9px rgba(17,79,143,.22); }
.temperature-range::-moz-range-thumb { width: 1.08rem; height: 1.08rem; border: .25rem solid rgba(244,252,255,.9); border-radius: 50%; background: #238feb; box-shadow: 0 0 0 2px rgba(255,255,255,.45), 0 0 11px rgba(29,139,241,.31), 0 4px 9px rgba(17,79,143,.22); }
.switch-grid { display: grid; grid-template-columns: 1fr 1fr; gap: .65rem; }
.switch-card { min-width: 0; min-height: 8.15rem; padding: .82rem; display: flex; flex-direction: column; gap: .72rem; }
.switch-title { display: flex; align-items: center; gap: .5rem; min-width: 0; }
.switch-title > span { min-width: 0; }
.switch-title small { display: block; margin-top: .12rem; color: var(--widget-muted); font-size: .58rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.switch-icon { width: 1.75rem; height: 1.75rem; flex: 0 0 auto; }
.switch-icon.green { color: #08a95a; filter: drop-shadow(0 0 5px rgba(20,190,104,.23)); }
.switch-icon.orange { color: #f06419; filter: drop-shadow(0 0 5px rgba(244,105,31,.2)); }
.glass-switch {
position: relative;
overflow: hidden;
width: 100%;
min-height: 3.35rem;
margin-top: auto;
border: 1.5px solid rgba(255,255,255,.86);
border-radius: .95rem;
color: var(--widget-ink);
background: rgba(199,222,235,.24);
box-shadow: var(--tile-shadow);
cursor: pointer;
font-size: 1.25rem;
font-weight: 850;
text-shadow: 0 1px 0 rgba(255,255,255,.3);
transition: transform .15s ease, background .2s ease, box-shadow .2s ease, filter .2s ease;
}
.glass-switch:hover { transform: translateY(-1px); filter: brightness(1.06); }
.glass-switch:active { transform: scale(.98); }
.glass-switch[aria-pressed="true"].green,
.glass-switch[aria-pressed="true"].orange {
background:
radial-gradient(circle at 25% -8%, rgba(255,255,255,.67), transparent 42%),
linear-gradient(132deg, rgba(255,255,255,.15), transparent 40%, rgba(0,125,62,.06)),
linear-gradient(145deg, rgba(139,244,190,.67), rgba(55,194,122,.43));
border-color: rgba(218,255,235,.84);
box-shadow: 0 8px 19px rgba(18,143,80,.14), 0 0 8px rgba(38,199,116,.09), inset 0 1px 0 rgba(255,255,255,.9), inset 0 -4px 9px rgba(0,114,57,.08);
}
.info-card { padding: .82rem; }
.section-title { display: flex; align-items: center; justify-content: space-between; gap: .65rem; }
.section-title > span { display: flex; align-items: center; gap: .5rem; }
.section-icon { width: 1.75rem; height: 1.75rem; color: #207bcc; filter: drop-shadow(0 0 5px rgba(26,124,210,.17)); }
.section-icon.leaf { color: #069c51; transform: rotate(-18deg); filter: drop-shadow(0 0 5px rgba(8,160,81,.2)); }
.open-section { width: 2rem; height: 2rem; padding: 0; border-radius: .7rem; color: #147bd5; font-size: .96rem; }
.co2-summary { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: .6rem; margin: .8rem .1rem .52rem; }
.co2-label { color: var(--widget-muted); font-size: .74rem; font-weight: 750; }
.co2-summary strong { text-align: center; font-size: 2rem; line-height: 1; letter-spacing: -.045em; }
.co2-summary strong small { color: var(--widget-muted); font-size: .62rem; font-weight: 650; letter-spacing: 0; }
.quality-chip { display: inline-flex; justify-content: center; padding: .32rem .62rem; border: 1px solid var(--tile-edge-soft); border-radius: 999px; background: rgba(199,222,235,.2); color: var(--widget-muted); font-size: .6rem; font-weight: 750; white-space: nowrap; }
.quality-chip.good { color: #076d3d; border-color: rgba(109,237,167,.65); background: linear-gradient(145deg, rgba(179,255,214,.58), rgba(92,218,151,.39)); box-shadow: 0 0 9px rgba(33,203,116,.12), inset 0 1px 0 rgba(255,255,255,.82); }
.quality-chip.warn { color: #9c5513; border-color: rgba(244,183,106,.67); background: linear-gradient(145deg, rgba(255,232,188,.56), rgba(239,168,80,.34)); }
.quality-chip.bad { color: #a62f3d; border-color: rgba(242,135,147,.62); background: linear-gradient(145deg, rgba(255,209,216,.53), rgba(225,105,120,.3)); }
:root[data-theme="dark"] .quality-chip.good { color: #b9ffda; }
:root[data-theme="dark"] .quality-chip.warn { color: #ffd59e; }
:root[data-theme="dark"] .quality-chip.bad { color: #ffc0c8; }
.air-card {
--air-color: #7896ac;
--air-glow: rgba(93, 140, 171, .2);
--air-track: rgba(181, 203, 200, .28);
}
.air-card[data-air-tone="good"] {
--air-color: #1fbd69;
--air-glow: rgba(18, 199, 104, .34);
}
.air-card[data-air-tone="warn"] {
--air-color: #efa12b;
--air-glow: rgba(244, 161, 42, .35);
}
.air-card[data-air-tone="bad"] {
--air-color: #e8495c;
--air-glow: rgba(235, 74, 83, .36);
}
.co2-meter { height: .72rem; border: 1px solid rgba(255,255,255,.82); border-radius: 999px; background-color: var(--air-track); background-image: linear-gradient(180deg, rgba(255,255,255,.15), transparent 52%, rgba(0,20,36,.045)); box-shadow: inset 0 1px 3px rgba(20,61,78,.14), 0 1px 4px rgba(8,43,72,.07); overflow: hidden; transition: background-color .65s ease; }
.co2-meter i { display: block; width: 0; height: 100%; border-radius: inherit; background-color: var(--air-color); background-image: linear-gradient(180deg, rgba(255,255,255,.28), rgba(255,255,255,.045) 48%, rgba(0,35,20,.1)); box-shadow: 0 0 8px var(--air-glow), inset 0 1px 0 rgba(255,255,255,.58), inset 0 -1px 2px rgba(0,34,19,.1); transition: width .35s ease, background-color .65s ease, box-shadow .65s ease; }
.meter-labels { display: flex; justify-content: space-between; margin-top: .27rem; padding: 0 .2rem; color: rgba(22,69,108,.78); font-size: .58rem; font-weight: 650; text-shadow: 0 1px 0 rgba(255,255,255,.48); }
:root[data-theme="dark"] .meter-labels { color: rgba(211,235,248,.76); text-shadow: 0 1px 2px rgba(0,0,0,.58); }
.mini-metrics { display: grid; grid-template-columns: 1fr 1fr; gap: .52rem; margin-top: .68rem; }
.mini-metric { min-width: 0; min-height: 4.35rem; display: flex; align-items: center; justify-content: center; gap: .5rem; padding: .62rem .5rem; border: 1px solid var(--tile-edge-soft); border-radius: .9rem; background: linear-gradient(145deg, rgba(255,255,255,.13), rgba(107,151,177,.055)); box-shadow: inset 0 1px 0 rgba(255,255,255,.33); text-align: center; }
.metric-icon { width: 1.55rem; height: 1.55rem; flex: 0 0 auto; color: #137edc; filter: drop-shadow(0 0 4px rgba(20,124,221,.15)); }
.mini-metric span { min-width: 0; }
.mini-metric small { display: block; color: var(--widget-muted); font-size: .58rem; }
.mini-metric strong { display: block; margin-top: .2rem; font-size: 1.35rem; line-height: 1; letter-spacing: -.035em; }
.schedule-times { display: grid; grid-template-columns: 1fr 1px 1fr; align-items: center; gap: .7rem; margin-top: .75rem; padding: .15rem .25rem .25rem; }
.schedule-times > span { display: grid; justify-items: center; gap: .18rem; text-align: center; }
.schedule-times small { color: var(--widget-muted); font-size: .6rem; }
.schedule-times strong { font-size: 1.35rem; letter-spacing: -.035em; }
.schedule-times > i { width: 1px; height: 2.75rem; background: var(--tile-edge-soft); }
.open-panel {
min-height: 3.25rem;
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: .65rem;
padding: .65rem .9rem;
border: 1px solid rgba(194,232,255,.84);
border-radius: 1rem;
color: white;
background:
radial-gradient(circle at 18% -35%, rgba(255,255,255,.52), transparent 47%),
linear-gradient(135deg, rgba(255,255,255,.13), transparent 43%),
linear-gradient(145deg, rgba(60,174,239,.92), rgba(17,113,194,.88));
box-shadow: 0 9px 20px rgba(15,92,183,.2), 0 0 9px rgba(48,151,239,.11), inset 0 1px 0 rgba(255,255,255,.84), inset 0 -3px 7px rgba(0,67,156,.15);
cursor: pointer;
font-size: .78rem;
font-weight: 760;
transition: transform .15s ease, filter .15s ease, box-shadow .15s ease;
}
.open-panel svg { width: 1.45rem; height: 1.45rem; }
.open-panel b { font-size: 1rem; }
.open-panel:hover { transform: translateY(-1px); filter: brightness(1.05); box-shadow: 0 11px 23px rgba(20,101,190,.23), 0 0 11px rgba(48,151,239,.13), inset 0 1px 0 rgba(255,255,255,.86); }
.open-panel:active { transform: scale(.99); }
.demo-note { color: var(--widget-muted); text-align: center; font-size: .58rem; }
:root[data-theme="dark"] .brand-icon { border-color: rgba(193,228,245,.25); background: radial-gradient(circle at 25% 2%, rgba(208,243,255,.16), transparent 43%), linear-gradient(145deg, rgba(38,125,187,.27), rgba(15,61,91,.26)); }
:root[data-theme="dark"] .hero-step { color: #76c7fa; border-color: rgba(192,226,244,.25); background: radial-gradient(circle at 24% 5%, rgba(213,240,252,.11), transparent 40%), linear-gradient(145deg, rgba(77,112,133,.23), rgba(20,44,59,.28)); box-shadow: 0 9px 21px rgba(0,0,0,.23), inset 0 1px 0 rgba(226,246,255,.12); }
:root[data-theme="dark"] .hero-step.primary { color: white; background: radial-gradient(circle at 24% 5%, rgba(214,246,255,.32), transparent 38%), linear-gradient(135deg, rgba(255,255,255,.08), transparent 42%, rgba(0,32,95,.17)), linear-gradient(145deg, #33aaf4, #0869d0 74%); box-shadow: 0 10px 24px rgba(0,53,119,.38), 0 0 11px rgba(41,162,244,.19), inset 0 1px 0 rgba(220,248,255,.4), inset 0 -3px 7px rgba(0,27,91,.27); }
:root[data-theme="dark"] .speed-segments button { border-color: rgba(192,226,244,.25); background: linear-gradient(180deg, rgba(91,136,162,.23), rgba(24,55,74,.28)); }
:root[data-theme="dark"] .speed-segments button.active { border-color: rgba(117,207,255,.48); background: linear-gradient(180deg, rgba(216,246,255,.19), transparent 48%), linear-gradient(90deg, #0877df, #20b7ff); box-shadow: 0 0 7px rgba(24,156,255,.27), inset 0 1px 0 rgba(223,248,255,.34); }
:root[data-theme="dark"] .glass-switch { color: #ddecf4; border-color: rgba(193,228,245,.25); background: linear-gradient(145deg, rgba(77,112,133,.23), rgba(20,44,59,.28)); text-shadow: 0 1px 2px rgba(0,0,0,.4); }
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].green,
:root[data-theme="dark"] .glass-switch[aria-pressed="true"].orange { color: #effff6; border-color: rgba(127,242,182,.4); background: radial-gradient(circle at 25% -8%, rgba(218,255,236,.3), transparent 42%), linear-gradient(132deg, rgba(255,255,255,.07), transparent 40%, rgba(0,45,23,.12)), linear-gradient(145deg, rgba(51,190,119,.52), rgba(9,102,59,.49)); box-shadow: 0 9px 21px rgba(0,0,0,.22), 0 0 9px rgba(37,207,121,.1), inset 0 1px 0 rgba(218,255,236,.32), inset 0 -3px 8px rgba(0,31,16,.16); }
:root[data-theme="dark"] .air-card { --air-track: rgba(8,28,39,.38); }
:root[data-theme="dark"] .air-card[data-air-tone="good"] { --air-glow: rgba(30, 224, 128, .3); }
:root[data-theme="dark"] .air-card[data-air-tone="warn"] { --air-glow: rgba(255, 176, 49, .3); }
:root[data-theme="dark"] .air-card[data-air-tone="bad"] { --air-glow: rgba(255, 82, 102, .32); }
:root[data-theme="dark"] .co2-meter { border-color: rgba(205,235,248,.3); box-shadow: inset 0 1px 4px rgba(0,0,0,.27), 0 1px 5px rgba(0,0,0,.12); }
:root[data-theme="dark"] .mini-metric { background: linear-gradient(145deg, rgba(196,231,247,.055), rgba(3,24,37,.08)); box-shadow: inset 0 1px 0 rgba(224,246,255,.07); }
/* Wide monitor layout. The same markup stays vertical on narrow screens, so
controls and API behaviour cannot drift between two widget versions. */
:root[data-widget-layout="horizontal"] body {
padding: .36rem;
}
:root[data-widget-layout="horizontal"] .widget {
width: min(100%, 76rem);
max-width: none;
gap: .48rem;
padding: .58rem;
border-radius: 1.35rem;
grid-template-columns: minmax(0, 1.4fr) minmax(0, 1.4fr) minmax(0, .8fr) minmax(0, .8fr);
grid-template-areas:
"header header header header"
"speed temperature power heater"
"air air schedule schedule"
"open open open open"
"demo demo demo demo";
align-items: stretch;
}
:root[data-widget-layout="horizontal"] .widget-header {
grid-area: header;
min-height: 2.6rem;
grid-template-columns: minmax(0, 1fr) auto auto;
gap: .35rem .55rem;
padding: 0 .12rem;
}
:root[data-widget-layout="horizontal"] .widget-header .identity { grid-column: 1; grid-row: 1; }
:root[data-widget-layout="horizontal"] .widget-header .status-row { grid-column: 2; grid-row: 1; }
:root[data-widget-layout="horizontal"] .widget-header .theme-button { grid-column: 3; grid-row: 1; }
:root[data-widget-layout="horizontal"] .identity { gap: .55rem; }
:root[data-widget-layout="horizontal"] .brand-icon { width: 2.45rem; height: 2.45rem; border-radius: .82rem; }
:root[data-widget-layout="horizontal"] .brand-icon svg { width: 1.48rem; height: 1.48rem; }
:root[data-widget-layout="horizontal"] .identity h1 { font-size: 1.42rem; }
:root[data-widget-layout="horizontal"] .identity-copy > small { margin-top: .18rem; font-size: .61rem; }
:root[data-widget-layout="horizontal"] .title-row { gap: .42rem; }
:root[data-widget-layout="horizontal"] .widget .pill { min-height: 1.52rem; padding: .2rem .5rem; font-size: .54rem; }
:root[data-widget-layout="horizontal"] .mode-detail { font-size: .59rem; }
:root[data-widget-layout="horizontal"] .theme-button { width: 2.2rem; height: 2.2rem; border-radius: .75rem; }
:root[data-widget-layout="horizontal"] .speed-card { grid-area: speed; }
:root[data-widget-layout="horizontal"] .temperature-card { grid-area: temperature; }
:root[data-widget-layout="horizontal"] .control-card {
min-height: 8.75rem;
padding: .66rem .78rem .58rem;
}
:root[data-widget-layout="horizontal"] .card-title { gap: .5rem; }
:root[data-widget-layout="horizontal"] .card-title h2,
:root[data-widget-layout="horizontal"] .switch-title h2,
:root[data-widget-layout="horizontal"] .section-title h2 { font-size: .86rem; }
:root[data-widget-layout="horizontal"] .card-title p { margin-top: .1rem; font-size: .58rem; }
:root[data-widget-layout="horizontal"] .feature-icon { width: 1.65rem; height: 1.65rem; }
:root[data-widget-layout="horizontal"] .hero-control {
grid-template-columns: 2.75rem 1fr 2.75rem;
gap: .55rem;
margin: .46rem 0 .34rem;
}
:root[data-widget-layout="horizontal"] .hero-step { width: 2.75rem; height: 2.75rem; border-radius: .78rem; font-size: 1.5rem; }
:root[data-widget-layout="horizontal"] .hero-value { font-size: 2.4rem; }
:root[data-widget-layout="horizontal"] .speed-segments button { height: .68rem; }
:root[data-widget-layout="horizontal"] .scale-labels,
:root[data-widget-layout="horizontal"] .temperature-labels { margin-top: .2rem; font-size: .52rem; }
:root[data-widget-layout="horizontal"] .temperature-range { height: 1.05rem; }
:root[data-widget-layout="horizontal"] .temperature-range::-webkit-slider-runnable-track { height: .55rem; }
:root[data-widget-layout="horizontal"] .temperature-range::-moz-range-track { height: .55rem; }
:root[data-widget-layout="horizontal"] .temperature-range::-webkit-slider-thumb { width: 1.32rem; height: 1.32rem; margin-top: -.4rem; border-width: .21rem; }
:root[data-widget-layout="horizontal"] .temperature-range::-moz-range-thumb { width: .9rem; height: .9rem; border-width: .21rem; }
:root[data-widget-layout="horizontal"] .switch-grid { display: contents; }
:root[data-widget-layout="horizontal"] .switch-grid > * { z-index: 1; }
:root[data-widget-layout="horizontal"] .power-card { grid-area: power; }
:root[data-widget-layout="horizontal"] .heater-card { grid-area: heater; }
:root[data-widget-layout="horizontal"] .switch-card {
min-height: 8.75rem;
gap: .45rem;
padding: .66rem .68rem .58rem;
}
:root[data-widget-layout="horizontal"] .switch-title { gap: .4rem; }
:root[data-widget-layout="horizontal"] .switch-title small { font-size: .52rem; }
:root[data-widget-layout="horizontal"] .switch-icon { width: 1.5rem; height: 1.5rem; }
:root[data-widget-layout="horizontal"] .glass-switch { min-height: 2.7rem; border-radius: .78rem; font-size: 1.05rem; }
:root[data-widget-layout="horizontal"] .info-card { padding: .62rem .68rem; }
:root[data-widget-layout="horizontal"] .section-icon { width: 1.5rem; height: 1.5rem; }
:root[data-widget-layout="horizontal"] .open-section { width: 1.75rem; height: 1.75rem; border-radius: .58rem; font-size: .82rem; }
:root[data-widget-layout="horizontal"] .air-card {
grid-area: air;
display: grid;
grid-template-columns: minmax(0, 1.55fr) minmax(10.8rem, .82fr);
grid-template-rows: auto auto auto auto;
column-gap: .72rem;
align-content: start;
}
:root[data-widget-layout="horizontal"] .air-card .section-title { grid-column: 1 / -1; grid-row: 1; }
:root[data-widget-layout="horizontal"] .air-card .co2-summary {
grid-column: 1;
grid-row: 2;
margin: .42rem .05rem .3rem;
}
:root[data-widget-layout="horizontal"] .air-card .co2-meter { grid-column: 1; grid-row: 3; }
:root[data-widget-layout="horizontal"] .air-card .meter-labels { grid-column: 1; grid-row: 4; }
:root[data-widget-layout="horizontal"] .air-card .mini-metrics {
grid-column: 2;
grid-row: 2 / 5;
align-self: stretch;
gap: .38rem;
margin-top: .4rem;
}
:root[data-widget-layout="horizontal"] .air-card .mini-metric {
min-height: 0;
flex-direction: column;
gap: .14rem;
padding: .35rem .25rem;
border-radius: .72rem;
}
:root[data-widget-layout="horizontal"] .air-card .metric-icon { width: 1.25rem; height: 1.25rem; }
:root[data-widget-layout="horizontal"] .air-card .mini-metric small { font-size: .51rem; }
:root[data-widget-layout="horizontal"] .air-card .mini-metric strong { margin-top: .1rem; font-size: 1.08rem; }
:root[data-widget-layout="horizontal"] .air-card .co2-summary strong { font-size: 1.65rem; }
:root[data-widget-layout="horizontal"] .air-card .quality-chip { padding: .25rem .48rem; font-size: .54rem; }
:root[data-widget-layout="horizontal"] .co2-meter { height: .62rem; }
:root[data-widget-layout="horizontal"] .schedule-card { grid-area: schedule; }
:root[data-widget-layout="horizontal"] .air-card,
:root[data-widget-layout="horizontal"] .schedule-card { min-height: 6.9rem; }
:root[data-widget-layout="horizontal"] .schedule-times {
gap: .5rem;
margin-top: .42rem;
padding: .08rem .18rem .12rem;
}
:root[data-widget-layout="horizontal"] .schedule-times small { font-size: .53rem; }
:root[data-widget-layout="horizontal"] .schedule-times strong { font-size: 1.18rem; }
:root[data-widget-layout="horizontal"] .schedule-times > i { height: 2.2rem; }
:root[data-widget-layout="horizontal"] .open-panel {
grid-area: open;
min-height: 2.45rem;
gap: .5rem;
padding: .38rem .75rem;
border-radius: .82rem;
font-size: .68rem;
}
:root[data-widget-layout="horizontal"] .open-panel svg { width: 1.15rem; height: 1.15rem; }
:root[data-widget-layout="horizontal"] .open-panel b { font-size: .85rem; }
:root[data-widget-layout="horizontal"] .demo-note { grid-area: demo; }
button:disabled { opacity: .58; cursor: default; transform: none !important; }
@media (min-width: 560px) and (min-height: 900px) {
html { font-size: 17px; }
:root[data-widget-layout="vertical"] .widget { width: min(100%, 33rem); }
}
@media (max-width: 380px) {
body { padding: .36rem; }
.widget { padding: .55rem; gap: .52rem; border-radius: 1.2rem; }
.brand-icon { width: 2.55rem; height: 2.55rem; }
.identity h1 { font-size: 1.38rem; }
.title-row { gap: .38rem; }
.widget .pill { padding-inline: .46rem; font-size: .54rem; }
.hero-control { grid-template-columns: 3.15rem 1fr 3.15rem; gap: .55rem; }
.hero-step { width: 3.15rem; height: 3.15rem; }
.hero-value { font-size: 2.65rem; }
.switch-grid { gap: .5rem; }
.switch-card { padding: .7rem; }
.switch-title { align-items: flex-start; }
.switch-title small { display: none; }
.co2-summary { grid-template-columns: auto 1fr; }
.co2-summary .quality-chip { grid-column: 1 / -1; justify-self: center; }
}
@media (prefers-reduced-motion: reduce) {
.hero-step:hover, .theme-button:hover, .open-section:hover, .glass-switch:hover, .open-panel:hover { transform: none; }
}
+1 -3
View File
@@ -1,6 +1,4 @@
/* Elica-specific layout only. /* Elica widget extends the exact Tion widget aeroglass material and background. */
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)); } .hood-icon svg { width: 1.75rem; height: 1.75rem; filter: drop-shadow(0 0 5px rgba(20,123,213,.18)); }
+4 -4
View File
@@ -5,9 +5,9 @@
<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>Elica — виджет</title> <title>Elica — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/widget.css">
<link rel="stylesheet" href="/ui/static/css/elica-widget.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/elica-widget.css">
</head> </head>
<body> <body>
<div class="ambient" aria-hidden="true"></div> <div class="ambient" aria-hidden="true"></div>
@@ -80,6 +80,6 @@
<span>Открыть панель вытяжки</span><b aria-hidden="true">↗</b> <span>Открыть панель вытяжки</span><b aria-hidden="true">↗</b>
</button> </button>
</main> </main>
<script type="module" src="/ui/static/js/elica-widget.js?v=20260927-1"></script> <script type="module" src="/ui/static/js/elica-widget.js"></script>
</body> </body>
</html> </html>
+4 -4
View File
@@ -5,9 +5,9 @@
<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>Elica — управление вытяжкой</title> <title>Elica — управление вытяжкой</title>
<link rel="stylesheet" href="/ui/static/css/base.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/panel.css">
<link rel="stylesheet" href="/ui/static/css/elica.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/elica.css">
</head> </head>
<body> <body>
<div class="ambient" aria-hidden="true"></div> <div class="ambient" aria-hidden="true"></div>
@@ -113,6 +113,6 @@
</section> </section>
</main> </main>
<script type="module" src="/ui/static/js/elica.js?v=20260927-1"></script> <script type="module" src="/ui/static/js/elica.js"></script>
</body> </body>
</html> </html>
+2 -4
View File
@@ -179,9 +179,7 @@ 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) let mode = allowed.includes(explicit) ? explicit : (localStorage.getItem("tion-theme") || "auto");
? 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);
@@ -198,7 +196,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("climate-theme", mode); localStorage.setItem("tion-theme", mode);
apply(); apply();
}); });
+1 -1
View File
@@ -83,7 +83,7 @@ function render(status) {
airCard.style.setProperty("--air-color", airPalette.color); airCard.style.setProperty("--air-color", airPalette.color);
airCard.style.setProperty("--air-glow", airPalette.glow); airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`; $("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setText("#room-temp", numberOrDash(sensor.temperature, 1)); setText("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1));
setText("#humidity", numberOrDash(sensor.humidity)); setText("#humidity", numberOrDash(sensor.humidity));
setText("#current-time", schedule.current_time || tion.device_time || "—"); setText("#current-time", schedule.current_time || tion.device_time || "—");
setText("#next-time", schedule.next_time || "—"); setText("#next-time", schedule.next_time || "—");
+2 -2
View File
@@ -74,7 +74,7 @@ function renderAir(sensor, tion) {
airCard.style.setProperty("--air-glow", airPalette.glow); airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`; $("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad"); setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad");
text("#room-temp", numberOrDash(sensor.temperature, 1)); text("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1));
text("#humidity", numberOrDash(sensor.humidity)); text("#humidity", numberOrDash(sensor.humidity));
text("#pm25", numberOrDash(sensor.pm25)); text("#pm25", numberOrDash(sensor.pm25));
text("#pm10", numberOrDash(sensor.pm10)); text("#pm10", numberOrDash(sensor.pm10));
@@ -122,7 +122,7 @@ function render(status) {
$("#mode-outside").classList.toggle("active", tion.mode === "outside"); $("#mode-outside").classList.toggle("active", tion.mode === "outside");
$("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation"); $("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation");
text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция"); text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция");
text("#outside-temp", numberOrDash(tion.in_temp)); text("#outside-temp", numberOrDash(tion.out_temp));
text("#filter-remain", numberOrDash(tion.filter_remain)); text("#filter-remain", numberOrDash(tion.filter_remain));
const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2)); const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2));
$("#filter-progress").style.width = `${filterPercent}%`; $("#filter-progress").style.width = `${filterPercent}%`;
+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?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/aeroglass-widget.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/widget.css">
</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/tion-widget.js?v=20260927-1"></script> <script type="module" src="/ui/static/js/tion-widget.js"></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?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/aeroglass-panel.css?v=20260927-1"> <link rel="stylesheet" href="/ui/static/css/panel.css">
</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/tion.js?v=2"></script> <script type="module" src="/ui/static/js/tion.js"></script>
</body> </body>
</html> </html>