1 Commits
39 changed files with 30 additions and 4864 deletions
+1 -2
View File
@@ -3,10 +3,9 @@
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.venv" /> <excludeFolder url="file://$MODULE_DIR$/.venv" />
</content> </content>
<orderEntry type="jdk" jdkName="Python 3.14 (ClimatController)" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Python 3.14 (TionController)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
</module> </module>
+1 -1
View File
@@ -2,7 +2,7 @@
<project version="4"> <project version="4">
<component name="ProjectModuleManager"> <component name="ProjectModuleManager">
<modules> <modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ClimatController.iml" filepath="$PROJECT_DIR$/.idea/ClimatController.iml" /> <module fileurl="file://$PROJECT_DIR$/.idea/TionController.iml" filepath="$PROJECT_DIR$/.idea/TionController.iml" />
</modules> </modules>
</component> </component>
</project> </project>
-8
View File
@@ -1,8 +0,0 @@
[version]
major = 1
minor = 4
patch = 0
[build]
date = "2026-09-26"
time = "23:54:18"
+1 -256
View File
@@ -1,24 +1,17 @@
import logging import logging
import shutil
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from typing import Literal, Annotated from typing import Literal, Annotated
import yaml
from fastapi import FastAPI, Request, HTTPException, Path from fastapi import FastAPI, Request, HTTPException, Path
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from pathlib import Path as FilePath from pathlib import Path as FilePath
from app.qingping.service import QingpingService from app.qingping.service import QingpingService
from app.metrics import PrometheusMetricsService
from app.elica import ElicaConfig, ElicaController, ElicaService
from app.my_dataclasses import ( from app.my_dataclasses import (
TION_MAC, TION_MAC,
QINGPING_MAC, QINGPING_MAC,
QINGPING_MQTT_HOST, QINGPING_MQTT_HOST,
QINGPING_MQTT_PORT, QINGPING_MQTT_PORT,
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
MIN_FAN_SPEED, MIN_FAN_SPEED,
MAX_FAN_SPEED, MAX_FAN_SPEED,
MIN_TARGET_TEMP, MIN_TARGET_TEMP,
@@ -90,22 +83,12 @@ qingping_service = QingpingService(
mac=QINGPING_MAC, mac=QINGPING_MAC,
) )
elica_service = ElicaService(
ElicaConfig(
mqtt_host=ELICA_MQTT_HOST,
mqtt_port=ELICA_MQTT_PORT,
)
)
elica_controller = ElicaController(elica_service)
schedule_service: ScheduleService | None = None schedule_service: ScheduleService | None = None
schedule_load_error: str | None = None schedule_load_error: str | None = None
auto_controller: AutoController | None = None auto_controller: AutoController | None = None
auto_load_error: str | None = None auto_load_error: str | None = None
metrics_service: PrometheusMetricsService | None = None
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Application lifecycle # Application lifecycle
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@@ -116,11 +99,9 @@ async def lifespan(app: FastAPI):
global schedule_load_error global schedule_load_error
global auto_controller global auto_controller
global auto_load_error global auto_load_error
global metrics_service
await service.start() await service.start()
await qingping_service.start() await qingping_service.start()
await elica_service.start()
try: try:
try: try:
@@ -183,36 +164,12 @@ async def lifespan(app: FastAPI):
except Exception as exc: except Exception as exc:
schedule_service = None schedule_service = None
schedule_load_error = f"{type(exc).__name__}: {exc}" schedule_load_error = f"{type(exc).__name__}: {exc}"
try:
metrics_service = PrometheusMetricsService(
tion_service=service,
qingping_service=qingping_service,
schedule_service=schedule_service,
auto_controller=auto_controller,
output_path=(
"/var/lib/prometheus/"
"node-exporter/"
"climatcontroller.prom"
),
interval=5.0,
)
await metrics_service.start()
except Exception:
logging.getLogger(__name__).exception("Could not start Prometheus metrics service")
metrics_service = None
yield yield
finally: finally:
if metrics_service is not None:
await metrics_service.stop()
if schedule_service is not None: if schedule_service is not None:
await schedule_service.stop() await schedule_service.stop()
await elica_service.stop()
await qingping_service.stop() await qingping_service.stop()
await service.stop() await service.stop()
@@ -227,67 +184,6 @@ app = FastAPI(
lifespan=lifespan, lifespan=lifespan,
) )
WEB_ROOT = FilePath(__file__).resolve().parents[1] / "web"
app.mount(
"/ui/static",
StaticFiles(directory=WEB_ROOT),
name="ui-static",
)
@app.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/ui/tion")
@app.get("/ui", include_in_schema=False)
async def ui_root():
return RedirectResponse(url="/ui/tion")
# Canonical UI routes. Device-specific names make room for additional
# controllers/widgets without overloading generic "panel"/"widget" names.
@app.get("/ui/tion", include_in_schema=False)
async def ui_tion():
return FileResponse(WEB_ROOT / "tion.html")
@app.get("/ui/tion-widget", include_in_schema=False)
async def ui_tion_widget():
return FileResponse(WEB_ROOT / "tion-widget.html")
@app.get("/ui/elica", include_in_schema=False)
async def ui_elica():
return FileResponse(WEB_ROOT / "elica.html")
@app.get("/ui/elica-widget", include_in_schema=False)
async def ui_elica_widget():
return FileResponse(WEB_ROOT / "elica-widget.html")
# Backward-compatible aliases for existing bookmarks/Homarr embeds.
@app.get("/ui/panel", include_in_schema=False)
async def ui_panel_legacy():
return RedirectResponse(url="/ui/tion")
@app.get("/ui/widget", include_in_schema=False)
async def ui_widget_legacy():
return RedirectResponse(url="/ui/tion-widget")
@app.get("/ui/exhaust", include_in_schema=False)
async def ui_exhaust_legacy():
return RedirectResponse(url="/ui/elica")
@app.get("/ui/exhaust-widget", include_in_schema=False)
async def ui_exhaust_widget_legacy():
return RedirectResponse(url="/ui/elica-widget")
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
async def validation_exception_handler( async def validation_exception_handler(
@@ -337,31 +233,9 @@ def get_status() -> dict:
"qingping": qingping_service.status(), "qingping": qingping_service.status(),
"elica": get_elica_status(),
"schedule": get_schedule_status(), "schedule": get_schedule_status(),
} }
def get_elica_status() -> dict:
"""Текущее состояние ESP32, вытяжки Elica и внешнего вентилятора."""
return elica_service.status()
async def execute_elica_command(operation):
try:
await operation()
except Exception as exc:
raise HTTPException(
status_code=503,
detail={
"message": "Elica unavailable",
"error": f"{type(exc).__name__}: {exc}",
},
) from exc
return get_elica_status()
def get_effective_speed() -> int: def get_effective_speed() -> int:
if ( if (
@@ -599,55 +473,6 @@ async def status():
return get_status() return get_status()
# ----------------------------------------------------------------------
# Elica / exhaust
# ----------------------------------------------------------------------
@app.get("/api/elica/status")
async def elica_status():
return get_elica_status()
@app.post("/api/elica/power/{state}")
async def set_elica_power(state: Literal["on", "off"]):
operation = (
elica_controller.power_on
if state == "on"
else elica_controller.power_off
)
return await execute_elica_command(operation)
@app.post("/api/elica/speed/{speed}")
async def set_elica_speed(
speed: Annotated[int, Path(ge=1, le=4)],
):
return await execute_elica_command(
lambda: elica_controller.set_speed(speed)
)
@app.post("/api/elica/timer/{state}")
async def set_elica_timer(state: Literal["on", "off"]):
enabled = state == "on"
return await execute_elica_command(
lambda: elica_controller.set_timer(enabled)
)
@app.post("/api/elica/light/toggle")
async def toggle_elica_light():
return await execute_elica_command(elica_controller.toggle_light)
@app.post("/api/elica/external-fan/{state}")
async def set_external_fan(state: Literal["on", "off"]):
enabled = state == "on"
return await execute_elica_command(
lambda: elica_controller.set_external_fan(enabled)
)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Power # Power
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@@ -899,86 +724,6 @@ async def set_light(
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Переход в auto # Переход в auto
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
@app.get("/api/schedule/config")
async def get_schedule_config():
try:
raw = yaml.safe_load(
FilePath(SCHEDULE_FILE).read_text(encoding="utf-8")
)
except (OSError, yaml.YAMLError) as exc:
raise HTTPException(
status_code=500,
detail={
"message": "Could not read schedule config",
"error": f"{type(exc).__name__}: {exc}",
},
) from exc
if not isinstance(raw, dict):
raise HTTPException(
status_code=500,
detail="Schedule config root must be an object",
)
return raw
@app.put("/api/schedule/config")
async def update_schedule_config(payload: dict):
global schedule_load_error
schedule_path = FilePath(SCHEDULE_FILE)
temp_path = schedule_path.with_name(schedule_path.name + ".tmp")
backup_path = schedule_path.with_name(schedule_path.name + ".bak")
try:
serialized = yaml.safe_dump(
payload,
allow_unicode=True,
sort_keys=False,
default_flow_style=False,
)
temp_path.write_text(serialized, encoding="utf-8")
config = load_schedule(temp_path)
except (OSError, ValueError, yaml.YAMLError) as exc:
temp_path.unlink(missing_ok=True)
raise HTTPException(
status_code=400,
detail={
"message": "Invalid schedule config",
"error": str(exc),
},
) from exc
try:
if schedule_path.exists():
shutil.copy2(schedule_path, backup_path)
temp_path.replace(schedule_path)
except OSError as exc:
temp_path.unlink(missing_ok=True)
raise HTTPException(
status_code=500,
detail={
"message": "Could not save schedule config",
"error": f"{type(exc).__name__}: {exc}",
},
) from exc
schedule_load_error = None
restart_required = schedule_service is None
if schedule_service is not None:
await schedule_service.replace_config(config)
return {
"ok": True,
"restart_required": restart_required,
"config": payload,
"schedule": get_schedule_status(),
}
@app.post("/api/schedule/override/clear") @app.post("/api/schedule/override/clear")
async def clear_schedule_override(): async def clear_schedule_override():
if schedule_service is None: if schedule_service is None:
+7 -6
View File
@@ -23,12 +23,6 @@ class Co2Config:
... ...
] ]
@dataclass(
frozen=True,
slots=True,
)
class TemperatureConfig:
hysteresis: float
@dataclass( @dataclass(
frozen=True, frozen=True,
@@ -40,6 +34,13 @@ class AutoConfig:
co2: Co2Config co2: Co2Config
temperature: TemperatureConfig temperature: TemperatureConfig
@dataclass(
frozen=True,
slots=True,
)
class TemperatureConfig:
hysteresis: float
def _require_dict(name: str, value: Any) -> dict: def _require_dict(name: str, value: Any) -> dict:
-14
View File
@@ -1,14 +0,0 @@
from .config import ElicaConfig
from .controller import ElicaController
from .models import ElicaLogicalState, ElicaPanelState, ElicaState, ExternalFanState
from .service import ElicaService
__all__ = [
"ElicaConfig",
"ElicaController",
"ElicaLogicalState",
"ElicaPanelState",
"ElicaService",
"ElicaState",
"ExternalFanState",
]
-88
View File
@@ -1,88 +0,0 @@
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class ElicaConfig:
mqtt_host: str
mqtt_port: int = 1883
# Корневой MQTT topic ESPHome-контроллера Elica
topic: str = "elica"
# Длительность виртуального нажатия кнопки
pulse_ms: int = 300
# Физические реле платы ESP32 Relay X8 Modbus.
# OUT1-OUT4 используются для кнопок Elica.
power_relay: int = 1
speed_relay: int = 2
light_relay: int = 3
timer_relay: int = 4
# Внешний вытяжной вентилятор подключён к OUT5.
# Нагрузка заведена через NC-контакт реле, поэтому логическое
# состояние вентилятора инвертировано относительно катушки реле:
# relay OFF -> NC замкнут -> fan ON; relay ON -> fan OFF.
external_fan_relay: int = 5
external_fan_normally_closed: bool = True
# Индикаторы Elica -> IN
speed_1_input: int = 1
speed_2_input: int = 2
speed_3_input: int = 3
speed_4_input: int = 4
power_input: int = 5
# Определение мигания индикатора скорости.
blink_max_off_s: float = 1.5
blink_hold_s: float = 2.5
@property
def status_topic(self) -> str:
"""
Доступность ESP32.
Payload:
online
offline
"""
return f"{self.topic}/status"
def relay_command_topic(self, relay: int) -> str:
"""
Команда конкретному реле.
Payload:
ON
OFF
"""
return f"{self.topic}/relay/{relay}/set"
def relay_state_topic(self, relay: int) -> str:
"""
Состояние конкретного реле.
Payload:
ON
OFF
"""
return f"{self.topic}/relay/{relay}/state"
def input_state_topic(self, input_number: int) -> str:
"""
Состояние физического входа IN1-IN8.
Payload:
ON
OFF
"""
return f"{self.topic}/input/{input_number}/state"
@property
def relay_state_wildcard(self) -> str:
return f"{self.topic}/relay/+/state"
@property
def input_state_wildcard(self) -> str:
return f"{self.topic}/input/+/state"
-312
View File
@@ -1,312 +0,0 @@
import asyncio
from collections.abc import Callable
from .models import ElicaLogicalState
from .service import ElicaService
class ElicaController:
"""
Высокоуровневый контроллер вытяжки Elica.
ElicaService отвечает за ESP32, MQTT, реле и входы.
ElicaController работает уже с понятиями самой вытяжки:
питание, скорость, таймер и свет.
"""
def __init__(
self,
service: ElicaService,
state_timeout: float = 3.0,
poll_interval: float = 0.05,
speed_inter_press_delay: float = 0.4,
):
self._service = service
self._state_timeout = state_timeout
self._poll_interval = poll_interval
self._speed_inter_press_delay = max(0.0, speed_inter_press_delay)
# Не допускаем одновременное выполнение нескольких
# последовательностей нажатий кнопок.
self._lock = asyncio.Lock()
self._external_fan_lock = asyncio.Lock()
@property
def service(self) -> ElicaService:
return self._service
@property
def state(self) -> ElicaLogicalState:
return self._service.logical_state
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _ensure_available(self) -> None:
if not self._service.running:
raise RuntimeError("Elica service is not running")
if not self._service.state.mqtt_connected:
raise RuntimeError("Elica MQTT is not connected")
if not self._service.state.device_online:
raise RuntimeError("ESP32 Elica controller is offline")
async def _wait_state(
self,
predicate: Callable[[ElicaLogicalState], bool],
description: str,
timeout: float | None = None,
) -> ElicaLogicalState:
"""Ждёт подтверждения требуемого состояния по обратной связи."""
timeout = self._state_timeout if timeout is None else timeout
deadline = asyncio.get_running_loop().time() + timeout
while True:
self._ensure_available()
self._ensure_feedback_ready()
state = self.state
if predicate(state):
return state
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError(
f"Elica did not reach expected state: {description}; "
f"current state: {state}"
)
await asyncio.sleep(self._poll_interval)
async def _power_on_locked(self) -> ElicaLogicalState:
"""Включает вытяжку. Вызывается только под self._lock."""
await self._ensure_ready()
state = self.state
if state.power:
return state
await self._service.press_power()
return await self._wait_state(
lambda value: value.power,
"power on",
)
async def _power_off_locked(self) -> ElicaLogicalState:
"""Выключает вытяжку. Вызывается только под self._lock."""
await self._ensure_ready()
state = self.state
if not state.power:
return state
await self._service.press_power()
return await self._wait_state(
lambda value: not value.power,
"power off",
)
# ------------------------------------------------------------------
# Power
# ------------------------------------------------------------------
async def power_on(self) -> ElicaLogicalState:
async with self._lock:
return await self._power_on_locked()
async def power_off(self) -> ElicaLogicalState:
async with self._lock:
return await self._power_off_locked()
# ------------------------------------------------------------------
# Speed
# ------------------------------------------------------------------
async def set_speed(self, speed: int) -> ElicaLogicalState:
"""Устанавливает скорость 1-4 последовательными нажатиями Speed.
У Elica одна кнопка скорости и фиксированный цикл:
1 -> 2 -> 3 -> 4 -> 1
Поэтому сначала определяем текущую скорость по индикаторам,
вычисляем точное число нажатий и после каждого нажатия ждём
подтверждения следующей скорости.
"""
if not 1 <= speed <= 4:
raise ValueError("Elica speed must be between 1 and 4")
async with self._lock:
await self._ensure_ready()
state = self.state
if not state.power:
# У Elica кнопка Speed сама включает вытяжку. Первое
# нажатие из состояния OFF запускает её на скорости 1.
# Поэтому при выборе скорости Power здесь не нажимаем.
await self._service.press_speed()
state = await self._wait_state(
lambda value: value.power and value.speed == 1,
"speed 1",
)
# После физического отпускания кнопки Elica нужен
# небольшой гарантированный интервал до следующего
# нажатия. Иначе при быстром наборе 2/3/4 контроллер
# вытяжки иногда воспринимает два импульса как одно
# длинное нажатие или просто игнорирует следующий.
if speed != 1 and self._speed_inter_press_delay > 0:
await asyncio.sleep(self._speed_inter_press_delay)
# Если питание уже было включено, но индикатор скорости ещё
# не успел синхронизироваться, ждём корректное значение 1-4.
if not 1 <= state.speed <= 4:
state = await self._wait_state(
lambda value: value.power and 1 <= value.speed <= 4,
"initial speed",
)
current_speed = state.speed
presses = (speed - current_speed) % 4
for _ in range(presses):
expected_speed = current_speed % 4 + 1
await self._service.press_speed()
state = await self._wait_state(
lambda value, expected=expected_speed: (
value.power and value.speed == expected
),
f"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
# ------------------------------------------------------------------
# Timer
# ------------------------------------------------------------------
async def set_timer(self, enabled: bool) -> ElicaLogicalState:
"""
Включает или выключает таймер.
Состояние подтверждается по миганию индикатора скорости.
"""
async with self._lock:
await self._ensure_ready()
state = self.state
if not enabled and not state.power:
return state
if enabled and not state.power:
state = await self._power_on_locked()
if state.timer == enabled:
return state
await self._service.press_timer()
# При выключении таймера logical_state.timer остаётся True,
# пока не истечёт blink_hold_s после последнего мигания.
timeout = max(
self._state_timeout,
self._service.config.blink_hold_s + 1.5,
)
return await self._wait_state(
lambda value: value.timer == enabled,
f"timer {'on' if enabled else 'off'}",
timeout=timeout,
)
async def timer_on(self) -> ElicaLogicalState:
return await self.set_timer(True)
async def timer_off(self) -> ElicaLogicalState:
return await self.set_timer(False)
# ------------------------------------------------------------------
# Light
# ------------------------------------------------------------------
async def toggle_light(self) -> None:
"""
Переключает свет.
Обратной связи о состоянии света сейчас нет,
поэтому light_on/light_off реализовать достоверно нельзя.
"""
async with self._lock:
await self._ensure_ready()
await self._service.press_light()
# ------------------------------------------------------------------
# External fan (OUT5 / NC contact)
# ------------------------------------------------------------------
async def set_external_fan(self, enabled: bool) -> bool:
"""
Управляет внешним вентилятором через OUT5.
Вентилятор подключён к NC-контакту, поэтому для включения
вентилятора катушка реле должна быть выключена, а для выключения
— включена. Физическая инверсия скрыта внутри этого метода.
"""
async with self._external_fan_lock:
self._ensure_available()
relay = self._service.config.external_fan_relay
await self._service.wait_relay_feedback_ready(
relay,
timeout=self._state_timeout,
)
relay_enabled = (
not enabled
if self._service.config.external_fan_normally_closed
else enabled
)
if self._service.relay_state(relay) != relay_enabled:
self._service.set_relay(relay, relay_enabled)
await self._service.wait_relay_state(
relay,
relay_enabled,
timeout=self._state_timeout,
)
state = self._service.external_fan_state
if state.on is None:
raise RuntimeError("External fan state is unavailable")
return state.on
async def external_fan_on(self) -> bool:
return await self.set_external_fan(True)
async def external_fan_off(self) -> bool:
return await self.set_external_fan(False)
# ------------------------------------------------------------------
# Синхронизация начального состояния
# ------------------------------------------------------------------
async def _ensure_ready(self) -> None:
"""Проверяет доступность и ждёт исходной синхронизации feedback."""
self._ensure_available()
await self._service.wait_feedback_ready(timeout=self._state_timeout)
self._ensure_available()
def _ensure_feedback_ready(self) -> None:
if not self._service.feedback_ready:
raise RuntimeError("Elica feedback is not synchronized")
-70
View File
@@ -1,70 +0,0 @@
from dataclasses import asdict, dataclass
from datetime import datetime
@dataclass(frozen=True, slots=True)
class ElicaState:
mqtt_connected: bool = False
device_online: bool = False
last_message_at: datetime | None = None
firmware: str | None = None
uptime_seconds: int | None = None
wifi_rssi: int | None = None
# Фактические состояния OUT1-OUT8,
# полученные от ESPHome через MQTT.
relay_states: tuple[bool, ...] = (
False, False, False, False,
False, False, False, False,
)
# Состояния оптовходов IN1-IN8, полученные от ESPHome через MQTT.
# True означает электрически активный вход платы. Для линий
# индикаторов Elica это НЕ равно "LED включён": Elica активна LOW.
input_states: tuple[bool, ...] = (
False, False, False, False,
False, False, False, False,
)
def to_dict(self) -> dict:
result = asdict(self)
if result["last_message_at"] is not None:
result["last_message_at"] = (
result["last_message_at"].isoformat()
)
return result
@dataclass(frozen=True, slots=True)
class ElicaPanelState:
speed_leds: tuple[bool, bool, bool, bool] = (
False, False, False, False
)
power_led: bool = False
def to_dict(self) -> dict:
return asdict(self)
@dataclass(frozen=True, slots=True)
class ElicaLogicalState:
power: bool = False
speed: int = 0
timer: bool = False
def to_dict(self) -> dict:
return asdict(self)
@dataclass(frozen=True, slots=True)
class ExternalFanState:
available: bool = False
on: bool | None = None
relay: int = 5
relay_on: bool | None = None
normally_closed: bool = True
def to_dict(self) -> dict:
return asdict(self)
-691
View File
@@ -1,691 +0,0 @@
import time
import asyncio
import logging
import paho.mqtt.client as mqtt
from dataclasses import replace
from datetime import datetime, timezone
from .config import ElicaConfig
from .models import ElicaState, ElicaPanelState, ElicaLogicalState, ExternalFanState
logger = logging.getLogger(__name__)
class ElicaService:
"""
Низкоуровневый сервис связи с ESP32-контроллером Elica.
На данном этапе умеет:
- подключаться к MQTT;
- отслеживать online/offline ESP32;
- получать состояния OUT1-OUT8;
- включать и выключать любое реле.
Логика самой вытяжки здесь пока отсутствует.
"""
def __init__(self, config: ElicaConfig):
self._config = config
self._state = ElicaState()
self._running = False
self._client: mqtt.Client | None = None
self._last_speed = 0
self._speed_led_off_at: float | None = None
self._last_blink_at: float | None = None
self._received_input_mask = 0
self._received_relay_mask = 0
@property
def config(self) -> ElicaConfig:
return self._config
@property
def state(self) -> ElicaState:
return self._state
@property
def running(self) -> bool:
return self._running
async def start(self) -> None:
if self._running:
return
client = mqtt.Client(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
client_id="climatcontroller-elica",
)
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 stop(self) -> None:
if not self._running:
return
self._running = False
if self._client is not None:
self._client.disconnect()
self._client.loop_stop()
self._client = None
self._state = replace(
self._state,
mqtt_connected=False,
device_online=False,
)
# ------------------------------------------------------------------
# MQTT callbacks
# ------------------------------------------------------------------
def _on_connect(
self,
_client,
_userdata,
_flags,
reason_code,
_properties=None,
) -> None:
if reason_code != 0:
logger.error("ESP32 elica MQTT connection failed: %s",reason_code)
return
logger.info("ESP32 elica MQTT connected")
self._received_input_mask = 0
self._received_relay_mask = 0
# ------------------------------------------------------------------
# Подписки сервиса
# ------------------------------------------------------------------
#Статус
_client.subscribe(self._config.status_topic)
#широковещательная подписка статусов реле
_client.subscribe(self._config.relay_state_wildcard)
# широковещательная подписка статусов входов
_client.subscribe(self._config.input_state_wildcard)
self._state = replace(self._state, mqtt_connected=True)
def _on_disconnect(
self,
_client,
_userdata,
_disconnect_flags,
reason_code,
_properties=None,
) -> None:
if self._running:
logger.warning("ESP32 Elica MQTT disconnected unexpectedly: %s",reason_code)
else:
logger.info("ESP32 Elica MQTT disconnected: %s",reason_code)
self._received_input_mask = 0
self._received_relay_mask = 0
self._state = replace(
self._state,
mqtt_connected=False,
device_online=False,
)
def _on_message(
self,
_client,
_userdata,
message,
) -> None:
if message.topic == self._config.status_topic:
self._handle_status(message)
return
relay_prefix = f"{self._config.topic}/relay/"
if message.topic.startswith(relay_prefix) and message.topic.endswith("/state"):
self._handle_relay_state(message)
return
input_prefix = f"{self._config.topic}/input/"
if message.topic.startswith(input_prefix) and message.topic.endswith("/state"):
self._handle_input_state(message)
return
# ------------------------------------------------------------------
# Device status
# ------------------------------------------------------------------
def _handle_status(self, message) -> None:
payload = message.payload.decode("utf-8").strip()
now = datetime.now(timezone.utc)
if payload.lower() == "online":
device_online = True
elif payload.lower() == "offline":
device_online = False
else:
logger.warning("Unknown Exhaust LWT payload: %r",payload)
return
self._state = replace(
self._state,
device_online=device_online,
last_message_at=now,
)
# ------------------------------------------------------------------
# Relay state
# ------------------------------------------------------------------
def _handle_relay_state(self, message) -> None:
"""
Обрабатывает сообщения:
elica/relay/1/state
...
elica/relay/8/state
Payload:
ON
OFF
"""
prefix = f"{self._config.topic}/relay/"
suffix = "/state"
relay_text = message.topic[
len(prefix):-len(suffix)
]
try:
relay = int(relay_text)
except ValueError:
logger.warning("Invalid ESP32 Elica relay topic: %s",message.topic)
return
if not 1 <= relay <= 8:
logger.warning("ESP32 Elica relay number out of range: %s",relay)
return
try:
payload = message.payload.decode("utf-8").strip().upper()
except UnicodeDecodeError:
logger.warning("Invalid ESP32 Elica relay payload")
return
if payload == "ON":
enabled = True
elif payload == "OFF":
enabled = False
else:
logger.warning("Unknown ESP32 Elica relay payload: %r",payload,)
return
relay_states = list(self._state.relay_states)
relay_states[relay - 1] = enabled
self._state = replace(
self._state,
relay_states=tuple(relay_states),
last_message_at=datetime.now(timezone.utc),
)
self._received_relay_mask |= 1 << (relay - 1)
# ------------------------------------------------------------------
# Input state
# ------------------------------------------------------------------
def _handle_input_state(self, message) -> None:
"""
Обрабатывает elica/input/1/state ... elica/input/8/state.
Payload: ON / OFF.
"""
prefix = f"{self._config.topic}/input/"
suffix = "/state"
input_text = message.topic[len(prefix):-len(suffix)]
try:
input_number = int(input_text)
except ValueError:
logger.warning("Invalid ESP32 Elica input topic: %s", message.topic)
return
if not 1 <= input_number <= 8:
logger.warning("ESP32 Elica input number out of range: %s", input_number)
return
try:
payload = message.payload.decode("utf-8").strip().upper()
except UnicodeDecodeError:
logger.warning("Invalid ESP32 Elica input payload")
return
if payload == "ON":
enabled = True
elif payload == "OFF":
enabled = False
else:
logger.warning("Unknown ESP32 Elica input payload: %r", payload)
return
input_states = list(self._state.input_states)
input_states[input_number - 1] = enabled
self._state = replace(
self._state,
input_states=tuple(input_states),
last_message_at=datetime.now(timezone.utc),
)
self._received_input_mask |= 1 << (input_number - 1)
self._update_panel_tracker()
def input_state(self, input_number: int) -> bool:
"""Возвращает последнее известное состояние IN1-IN8."""
if not 1 <= input_number <= 8:
raise ValueError("Input number must be between 1 and 8")
return self._state.input_states[input_number - 1]
# ------------------------------------------------------------------
# Elica state tracking
# ------------------------------------------------------------------
def _update_panel_tracker(self) -> None:
"""Отслеживает скорость и мигание индикатора таймера."""
# Пока не получили все пять входов панели, не пытаемся
# интерпретировать их начальные значения. После инверсии Elica
# значение False по умолчанию выглядело бы как включённый LED.
if not self.feedback_ready:
return
panel = self.panel_state
now = time.monotonic()
if not panel.power_led:
self._last_speed = 0
self._speed_led_off_at = None
self._last_blink_at = None
return
active_speeds = [
index + 1
for index, enabled in enumerate(panel.speed_leds)
if enabled
]
if active_speeds:
speed = active_speeds[0]
if speed != self._last_speed:
self._last_speed = speed
self._speed_led_off_at = None
self._last_blink_at = None
return
if self._speed_led_off_at is not None:
off_time = now - self._speed_led_off_at
if off_time <= self._config.blink_max_off_s:
self._last_blink_at = now
self._speed_led_off_at = None
return
if self._last_speed > 0 and self._speed_led_off_at is None:
self._speed_led_off_at = now
@property
def logical_state(self) -> ElicaLogicalState:
"""Возвращает интерпретированное состояние вытяжки Elica."""
if not self.feedback_ready:
return ElicaLogicalState()
panel = self.panel_state
now = time.monotonic()
if not panel.power_led:
return ElicaLogicalState()
active_speeds = [
index + 1
for index, enabled in enumerate(panel.speed_leds)
if enabled
]
if active_speeds:
speed = active_speeds[0]
elif (
self._last_speed > 0
and self._speed_led_off_at is not None
and now - self._speed_led_off_at <= self._config.blink_max_off_s
):
speed = self._last_speed
else:
speed = 0
timer = (
speed > 0
and self._last_blink_at is not None
and now - self._last_blink_at <= self._config.blink_hold_s
)
return ElicaLogicalState(
power=True,
speed=speed,
timer=timer,
)
# ------------------------------------------------------------------
# MQTT publish
# ------------------------------------------------------------------
def _publish(
self,
topic: str,
payload: str,
) -> None:
if not self._running:
raise RuntimeError("Elica service is not running")
if self._client is None or not self._state.mqtt_connected:
raise RuntimeError("ESP32 Elica MQTT is not connected")
result = self._client.publish(
topic,
payload,
retain=False,
)
if result.rc != mqtt.MQTT_ERR_SUCCESS:
raise RuntimeError(f"MQTT publish failed: {result.rc}")
# ------------------------------------------------------------------
# Relay control
# ------------------------------------------------------------------
def set_relay(
self,
relay: int,
enabled: bool,
) -> None:
"""
Устанавливает состояние физического реле OUT1-OUT8.
Это низкоуровневая функция.
Например:
set_relay(1, True)
отправит:
elica/relay/1/set -> ON
"""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
topic = self._config.relay_command_topic(relay)
payload = "ON" if enabled else "OFF"
self._publish(topic, payload)
def relay_state(
self,
relay: int,
) -> bool:
"""
Возвращает последнее известное состояние реле.
"""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
return self._state.relay_states[relay - 1]
def relay_feedback_ready(self, relay: int) -> bool:
"""True, если после подключения уже получено состояние реле."""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
return bool(self._received_relay_mask & (1 << (relay - 1)))
@property
def external_fan_state(self) -> ExternalFanState:
"""Логическое состояние внешнего вентилятора на OUT5."""
relay = self._config.external_fan_relay
ready = self.relay_feedback_ready(relay)
if not ready:
return ExternalFanState(
available=False,
on=None,
relay=relay,
relay_on=None,
normally_closed=self._config.external_fan_normally_closed,
)
relay_on = self.relay_state(relay)
fan_on = (
not relay_on
if self._config.external_fan_normally_closed
else relay_on
)
return ExternalFanState(
available=True,
on=fan_on,
relay=relay,
relay_on=relay_on,
normally_closed=self._config.external_fan_normally_closed,
)
# ------------------------------------------------------------------
# Public status
# ------------------------------------------------------------------
def status(self) -> dict:
return {
"running": self._running,
"topic": self._config.topic,
"pulse_ms": self._config.pulse_ms,
"panel": self.panel_state.to_dict(),
"elica": self.logical_state.to_dict(),
"external_fan": self.external_fan_state.to_dict(),
"feedback_ready": self.feedback_ready,
"missing_feedback_inputs": self.missing_feedback_inputs,
**self._state.to_dict(),
}
async def pulse_relay(self, relay: int, pulse_ms: int | None = None) -> None:
"""
Кратковременно включает реле и затем выключает его.
Используется для эмуляции нажатия кнопок Elica.
"""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
duration_ms = pulse_ms if pulse_ms is not None else self._config.pulse_ms
self.set_relay(relay, True)
try:
await self.wait_relay_state(relay, True)
await asyncio.sleep(duration_ms / 1000)
finally:
try:
self.set_relay(relay, False)
except Exception:
logger.exception("Failed to release Elica relay %s", relay)
await self.wait_relay_state(relay, False)
async def wait_relay_feedback_ready(
self,
relay: int,
timeout: float = 3.0,
poll_interval: float = 0.02,
) -> None:
"""Ждёт первого MQTT-состояния указанного реле после connect."""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
deadline = asyncio.get_running_loop().time() + timeout
while not self.relay_feedback_ready(relay):
if not self._running:
raise RuntimeError("Elica service is not running")
if not self._state.mqtt_connected:
raise RuntimeError("Elica MQTT is not connected")
if not self._state.device_online:
raise RuntimeError("ESP32 Elica controller is offline")
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError(
f"Relay {relay} feedback synchronization timeout"
)
await asyncio.sleep(poll_interval)
async def wait_relay_state(
self,
relay: int,
expected: bool,
timeout: float = 2.0,
) -> None:
"""
Ждёт подтверждения состояния реле через MQTT.
"""
if not 1 <= relay <= 8:
raise ValueError("Relay number must be between 1 and 8")
deadline = asyncio.get_running_loop().time() + timeout
while self.relay_state(relay) != expected:
if asyncio.get_running_loop().time() >= deadline:
state = self.relay_state(relay)
raise TimeoutError(
f"Relay {relay} did not reach state {expected}; current state: {state}"
)
await asyncio.sleep(0.02)
# ------------------------------------------------------------------
# Elica buttons
# ------------------------------------------------------------------
async def press_power(self) -> None:
"""Эмулирует нажатие кнопки Power."""
await self.pulse_relay(self._config.power_relay)
async def press_speed(self) -> None:
"""Эмулирует нажатие кнопки Speed."""
await self.pulse_relay(self._config.speed_relay)
async def press_light(self) -> None:
"""Эмулирует нажатие кнопки Light."""
await self.pulse_relay(self._config.light_relay)
async def press_timer(self) -> None:
"""Эмулирует нажатие кнопки Timer."""
await self.pulse_relay(self._config.timer_relay)
# ------------------------------------------------------------------
# Elica panel feedback
# ------------------------------------------------------------------
@property
def panel_state(self) -> ElicaPanelState:
"""Возвращает фактическое состояние светодиодов панели Elica.
Входы обратной связи имеют обратную полярность относительно LED:
высокий уровень на IN означает, что соответствующий индикатор
Elica погашен, низкий уровень — что индикатор горит.
MQTT-состояние входа поэтому инвертируем именно здесь, на границе
между электрическим состоянием IN и логическим состоянием панели.
"""
return ElicaPanelState(
speed_leds=(
not self.input_state(self._config.speed_1_input),
not self.input_state(self._config.speed_2_input),
not self.input_state(self._config.speed_3_input),
not self.input_state(self._config.speed_4_input),
),
power_led=not self.input_state(self._config.power_input),
)
@property
def feedback_ready(self) -> bool:
"""True, когда получены состояния всех входов, необходимых для Elica."""
return not self.missing_feedback_inputs
@property
def missing_feedback_inputs(self) -> tuple[int, ...]:
"""Возвращает номера входов Elica, состояние которых ещё не получено."""
required = (
self._config.speed_1_input,
self._config.speed_2_input,
self._config.speed_3_input,
self._config.speed_4_input,
self._config.power_input,
)
return tuple(
input_number
for input_number in required
if not self._received_input_mask & (1 << (input_number - 1))
)
async def wait_feedback_ready(
self,
timeout: float = 3.0,
poll_interval: float = 0.05,
) -> None:
"""Ждёт получения исходного состояния всех входов панели Elica."""
deadline = asyncio.get_running_loop().time() + timeout
while not self.feedback_ready:
if not self._running:
raise RuntimeError("Elica service is not running")
if not self._state.mqtt_connected:
raise RuntimeError("Elica MQTT is not connected")
if not self._state.device_online:
raise RuntimeError("ESP32 Elica controller is offline")
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError(
f"Elica feedback synchronization timeout; "
f"missing inputs: {self.missing_feedback_inputs}"
)
await asyncio.sleep(poll_interval)
-1
View File
@@ -1 +0,0 @@
from .service import PrometheusMetricsService
-309
View File
@@ -1,309 +0,0 @@
import asyncio
import logging
import time
from pathlib import Path
logger = logging.getLogger(__name__)
class PrometheusMetricsService:
def __init__(
self,
tion_service,
qingping_service,
schedule_service=None,
auto_controller=None,
output_path: str | Path = (
"/var/lib/prometheus/node-exporter/"
"climatcontroller.prom"
),
interval: float = 5.0,
):
self._tion = tion_service
self._qingping = qingping_service
self._schedule = schedule_service
self._auto = auto_controller
self._output_path = Path(output_path)
self._interval = interval
self._running = False
self._task = None
self._last_error: str | None = None
@property
def running(self) -> bool:
return self._running
@property
def last_error(self) -> str | None:
return self._last_error
async def start(self) -> None:
if self._running:
return
self._running = True
await self._write_metrics()
self._task = asyncio.create_task(
self._loop()
)
async def stop(self) -> None:
if not self._running:
return
self._running = False
if self._task is not None:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
self._task = None
async def _loop(self) -> None:
while self._running:
await asyncio.sleep(
self._interval
)
try:
await self._write_metrics()
except Exception as exc:
self._last_error = f"{type(exc).__name__}: {exc}"
logger.exception("Prometheus metrics update failed")
async def _write_metrics(self) -> None:
lines: list[str] = []
# --------------------------------------------------
# Время последнего успешного обновления файла.
# Позволяет определить протухшие метрики.
# --------------------------------------------------
self._add_gauge(
lines,
"climat_metrics_timestamp_seconds",
time.time(),
"Unix timestamp of the last "
"ClimatController metrics update",
)
# --------------------------------------------------
# Tion
# --------------------------------------------------
self._add_gauge(
lines,
"climat_tion_online",
self._tion.online,
"Tion connection state",
)
tion_state = self._tion.state
if tion_state is not None:
self._add_gauge(
lines,
"climat_tion_power",
tion_state.power,
"Tion power state",
)
self._add_gauge(
lines,
"climat_tion_heater",
tion_state.heater,
"Tion heater enabled state",
)
self._add_gauge(
lines,
"climat_tion_heating",
tion_state.heating,
"Tion active heating state",
)
self._add_gauge(
lines,
"climat_tion_fan_speed",
tion_state.fan_speed,
"Tion fan speed",
)
self._add_gauge(
lines,
"climat_tion_in_temperature_celsius",
tion_state.in_temp,
"Tion inlet temperature",
)
self._add_gauge(
lines,
"climat_tion_out_temperature_celsius",
tion_state.out_temp,
"Tion outside temperature",
)
self._add_gauge(
lines,
"climat_tion_target_temperature_celsius",
tion_state.target_temp,
"Tion target temperature",
)
# --------------------------------------------------
# Qingping
# --------------------------------------------------
self._add_gauge(
lines,
"climat_qingping_online",
self._qingping.online,
"Qingping online state",
)
qingping_state = self._qingping.state
if qingping_state is not None:
self._add_gauge(
lines,
"climat_qingping_mqtt_connected",
qingping_state.mqtt_connected,
"Qingping MQTT connection state",
)
self._add_gauge(
lines,
"climat_qingping_temperature_celsius",
qingping_state.temperature,
"Qingping temperature",
)
self._add_gauge(
lines,
"climat_qingping_humidity_percent",
qingping_state.humidity,
"Qingping relative humidity",
)
self._add_gauge(
lines,
"climat_qingping_co2_ppm",
qingping_state.co2,
"Qingping CO2 concentration",
)
self._add_gauge(
lines,
"climat_qingping_pm25_ug_m3",
qingping_state.pm25,
"Qingping PM2.5 concentration",
)
self._add_gauge(
lines,
"climat_qingping_pm10_ug_m3",
qingping_state.pm10,
"Qingping PM10 concentration",
)
self._add_gauge(
lines,
"climat_qingping_battery_percent",
qingping_state.battery,
"Qingping battery level",
)
# --------------------------------------------------
# Schedule / AUTO
# --------------------------------------------------
if self._schedule is not None:
self._add_gauge(
lines,
"climat_schedule_paused",
self._schedule.paused,
"Schedule manual pause state",
)
try:
resolution = (
self._schedule.resolve()
)
self._add_gauge(
lines,
"climat_auto_active",
resolution.auto_active,
"AUTO schedule state",
)
except Exception:
logger.exception(
"Schedule metrics resolve failed"
)
# --------------------------------------------------
# Atomic write
# --------------------------------------------------
self._output_path.parent.mkdir(
parents=True,
exist_ok=True,
)
temp_path = (
self._output_path.with_suffix(
self._output_path.suffix
+ ".tmp"
)
)
temp_path.write_text(
"\n".join(lines) + "\n",
encoding="utf-8",
)
temp_path.replace(
self._output_path
)
self._last_error = None
@staticmethod
def _add_gauge(
lines: list[str],
name: str,
value,
help_text: str,
) -> None:
if value is None:
return
if isinstance(value, bool):
value = 1 if value else 0
lines.append(f"# HELP {name} {help_text}")
lines.append(f"# TYPE {name} gauge")
lines.append(f"{name} {value}")
-4
View File
@@ -13,10 +13,6 @@ QINGPING_MAC = "CCB5D131BA93"
QINGPING_MQTT_HOST = "192.168.7.3" QINGPING_MQTT_HOST = "192.168.7.3"
QINGPING_MQTT_PORT = 1883 QINGPING_MQTT_PORT = 1883
# ESP32-контроллер вытяжки Elica подключён к Mosquitto на mini-PC/NAS.
ELICA_MQTT_HOST = "192.168.7.100"
ELICA_MQTT_PORT = 1883
MIN_FAN_SPEED = 1 MIN_FAN_SPEED = 1
MAX_FAN_SPEED = 6 MAX_FAN_SPEED = 6
-1
View File
@@ -74,4 +74,3 @@ days:
sat: weekend sat: weekend
sun: weekend sun: weekend
@@ -1,348 +0,0 @@
esphome:
name: elica-relay
friendly_name: Elica Relay Controller
on_boot:
# First disable 74HC595 outputs so relays cannot chatter during boot.
- priority: 900
then:
- lambda: |-
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
# Initialise shared bus, force all relays OFF, then enable outputs.
- priority: 600
then:
- delay: 500ms
- lambda: |-
pinMode(25, OUTPUT); // shared LATCH
pinMode(26, OUTPUT); // shared CLOCK
pinMode(33, OUTPUT); // data to 74HC595
pinMode(27, INPUT); // data from 74HC165
digitalWrite(25, LOW);
shiftOut(33, 26, MSBFIRST, 0xFF); // active-low relays: all OFF
digitalWrite(25, HIGH);
id(relay_state) = 0x00;
digitalWrite(13, LOW); // enable 74HC595 outputs
esp32:
board: esp32dev
framework:
type: arduino
logger:
wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
ap:
ssid: "Elica-Relay-Fallback"
password: !secret fallback_password
captive_portal:
# We use MQTT as the main connection to the controller.
# Home Assistant / native ESPHome API is deliberately not enabled.
mqtt:
broker: !secret mqtt_broker
username: !secret mqtt_username
password: !secret mqtt_password
discovery: false
birth_message:
topic: elica/status
payload: online
retain: true
will_message:
topic: elica/status
payload: offline
retain: true
ota:
- platform: esphome
password: !secret ota_password
# Handy while commissioning the board.
web_server:
port: 80
globals:
- id: relay_state
type: uint8_t
restore_value: no
initial_value: '0x00'
- id: input_state
type: uint8_t
restore_value: no
initial_value: '0xFF'
# Tracks the real Elica Power LED so OUT5 can be used as a hard
# interlock for the external fan. The LED line is active LOW.
- id: elica_power_initialized
type: bool
restore_value: no
initial_value: 'false'
- id: elica_power_was_on
type: bool
restore_value: no
initial_value: 'false'
script:
- id: write_relays
mode: restart
then:
- lambda: |-
// Relay drivers are active LOW.
digitalWrite(25, LOW);
shiftOut(33, 26, MSBFIRST, ~id(relay_state));
digitalWrite(25, HIGH);
# 74HC595 and 74HC165 share CLOCK/LATCH on this board.
# Read inputs, then immediately restore the relay register.
interval:
- interval: 100ms
then:
- lambda: |-
// Parallel-load current input state into 74HC165.
digitalWrite(25, LOW);
delayMicroseconds(10);
digitalWrite(25, HIGH);
uint8_t v = 0;
for (int i = 0; i < 8; i++) {
v <<= 1;
if (digitalRead(27)) v |= 1;
digitalWrite(26, HIGH);
delayMicroseconds(2);
digitalWrite(26, LOW);
delayMicroseconds(2);
}
id(input_state) = v;
// Elica Power LED is connected to IN5 (74HC165 mask 0x40).
// IMPORTANT: on this board the 74HC165 raw state is inverted
// relative to the MQTT binary_sensor state. Empirically:
// raw bit 1 -> Elica Power LED ON, raw bit 0 -> LED OFF.
const bool elica_power_on = (v & 0x40) != 0;
bool relay5_changed = false;
if (!id(elica_power_initialized)) {
id(elica_power_initialized) = true;
// If ESP32 boots while Elica is already running, enforce
// the interlock immediately. If Elica is OFF, boot defaults
// already leave Relay 5 OFF -> NC closed -> fan ON.
if (elica_power_on && !(id(relay_state) & 0x10)) {
id(relay_state) |= 0x10;
relay5_changed = true;
}
} else if (elica_power_on) {
// Hard interlock: while Elica is ON, Relay 5 must stay ON.
// Relay 5 ON opens the NC contact and stops the external fan.
if (!(id(relay_state) & 0x10)) {
id(relay_state) |= 0x10;
relay5_changed = true;
}
} else if (id(elica_power_was_on)) {
// Elica has just switched OFF: automatically restore the
// external fan. Relay 5 OFF closes NC and starts the fan.
if (id(relay_state) & 0x10) {
id(relay_state) &= ~0x10;
relay5_changed = true;
}
}
id(elica_power_was_on) = elica_power_on;
// Shared bus changed while reading 74HC165:
// restore the requested relay state in 74HC595.
digitalWrite(25, LOW);
shiftOut(33, 26, MSBFIRST, ~id(relay_state));
digitalWrite(25, HIGH);
// Keep MQTT/web-server state in sync when the interlock itself
// changes Relay 5 rather than an external command doing it.
if (relay5_changed) {
id(relay5).publish_state((id(relay_state) & 0x10) != 0);
}
switch:
- platform: template
name: "Relay 1"
id: relay1
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x01) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x01;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x01;
- script.execute: write_relays
command_topic: "elica/relay/1/set"
state_topic: "elica/relay/1/state"
- platform: template
name: "Relay 2"
id: relay2
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x02) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x02;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x02;
- script.execute: write_relays
command_topic: "elica/relay/2/set"
state_topic: "elica/relay/2/state"
- platform: template
name: "Relay 3"
id: relay3
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x04) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x04;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x04;
- script.execute: write_relays
command_topic: "elica/relay/3/set"
state_topic: "elica/relay/3/state"
- platform: template
name: "Relay 4"
id: relay4
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x08) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x08;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x08;
- script.execute: write_relays
command_topic: "elica/relay/4/set"
state_topic: "elica/relay/4/state"
# OUT5 управляет внешним вентилятором через NC-контакт.
# relay5=OFF -> NC замкнут -> внешний вентилятор ВКЛ.
# relay5=ON -> NC разомкнут -> внешний вентилятор ВЫКЛ.
#
# HARD INTERLOCK по фактическому Power LED Elica (IN5):
# Elica ON -> Relay 5 принудительно ON -> внешний вентилятор OFF.
# Elica OFF -> при переходе автоматически Relay 5 OFF -> вентилятор ON.
# Пока Elica включена, MQTT-команда Relay 5 OFF игнорируется, чтобы
# внешний вентилятор нельзя было случайно включить одновременно с Elica.
- platform: template
name: "Relay 5"
id: relay5
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x10) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x10;
- script.execute: write_relays
turn_off_action:
- lambda: |-
// Use the same raw IN5 polarity as the interlock above:
// raw bit 1 means the Elica Power LED is ON.
const bool elica_power_on = (id(input_state) & 0x40) != 0;
if (elica_power_on) {
id(relay_state) |= 0x10;
} else {
id(relay_state) &= ~0x10;
}
- script.execute: write_relays
command_topic: "elica/relay/5/set"
state_topic: "elica/relay/5/state"
- platform: template
name: "Relay 6"
id: relay6
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x20) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x20;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x20;
- script.execute: write_relays
command_topic: "elica/relay/6/set"
state_topic: "elica/relay/6/state"
- platform: template
name: "Relay 7"
id: relay7
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x40) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x40;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x40;
- script.execute: write_relays
command_topic: "elica/relay/7/set"
state_topic: "elica/relay/7/state"
- platform: template
name: "Relay 8"
id: relay8
restore_mode: ALWAYS_OFF
lambda: return (id(relay_state) & 0x80) != 0;
turn_on_action:
- lambda: id(relay_state) |= 0x80;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x80;
- script.execute: write_relays
command_topic: "elica/relay/8/set"
state_topic: "elica/relay/8/state"
binary_sensor:
- platform: template
name: "Input 1"
lambda: return !(id(input_state) & 0x10);
state_topic: "elica/input/1/state"
- platform: template
name: "Input 2"
lambda: return !(id(input_state) & 0x08);
state_topic: "elica/input/2/state"
- platform: template
name: "Input 3"
lambda: return !(id(input_state) & 0x20);
state_topic: "elica/input/3/state"
- platform: template
name: "Input 4"
lambda: return !(id(input_state) & 0x04);
state_topic: "elica/input/4/state"
- platform: template
name: "Input 5"
lambda: return !(id(input_state) & 0x40);
state_topic: "elica/input/5/state"
- platform: template
name: "Input 6"
lambda: return !(id(input_state) & 0x02);
state_topic: "elica/input/6/state"
- platform: template
name: "Input 7"
lambda: return !(id(input_state) & 0x80);
state_topic: "elica/input/7/state"
- platform: template
name: "Input 8"
lambda: return !(id(input_state) & 0x01);
state_topic: "elica/input/8/state"
- platform: status
name: "Controller Status"
-28
View File
@@ -1,28 +0,0 @@
ELICA ESP32 RELAY X8 - INITIAL COMMISSIONING
Files:
elica-relay.yaml Main ESPHome configuration
secrets.yaml.template Copy/rename this to secrets.yaml and enter your values
Target hardware:
LCTech ESP32 Relay Board X8 Modbus / 303e32dc812
ESP32-WROOM-32E
74HC595 relay outputs + 74HC165 optocoupled inputs on shared bus
First commissioning:
1. Install ESPHome Device Builder.
2. Put elica-relay.yaml and secrets.yaml in its config folder/project.
3. Connect the board by USB-C.
4. Compile and install via USB.
5. After boot, supply the board from a suitable 9-24 V DC power supply for relay/input tests.
6. Test all relays before connecting anything to Elica.
MQTT topics:
elica/status
elica/relay/1/set ... elica/relay/8/set
elica/relay/1/state ... elica/relay/8/state
elica/input/1/state ... elica/input/8/state
Relay commands use ON / OFF.
All relays are forced OFF during boot.
Inputs do not control relays.
@@ -1,15 +0,0 @@
# Fill these values before compiling.
wifi_ssid: "YOUR_WIFI_SSID"
wifi_password: "YOUR_WIFI_PASSWORD"
# IP address or DNS name of the existing Mosquitto broker.
mqtt_broker: "192.168.1.10"
mqtt_username: "YOUR_MQTT_USERNAME"
mqtt_password: "YOUR_MQTT_PASSWORD"
# Used only if normal Wi-Fi cannot be reached.
fallback_password: "ChangeMe123!"
# Password for future wireless firmware updates.
ota_password: "ChangeThisOTAPassword"
+11 -20
View File
@@ -1,25 +1,16 @@
import argparse # Это пример Python скрипта.
import uvicorn # Нажмите Shift+F10 для выполнения или замените его своим кодом.
# Нажмите Двойное нажатие Shift для поиска везде: классы, файлы, окна инструментов, действия и настройки.
def parse_args() -> argparse.Namespace: def print_hi(name):
parser = argparse.ArgumentParser(description="Tion Controller web server") # Используйте точку останова в строке кода ниже для отладки скрипта.
parser.add_argument("--host", default="0.0.0.0") print(f'Hi, {name}') # Нажмите Ctrl+F8 для переключения точки останова.
parser.add_argument("--port", default=8000, type=int)
parser.add_argument(
"--reload",
action="store_true",
help="Reload the server after source file changes",
)
return parser.parse_args()
if __name__ == "__main__": # Нажмите зеленую кнопку на полях для запуска скрипта.
args = parse_args() if __name__ == '__main__':
uvicorn.run( print_hi('PyCharm')
"app.api:app",
host=args.host, # Справка PyCharm доступна на https://www.jetbrains.com/help/pycharm/
port=args.port,
reload=args.reload,
)
+1
View File
@@ -3,3 +3,4 @@ fastapi
uvicorn[standard] uvicorn[standard]
PyYAML PyYAML
paho-mqtt>=2.1,<3 paho-mqtt>=2.1,<3
paho-mqtt
-21
View File
@@ -105,27 +105,6 @@ class ScheduleService:
def config(self) -> ScheduleConfig: def config(self) -> ScheduleConfig:
return self._config return self._config
async def replace_config(
self,
config: ScheduleConfig,
) -> None:
"""Заменить расписание без перезапуска приложения."""
if not isinstance(config, ScheduleConfig):
raise TypeError("config must be ScheduleConfig")
self._config = config
self._last_applied_when = None
self._clear_override()
self._last_error = None
# Сохранение расписания не должно завершаться ошибкой только из-за
# временно недоступного Bluetooth. Фоновый цикл повторит применение.
if self._running and not self._paused:
try:
await self._process()
except Exception as exc:
self._last_error = f"{type(exc).__name__}: {exc}"
def _load_runtime_state(self) -> None: def _load_runtime_state(self) -> None:
if self._state_path is None: if self._state_path is None:
-112
View File
@@ -1,112 +0,0 @@
import asyncio
import json
from app.elica.config import ElicaConfig
from app.elica.service import ElicaService
async def main() -> None:
config = ElicaConfig(
mqtt_host="192.168.7.100", # IP Mosquitto
mqtt_port=1883,
)
service = ElicaService(config)
print("Starting ElicaService...")
await service.start( )
try:
# Даём MQTT время подключиться и получить retained elica/status.
await asyncio.sleep(2)
print(
json.dumps(
service.status(),
indent=2,
ensure_ascii=False,
)
)
assert service.state.mqtt_connected
assert service.state.device_online
print("\nMQTT: OK")
print("ESP32: ONLINE")
# --------------------------------------------------------------
# Проверяем все 8 реле по очереди
# --------------------------------------------------------------
for relay in range(1, 9):
# print(f"\nTesting Relay {relay}...")
#
# # ON
# service.set_relay(relay,True,)
#
# await asyncio.sleep(0.5)
#
# state = service.relay_state(relay)
#
# print(f"Relay {relay} after ON: {state}")
#
# assert state is True, (f"Relay {relay} did not report ON")
#
# # OFF
# service.set_relay(relay,False)
#
# await asyncio.sleep(0.5)
#
# state = service.relay_state(relay)
#
# print(f"Relay {relay} after OFF: {state}")
#
# assert state is False, (f"Relay {relay} did not report OFF")
print(f"Pulse Relay {relay}")
await service.pulse_relay(relay)
await asyncio.sleep(0.5)
print(f"Relay {relay} state:", service.relay_state(relay))
assert service.relay_state(relay) is False
print("\nAll 8 relays passed MQTT test.")
print("\nFinal state:")
print(
json.dumps(
service.status(),
indent=2,
ensure_ascii=False,
)
)
# print("\nInitial inputs:")
# print(service.state.input_states)
#
# print("\nToggle ESP32 inputs now...")
# for _ in range(15):
# await asyncio.sleep(1)
# print(service.state.input_states)
finally:
# На всякий случай гарантированно выключаем все реле.
if service.state.mqtt_connected:
for relay in range(1, 9):
service.set_relay(
relay,
False,
)
await asyncio.sleep(0.5)
await service.stop()
if __name__ == "__main__":
asyncio.run(main())
-64
View File
@@ -1,64 +0,0 @@
from datetime import datetime
from pathlib import Path
import subprocess
import tomllib
PROJECT_DIR = Path(__file__).resolve().parent.parent
VERSION_FILE = PROJECT_DIR / "version.toml"
def get_git_commit() -> str:
"""Возвращает short hash текущего HEAD."""
try:
result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
cwd=PROJECT_DIR,
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def main() -> None:
# Сначала читаем текущий version.toml.
# Нам нужны значения, которые разработчик поменял вручную.
with VERSION_FILE.open("rb") as file:
data = tomllib.load(file)
major = data["version"]["major"]
minor = data["version"]["minor"]
patch = data["version"]["patch"]
now = datetime.now()
content = f"""\
[version]
major = {major}
minor = {minor}
patch = {patch}
[build]
date = "{now:%Y-%m-%d}"
time = "{now:%H:%M:%S}"
"""
VERSION_FILE.write_text(
content,
encoding="utf-8",
)
print(
f"Version updated: "
f"{major}.{minor}.{patch} "
f"({now:%Y-%m-%d %H:%M:%S})"
)
if __name__ == "__main__":
main()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

-47
View File
@@ -1,47 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="fan" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="2.1" fill="currentColor" stroke="none"/>
<path d="M12 9.9c-1.3-1.6-2.1-3.1-1.3-5.1.6-1.5 2.5-2.2 3.8-1.2 1.7 1.3 1.2 3.5-.5 5.1-.6.6-1.3 1-2 1.2ZM14.1 12c1.6-1.3 3.1-2.1 5.1-1.3 1.5.6 2.2 2.5 1.2 3.8-1.3 1.7-3.5 1.2-5.1-.5-.6-.6-1-1.3-1.2-2ZM12 14.1c1.3 1.6 2.1 3.1 1.3 5.1-.6 1.5-2.5 2.2-3.8 1.2-1.7-1.3-1.2-3.5.5-5.1.6-.6 1.3-1 2-1.2ZM9.9 12c-1.6 1.3-3.1 2.1-5.1 1.3-1.5-.6-2.2-2.5-1.2-3.8 1.3-1.7 3.5-1.2 5.1.5.6.6 1 1.3 1.2 2Z" fill="currentColor" stroke="none"/>
</symbol>
<symbol id="thermometer" viewBox="0 0 24 24">
<path d="M9 14.4V5a3 3 0 0 1 6 0v9.4a5 5 0 1 1-6 0Z"/>
<path d="M12 7v9"/><circle cx="12" cy="18" r="1.7" fill="currentColor" stroke="none"/>
</symbol>
<symbol id="power" viewBox="0 0 24 24">
<path d="M12 2.8v8.4"/><path d="M7.2 6.1a8 8 0 1 0 9.6 0"/>
</symbol>
<symbol id="heat" viewBox="0 0 24 24">
<path d="M7 21c-2.7-3.1 2.5-5.5 0-8.6C4.7 9.6 8.8 7.1 7.2 3M12 21c-2.7-3.1 2.5-5.5 0-8.6C9.7 9.6 13.8 7.1 12.2 3M17 21c-2.7-3.1 2.5-5.5 0-8.6-2.3-2.8 1.8-5.3.2-9.4"/>
</symbol>
<symbol id="leaf" viewBox="0 0 24 24">
<path d="M20.5 3.5C12 3.3 5.5 6.4 5.2 13.1c-.2 3.5 2.5 6.1 5.8 5.7 6.3-.8 8.6-7.5 9.5-15.3Z"/>
<path d="M3 21c3.1-5 7-8.4 12.1-11"/>
</symbol>
<symbol id="drop" viewBox="0 0 24 24">
<path d="M12 2.7S5.7 9.6 5.7 14.8a6.3 6.3 0 0 0 12.6 0C18.3 9.6 12 2.7 12 2.7Z"/><path d="M9 16.2a3.3 3.3 0 0 0 3 2"/>
</symbol>
<symbol id="particles" viewBox="0 0 24 24">
<g fill="currentColor" stroke="none"><circle cx="7" cy="5" r="1.3"/><circle cx="13" cy="4" r="1"/><circle cx="18" cy="7" r="1.5"/><circle cx="5" cy="11" r="1"/><circle cx="11" cy="10" r="1.5"/><circle cx="17" cy="13" r="1"/><circle cx="7" cy="17" r="1.5"/><circle cx="13" cy="19" r="1"/><circle cx="19" cy="19" r="1.3"/></g>
</symbol>
<symbol id="filter" viewBox="0 0 24 24">
<rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 7v10M12 7v10M15 7v10"/>
</symbol>
<symbol id="clock" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/>
</symbol>
<symbol id="auto" viewBox="0 0 24 24">
<path d="M20 8V3.5L18.2 5A9 9 0 1 0 21 12M4 16v4.5L5.8 19"/><path d="m8.6 16 3.4-8 3.4 8M9.8 13h4.4"/>
</symbol>
<symbol id="pause" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9"/><path d="M9.5 8v8M14.5 8v8"/>
</symbol>
<symbol id="settings" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1-2.8 2.8-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.6v.2h-4V21a1.7 1.7 0 0 0-1-1.6 1.7 1.7 0 0 0-1.9.3l-.1.1L4.2 17l.1-.1a1.7 1.7 0 0 0 .3-1.9A1.7 1.7 0 0 0 3 14H2.8v-4H3a1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9L4.2 7 7 4.2l.1.1A1.7 1.7 0 0 0 9 4.6 1.7 1.7 0 0 0 10 3v-.2h4V3a1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1L19.8 7l-.1.1a1.7 1.7 0 0 0-.3 1.9 1.7 1.7 0 0 0 1.6 1h.2v4H21a1.7 1.7 0 0 0-1.6 1Z"/>
</symbol>
<symbol id="home" viewBox="0 0 24 24">
<path d="m3 11 9-8 9 8"/><path d="M5.5 9.5V21h13V9.5M9.5 21v-7h5v7"/>
</symbol>
<symbol id="wind" viewBox="0 0 24 24">
<path d="M3 7h9a3 3 0 1 0-2.6-4.5M3 12h15a3 3 0 1 1-2.7 4.3M3 17h7"/>
</symbol>
</svg>

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 388 KiB

-293
View File
@@ -1,293 +0,0 @@
:root {
color-scheme: light;
--page: #dcecf2;
--page-deep: #b7d4df;
--glass: rgba(244, 251, 253, 0.58);
--glass-strong: rgba(248, 253, 255, 0.76);
--glass-soft: rgba(255, 255, 255, 0.34);
--line: rgba(255, 255, 255, 0.72);
--line-soft: rgba(63, 104, 121, 0.14);
--text: #17313e;
--muted: #617b87;
--faint: #8ca0a9;
--blue: #198ed1;
--blue-deep: #096ca7;
--blue-soft: rgba(25, 142, 209, 0.14);
--green: #20a66a;
--green-soft: rgba(32, 166, 106, 0.14);
--orange: #e98a2c;
--orange-soft: rgba(233, 138, 44, 0.16);
--red: #d95665;
--red-soft: rgba(217, 86, 101, 0.14);
--yellow: #d7a823;
--shadow: 0 24px 70px rgba(42, 86, 105, 0.2), 0 2px 10px rgba(43, 82, 98, 0.08);
--shadow-soft: 0 10px 32px rgba(39, 80, 96, 0.12);
--radius-xl: 28px;
--radius-lg: 21px;
--radius-md: 16px;
--blur: 26px;
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
:root[data-theme="dark"] {
color-scheme: dark;
--page: #0d161d;
--page-deep: #172b39;
--glass: rgba(24, 38, 49, 0.68);
--glass-strong: rgba(28, 44, 56, 0.86);
--glass-soft: rgba(255, 255, 255, 0.045);
--line: rgba(193, 226, 240, 0.16);
--line-soft: rgba(188, 220, 234, 0.1);
--text: #eff8fb;
--muted: #9cb4bf;
--faint: #6e8793;
--blue: #56b9f0;
--blue-deep: #178ccf;
--blue-soft: rgba(69, 168, 225, 0.14);
--green: #52d394;
--green-soft: rgba(48, 193, 119, 0.14);
--orange: #f2a24c;
--orange-soft: rgba(242, 162, 76, 0.15);
--red: #ff7280;
--red-soft: rgba(255, 99, 116, 0.14);
--yellow: #f2c84b;
--shadow: 0 28px 80px rgba(0, 0, 0, 0.36), 0 2px 12px rgba(0, 0, 0, 0.28);
--shadow-soft: 0 12px 34px rgba(0, 0, 0, 0.22);
}
* { box-sizing: border-box; }
html, body { min-height: 100%; }
body {
margin: 0;
color: var(--text);
background:
radial-gradient(circle at 10% 5%, rgba(64, 176, 219, 0.32), transparent 32rem),
radial-gradient(circle at 88% 16%, rgba(73, 144, 225, 0.23), transparent 29rem),
radial-gradient(circle at 58% 92%, rgba(75, 191, 171, 0.2), transparent 32rem),
linear-gradient(145deg, var(--page), var(--page-deep));
background-attachment: fixed;
-webkit-font-smoothing: antialiased;
}
button, input { font: inherit; }
button { color: inherit; }
.ambient {
position: fixed;
inset: 0;
z-index: -1;
overflow: hidden;
pointer-events: none;
}
.ambient::before,
.ambient::after {
content: "";
position: absolute;
width: 28rem;
height: 28rem;
border-radius: 50%;
filter: blur(34px);
opacity: 0.34;
}
.ambient::before { left: -10rem; top: -12rem; background: #62d7e3; }
.ambient::after { right: -12rem; bottom: -15rem; background: #58a0ef; }
.glass {
background: linear-gradient(145deg, var(--glass-strong), var(--glass));
border: 1px solid var(--line);
box-shadow: var(--shadow);
backdrop-filter: blur(var(--blur)) saturate(135%);
-webkit-backdrop-filter: blur(var(--blur)) saturate(135%);
}
.glass-inner {
background: linear-gradient(145deg, var(--glass-soft), rgba(255,255,255,0.015));
border: 1px solid var(--line-soft);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.08), var(--shadow-soft);
}
.eyebrow {
color: var(--muted);
font-size: 0.69rem;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.brand { display: flex; align-items: center; gap: 0.78rem; min-width: 0; }
.brand-mark {
display: grid;
place-items: center;
width: 2.65rem;
height: 2.65rem;
flex: 0 0 auto;
border-radius: 0.9rem;
color: white;
background: linear-gradient(145deg, #45b9ed, #147cba);
box-shadow: 0 8px 20px rgba(18, 126, 184, 0.26), inset 0 1px 0 rgba(255,255,255,0.35);
}
.brand-mark svg { width: 1.42rem; height: 1.42rem; }
.brand-copy { min-width: 0; }
.brand-title { margin: 0; font-size: 1.05rem; line-height: 1.15; letter-spacing: -0.015em; }
.brand-subtitle { margin: 0.18rem 0 0; color: var(--muted); font-size: 0.72rem; }
.pill {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.43rem;
min-height: 1.75rem;
padding: 0.3rem 0.66rem;
border: 1px solid transparent;
border-radius: 999px;
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.055em;
white-space: nowrap;
text-transform: uppercase;
}
.pill::before { content: ""; width: 0.43rem; height: 0.43rem; border-radius: 50%; background: currentColor; box-shadow: 0 0 0 4px currentColor; opacity: 0.9; }
.pill.good { color: var(--green); background: var(--green-soft); border-color: color-mix(in srgb, var(--green) 24%, transparent); }
.pill.info { color: var(--blue); background: var(--blue-soft); border-color: color-mix(in srgb, var(--blue) 22%, transparent); }
.pill.warn { color: var(--orange); background: var(--orange-soft); border-color: color-mix(in srgb, var(--orange) 24%, transparent); }
.pill.bad { color: var(--red); background: var(--red-soft); border-color: color-mix(in srgb, var(--red) 24%, transparent); }
.pill.muted { color: var(--muted); background: var(--glass-soft); border-color: var(--line-soft); }
.pill.no-dot::before { display: none; }
.icon-button, .soft-button, .primary-button, .step-button, .toggle, .segment {
border: 0;
cursor: pointer;
transition: transform 150ms ease, background 150ms ease, border-color 150ms ease, opacity 150ms ease, box-shadow 150ms ease;
}
.icon-button:hover, .soft-button:hover, .primary-button:hover, .step-button:hover, .toggle:hover, .segment:hover { transform: translateY(-1px); }
.icon-button:active, .soft-button:active, .primary-button:active, .step-button:active, .toggle:active, .segment:active { transform: translateY(0) scale(0.98); }
button:focus-visible, input:focus-visible { outline: 3px solid color-mix(in srgb, var(--blue) 32%, transparent); outline-offset: 2px; }
button:disabled { cursor: wait; opacity: 0.55; transform: none !important; }
.icon-button {
display: grid;
place-items: center;
width: 2.45rem;
height: 2.45rem;
border: 1px solid var(--line-soft);
border-radius: 0.82rem;
background: var(--glass-soft);
}
.icon-button svg { width: 1.12rem; height: 1.12rem; }
.soft-button, .primary-button {
min-height: 2.55rem;
padding: 0.65rem 1rem;
border-radius: 0.88rem;
font-size: 0.77rem;
font-weight: 750;
}
.soft-button { color: var(--text); background: var(--glass-soft); border: 1px solid var(--line-soft); }
.primary-button { color: white; background: linear-gradient(145deg, #35aae3, #157dbb); box-shadow: 0 9px 24px rgba(14, 119, 177, 0.25); }
.soft-button.danger { color: var(--red); background: var(--red-soft); border-color: color-mix(in srgb, var(--red) 22%, transparent); }
.stepper { display: flex; align-items: center; justify-content: center; gap: 0.5rem; }
.step-button {
display: grid;
place-items: center;
width: 2.28rem;
height: 2.28rem;
border-radius: 0.78rem;
color: var(--blue);
background: var(--blue-soft);
border: 1px solid color-mix(in srgb, var(--blue) 22%, transparent);
font-size: 1.25rem;
font-weight: 500;
line-height: 1;
}
.toggle {
display: inline-flex;
align-items: center;
justify-content: space-between;
gap: 0.65rem;
min-width: 5.5rem;
padding: 0.48rem 0.58rem 0.48rem 0.7rem;
border: 1px solid var(--line-soft);
border-radius: 999px;
background: var(--glass-soft);
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.04em;
}
.toggle::after {
content: "";
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background: var(--faint);
box-shadow: inset 0 1px 0 rgba(255,255,255,0.3);
}
.toggle[aria-pressed="true"] { color: var(--green); background: var(--green-soft); border-color: color-mix(in srgb, var(--green) 26%, transparent); }
.toggle[aria-pressed="true"]::after { background: var(--green); box-shadow: 0 0 14px color-mix(in srgb, var(--green) 52%, transparent); }
.toggle.orange[aria-pressed="true"] { color: var(--orange); background: var(--orange-soft); border-color: color-mix(in srgb, var(--orange) 28%, transparent); }
.toggle.orange[aria-pressed="true"]::after { background: var(--orange); box-shadow: 0 0 14px color-mix(in srgb, var(--orange) 48%, transparent); }
.value { font-variant-numeric: tabular-nums; }
.muted { color: var(--muted); }
.range {
--progress: 50%;
width: 100%;
height: 1.35rem;
margin: 0;
appearance: none;
background: transparent;
cursor: pointer;
}
.range::-webkit-slider-runnable-track {
height: 0.42rem;
border-radius: 99px;
background: linear-gradient(90deg, var(--blue) var(--progress), var(--line-soft) var(--progress));
}
.range::-moz-range-track { height: 0.42rem; border-radius: 99px; background: var(--line-soft); }
.range::-moz-range-progress { height: 0.42rem; border-radius: 99px; background: var(--blue); }
.range::-webkit-slider-thumb {
width: 1.35rem;
height: 1.35rem;
margin-top: -0.465rem;
appearance: none;
border: 0.26rem solid var(--glass-strong);
border-radius: 50%;
background: var(--blue);
box-shadow: 0 3px 12px rgba(14, 118, 177, 0.36);
}
.range::-moz-range-thumb {
width: 0.92rem;
height: 0.92rem;
border: 0.25rem solid var(--glass-strong);
border-radius: 50%;
background: var(--blue);
box-shadow: 0 3px 12px rgba(14, 118, 177, 0.36);
}
.toast-region { position: fixed; right: 1rem; bottom: 1rem; z-index: 50; display: grid; gap: 0.55rem; }
.toast {
max-width: min(23rem, calc(100vw - 2rem));
padding: 0.78rem 1rem;
border: 1px solid var(--line);
border-radius: 0.9rem;
background: var(--glass-strong);
box-shadow: var(--shadow-soft);
backdrop-filter: blur(18px);
font-size: 0.78rem;
animation: toast-in 180ms ease both;
}
.toast.error { color: var(--red); border-color: color-mix(in srgb, var(--red) 28%, transparent); }
@keyframes toast-in { from { transform: translateY(0.55rem); opacity: 0; } }
.skeleton { color: transparent !important; border-radius: 0.4rem; background: linear-gradient(100deg, var(--line-soft) 35%, var(--glass-soft) 50%, var(--line-soft) 65%); background-size: 200% 100%; animation: shimmer 1.3s infinite; }
@keyframes shimmer { to { background-position-x: -200%; } }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }
}
-107
View File
@@ -1,107 +0,0 @@
/* Elica widget extends the exact Tion widget aeroglass material and background. */
.hood-icon svg { width: 1.75rem; height: 1.75rem; filter: drop-shadow(0 0 5px rgba(20,123,213,.18)); }
.exhaust-widget-speed { min-height: 12.2rem; }
.exhaust-widget-hero { grid-template-columns: 3.1rem 1fr 3.1rem; }
.hero-spacer { width: 3.1rem; height: 3.1rem; }
.exhaust-widget-segments { grid-template-columns: repeat(4, 1fr); }
.exhaust-widget-labels { grid-template-columns: repeat(4, 1fr); }
.external-fan-card { position: relative; overflow: hidden; }
.external-fan-card::after {
content: "";
position: absolute;
z-index: 0;
width: 10rem;
height: 10rem;
right: -4.4rem;
bottom: -5.4rem;
border-radius: 50%;
background: var(--blue-halo);
opacity: .16;
filter: blur(34px);
pointer-events: none;
}
.external-fan-card > * { position: relative; z-index: 1; }
.external-fan-card[data-on="true"] .fan-glyph { animation: exhaust-widget-spin 1.35s linear infinite; }
@keyframes exhaust-widget-spin { to { transform: rotate(360deg); } }
.exhaust-actions { display: grid; gap: .55rem; }
.exhaust-action-row { display: flex; align-items: center; justify-content: space-between; gap: .65rem; }
.exhaust-action-copy { min-width: 0; display: flex; align-items: center; gap: .55rem; }
.exhaust-action-copy > span { min-width: 0; display: grid; gap: .08rem; }
.exhaust-action-copy b { font-size: .78rem; }
.exhaust-action-copy small { color: var(--widget-muted); font-size: .58rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.exhaust-action-copy .section-icon, .bulb-icon { width: 1.55rem; height: 1.55rem; flex: 0 0 auto; }
.bulb-icon { color: #d59d17; filter: drop-shadow(0 0 5px rgba(213,157,23,.15)); }
.exhaust-divider { display: block; width: 100%; height: 1px; background: linear-gradient(90deg, transparent, var(--tile-edge-soft) 12%, var(--tile-edge-soft) 88%, transparent); }
.glass-switch.compact { width: 5.1rem; min-height: 2.45rem; font-size: .78rem; }
.glass-action {
min-height: 2.45rem;
padding: .5rem .68rem;
flex: 0 0 auto;
border: 1px solid var(--tile-edge);
border-radius: .76rem;
color: var(--widget-ink);
background: radial-gradient(circle at 20% -30%, rgba(255,255,255,.46), transparent 48%), linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
cursor: pointer;
font-size: .61rem;
font-weight: 760;
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
transition: transform .15s ease, filter .15s ease;
}
.glass-action:hover { transform: translateY(-1px); filter: brightness(1.05); }
.glass-action:active { transform: scale(.98); }
:root[data-theme="dark"] .glass-action { border-color: rgba(193,228,245,.22); background: radial-gradient(circle at 20% -30%, rgba(208,243,255,.09), transparent 48%), linear-gradient(145deg, rgba(77,112,133,.21), rgba(20,44,59,.26)); }
.exhaust-widget .open-panel svg { width: 1.45rem; height: 1.45rem; }
:root[data-widget-layout="horizontal"] .exhaust-widget {
width: min(100%, 64rem);
grid-template-columns: minmax(0, 1.45fr) minmax(14rem, .92fr) minmax(15rem, .86fr);
grid-template-areas:
"header header header"
"speed switches actions"
"open open open";
}
:root[data-widget-layout="horizontal"] .exhaust-widget-header { grid-area: header; }
:root[data-widget-layout="horizontal"] .exhaust-widget-speed { grid-area: speed; min-height: 8.8rem; }
:root[data-widget-layout="horizontal"] .exhaust-switch-grid {
grid-area: switches;
min-width: 0;
display: grid !important;
grid-template-columns: 1fr;
grid-template-rows: repeat(2, minmax(0, 1fr));
gap: .48rem;
align-content: stretch;
}
:root[data-widget-layout="horizontal"] .exhaust-switch-grid > .switch-card {
grid-area: auto !important;
min-width: 0;
min-height: 4.15rem;
padding: .55rem .62rem;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: .45rem;
}
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .switch-title,
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .switch-title > span { min-width: 0; }
:root[data-widget-layout="horizontal"] .exhaust-switch-grid .glass-switch { min-height: 2.45rem; width: 4.7rem; }
:root[data-widget-layout="horizontal"] .exhaust-actions { grid-area: actions; align-content: center; padding: .62rem .68rem; }
:root[data-widget-layout="horizontal"] .exhaust-action-copy small { max-width: 8.5rem; }
:root[data-widget-layout="horizontal"] .open-panel { grid-area: open; }
:root[data-widget-layout="horizontal"] .exhaust-widget-hero { margin: .45rem 0 .35rem; }
@media (max-width: 799px) {
:root[data-widget-layout="vertical"] .exhaust-widget { width: min(100%, 31.5rem); }
}
@media (max-width: 420px) {
.exhaust-action-copy small { max-width: 10rem; }
.glass-action { padding-inline: .55rem; }
}
-161
View File
@@ -1,161 +0,0 @@
/* Elica uses the same aeroglass material system as the Tion panel.
This file only defines the Elica-specific layout and controls. */
.exhaust-panel {
width: min(100%, 78rem);
min-height: auto;
display: grid;
gap: .75rem;
}
.exhaust-header { padding-bottom: .25rem; }
.exhaust-identity { min-width: 0; }
.exhaust-identity .identity-copy { min-width: 0; }
.exhaust-identity .title-row { display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; }
.exhaust-identity .identity-copy > small { display: block; margin-top: .28rem; color: var(--panel-muted); font-size: .7rem; }
.hood-mark {
width: 3.25rem;
height: 3.25rem;
padding: .68rem;
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 1rem;
color: #147bd5;
}
.hood-mark svg { width: 100%; height: 100%; filter: drop-shadow(0 0 6px rgba(20,123,213,.2)); }
.exhaust-badge { min-width: 19rem; }
.exhaust-badge svg { width: 2.25rem; height: 2.25rem; }
.panel-link { text-decoration: none; }
.exhaust-primary {
display: grid;
grid-template-columns: minmax(19rem, 1.42fr) repeat(2, minmax(13rem, .82fr));
grid-template-areas:
"speed power fan"
"speed action action";
gap: .75rem;
}
.exhaust-speed-card { grid-area: speed; min-height: 20rem; }
.exhaust-switch-card { min-height: 9.6rem; }
.power-card { grid-area: power; }
.exhaust-fan-card { grid-area: fan; }
.exhaust-action-card { grid-area: action; min-height: 9.6rem; justify-content: center; gap: .75rem; }
.exhaust-hero-control {
grid-template-columns: 3rem 1fr 3rem;
margin: auto 0 .9rem;
}
.hero-spacer { width: 3rem; height: 3rem; }
.exhaust-speed-segments { grid-template-columns: repeat(4, 1fr); gap: .2rem; }
.exhaust-speed-labels { grid-template-columns: repeat(4, 1fr); }
.exhaust-speed-segments button.active { transform: translateY(-1px); }
.exhaust-fan-card::after {
content: "";
position: absolute;
z-index: 0;
width: 13rem;
height: 13rem;
right: -5rem;
bottom: -7rem;
border-radius: 50%;
pointer-events: none;
filter: blur(44px);
background: var(--blue-halo);
opacity: .17;
}
.exhaust-fan-card > * { position: relative; z-index: 1; }
.exhaust-fan-card[data-on="true"] .fan-glyph { animation: exhaust-fan-spin 1.35s linear infinite; }
@keyframes exhaust-fan-spin { to { transform: rotate(360deg); } }
.action-row { display: flex; align-items: center; justify-content: space-between; gap: .9rem; }
.action-copy { display: flex; align-items: center; gap: .7rem; min-width: 0; }
.action-copy h2 { margin: 0; font-size: 1rem; line-height: 1.2; }
.action-copy p { margin: .18rem 0 0; color: var(--panel-muted); font-size: .68rem; line-height: 1.35; }
.bulb-icon { width: 2.1rem; height: 2.1rem; padding: .16rem; flex: 0 0 auto; color: #d59d17; filter: drop-shadow(0 0 6px rgba(213,157,23,.18)); }
.glass-divider { height: 1px; background: linear-gradient(90deg, transparent, var(--tile-line-soft) 12%, var(--tile-line-soft) 88%, transparent); }
.compact-switch {
width: 6.2rem;
min-height: 3.25rem;
flex: 0 0 auto;
font-size: 1.05rem;
}
.aero-button {
min-height: 3rem;
padding: .65rem .95rem;
flex: 0 0 auto;
border: 1px solid var(--tile-line);
border-radius: .9rem;
color: var(--panel-ink);
background:
radial-gradient(circle at 20% -25%, rgba(255,255,255,.48), transparent 48%),
linear-gradient(145deg, var(--tile-strong), var(--tile));
box-shadow: var(--tile-shadow);
backdrop-filter: blur(14px) saturate(122%);
-webkit-backdrop-filter: blur(14px) saturate(122%);
cursor: pointer;
font-size: .72rem;
font-weight: 760;
transition: transform .15s ease, filter .15s ease, box-shadow .15s ease;
}
.aero-button:hover { transform: translateY(-1px); filter: brightness(1.05); }
.aero-button:active { transform: scale(.98); }
:root[data-theme="dark"] .aero-button { border-color: rgba(193,228,245,.24); background: radial-gradient(circle at 20% -25%, rgba(208,243,255,.1), transparent 48%), linear-gradient(145deg, rgba(77,112,133,.22), rgba(20,44,59,.27)); }
.exhaust-status-section { margin-top: 0; }
.status-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .55rem; }
.status-item { min-height: 5rem; padding: .75rem .85rem; border-radius: .85rem; display: grid; align-content: center; gap: .25rem; }
.status-item span { color: var(--panel-muted); font-size: .58rem; text-transform: uppercase; letter-spacing: .07em; font-weight: 800; }
.status-item strong { font-size: .78rem; }
.status-item strong.good { color: #0a8a50; }
.status-item strong.warn { color: #bc6b16; }
.status-item strong.bad { color: #bd4050; }
:root[data-theme="dark"] .status-item strong.good { color: #7de5ad; }
:root[data-theme="dark"] .status-item strong.warn { color: #ffc078; }
:root[data-theme="dark"] .status-item strong.bad { color: #ff98a2; }
.diagnostic-note { margin: .6rem .25rem .05rem; color: var(--panel-muted); font-size: .63rem; }
.pending { opacity: .72; }
button:disabled { cursor: wait; }
@media (max-width: 980px) {
.exhaust-badge { display: none; }
.exhaust-primary {
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-areas:
"speed speed"
"power fan"
"action action";
}
.exhaust-speed-card { min-height: 16rem; }
}
@media (max-width: 640px) {
.exhaust-panel { gap: .6rem; }
.exhaust-header { align-items: flex-start; }
.exhaust-identity .identity-copy > small { display: none; }
.hood-mark { width: 2.8rem; height: 2.8rem; border-radius: .9rem; }
.exhaust-primary {
grid-template-columns: 1fr;
grid-template-areas: "speed" "power" "fan" "action";
}
.exhaust-speed-card { min-height: 14.5rem; }
.exhaust-switch-card { min-height: 8.2rem; }
.status-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.action-row { gap: .55rem; }
.action-copy p { font-size: .62rem; }
}
@media (max-width: 430px) {
.header-tools { gap: .35rem; }
.panel-link { display: none; }
.exhaust-speed-card, .exhaust-switch-card, .exhaust-action-card { padding: .8rem; }
.compact-switch { width: 5.35rem; min-height: 2.8rem; }
.aero-button { padding-inline: .7rem; }
}
-85
View File
@@ -1,85 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Elica — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/widget.css">
<link rel="stylesheet" href="/ui/static/css/elica-widget.css">
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
<main class="widget exhaust-widget" aria-live="polite">
<header class="widget-header exhaust-widget-header">
<div class="identity">
<span class="brand-icon hood-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none"><path d="M5 4h14M8 4v5l-3 4h14l-3-4V4M9 17c0 1.3-1 2-1 3M12 17c0 1.3-1 2-1 3M15 17c0 1.3-1 2-1 3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
</span>
<span class="identity-copy">
<span class="title-row"><h1>Elica</h1><span id="connection" class="pill muted">Загрузка</span></span>
<small id="header-detail">Вытяжная вентиляция</small>
</span>
</div>
<button id="theme-button" class="theme-button" type="button" title="Сменить тему">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
</button>
</header>
<section class="widget-tile control-card speed-card exhaust-widget-speed" aria-labelledby="speed-title">
<div class="card-title">
<svg class="ui-icon feature-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2 id="speed-title">Скорость вытяжки</h2><p id="speed-note">Фактическая ступень Elica</p></span>
</div>
<div class="hero-control exhaust-widget-hero">
<span class="hero-spacer" aria-hidden="true"></span>
<strong id="speed" class="hero-value value skeleton">0</strong>
<span class="hero-spacer" aria-hidden="true"></span>
</div>
<div class="speed-segments exhaust-widget-segments" role="group" aria-label="Выбор скорости">
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
</div>
<div class="scale-labels exhaust-widget-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span></div>
</section>
<section class="switch-grid exhaust-switch-grid" aria-label="Управление вентиляцией">
<article class="widget-tile switch-card power-card">
<div class="switch-title">
<svg class="ui-icon switch-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
<span><h2>Вытяжка</h2><small id="power-detail">Выключена</small></span>
</div>
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article id="external-fan-card" class="widget-tile switch-card external-fan-card" data-on="false">
<div class="switch-title">
<svg class="ui-icon switch-icon fan-glyph" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2>Внешний</h2><small id="external-fan-detail">OUT5 · NC</small></span>
</div>
<button id="external-fan-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
</section>
<section class="widget-tile info-card exhaust-actions" aria-label="Таймер и свет">
<div class="exhaust-action-row">
<span class="exhaust-action-copy"><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg><span><b>Таймер</b><small id="timer-detail">Выключен</small></span></span>
<button id="timer-toggle" class="glass-switch compact green" type="button" aria-pressed="false">OFF</button>
</div>
<i class="exhaust-divider" aria-hidden="true"></i>
<div class="exhaust-action-row">
<span class="exhaust-action-copy"><svg class="bulb-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 18h6M10 21h4M8.5 14.5A6 6 0 1 1 15.5 14.5c-.9.7-1.5 1.5-1.7 2.5h-3.6c-.2-1-.8-1.8-1.7-2.5Z" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg><span><b>Подсветка</b><small>Импульсное управление</small></span></span>
<button id="light-toggle" class="glass-action" type="button">Переключить</button>
</div>
</section>
<button id="open-panel" class="open-panel" type="button">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M5 4h14M8 4v5l-3 4h14l-3-4V4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>Открыть панель вытяжки</span><b aria-hidden="true">↗</b>
</button>
</main>
<script type="module" src="/ui/static/js/elica-widget.js"></script>
</body>
</html>
-118
View File
@@ -1,118 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Elica — управление вытяжкой</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/panel.css">
<link rel="stylesheet" href="/ui/static/css/elica.css">
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
<main class="climate-panel exhaust-panel" aria-live="polite">
<header class="panel-header exhaust-header">
<div class="identity exhaust-identity">
<span class="hood-mark glass-tile" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M5 4h14M8 4v5l-3 4h14l-3-4V4M9 17c0 1.3-1 2-1 3M12 17c0 1.3-1 2-1 3M15 17c0 1.3-1 2-1 3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
<span class="identity-copy">
<span class="title-row"><h1>Elica</h1><span id="connection" class="pill muted">Загрузка</span></span>
<small>Кухонная вытяжка и внешний вытяжной вентилятор</small>
</span>
</div>
<div class="header-tools">
<div class="ventilation-badge glass-tile exhaust-badge">
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><strong>Вытяжная вентиляция</strong><small>Управление Elica и внешним вентилятором</small></span>
</div>
<a class="icon-button panel-link" href="/ui/tion" title="Открыть Tion 4S" aria-label="Открыть Tion 4S">
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#wind"></use></svg>
</a>
<button id="refresh-button" class="icon-button" type="button" title="Обновить данные">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M20 11a8 8 0 1 0-2.34 5.66M20 5v6h-6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<button id="theme-button" class="icon-button" type="button" title="Сменить тему">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
</button>
</div>
</header>
<section class="primary-controls exhaust-primary" aria-label="Основное управление">
<article class="control-card glass-tile speed-card exhaust-speed-card">
<div class="card-title">
<svg class="ui-icon feature-icon fan-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2>Скорость вытяжки</h2><p id="speed-caption">Скорость определяется по индикаторам Elica</p></span>
</div>
<div class="hero-control exhaust-hero-control">
<span class="hero-spacer" aria-hidden="true"></span>
<strong id="speed-value" class="hero-value">—</strong>
<span class="hero-spacer" aria-hidden="true"></span>
</div>
<div class="speed-segments exhaust-speed-segments" role="group" aria-label="Выбор скорости">
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
</div>
<div class="speed-labels exhaust-speed-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span></div>
</article>
<article class="switch-card glass-tile power-card exhaust-switch-card">
<div class="card-title compact">
<svg class="ui-icon feature-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
<span><h2>Питание</h2><p id="power-caption">Ожидаем состояние панели</p></span>
</div>
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article id="external-fan-card" class="switch-card glass-tile exhaust-fan-card exhaust-switch-card" data-on="false">
<div class="card-title compact">
<svg class="ui-icon feature-icon fan-glyph" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2>Внешний вентилятор</h2><p id="external-fan-caption">Ожидаем состояние OUT5</p></span>
</div>
<button id="external-fan-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article class="control-card glass-tile action-card exhaust-action-card">
<div class="action-row">
<div class="action-copy">
<svg class="ui-icon feature-icon orange" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg>
<div><h2>Таймер</h2><p id="timer-caption">По миганию индикатора скорости</p></div>
</div>
<button id="timer-toggle" class="glass-switch orange compact-switch" type="button" aria-pressed="false">OFF</button>
</div>
<div class="glass-divider"></div>
<div class="action-row">
<div class="action-copy">
<svg class="bulb-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M9 18h6M10 21h4M8.5 14.5A6 6 0 1 1 15.5 14.5c-.9.7-1.5 1.5-1.7 2.5h-3.6c-.2-1-.8-1.8-1.7-2.5Z" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
<div><h2>Подсветка</h2><p>Без обратной связи по состоянию</p></div>
</div>
<button id="light-toggle" class="aero-button" type="button">Переключить</button>
</div>
</article>
</section>
<section class="content-section glass-section exhaust-status-section" aria-labelledby="status-title">
<div class="section-title">
<div><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#settings"></use></svg><h2 id="status-title">Связь с контроллером</h2></div>
<span id="updated-at" class="updated">—</span>
</div>
<div class="status-grid">
<article class="status-item glass-tile"><span>MQTT</span><strong id="mqtt-status">—</strong></article>
<article class="status-item glass-tile"><span>ESP32</span><strong id="device-status">—</strong></article>
<article class="status-item glass-tile"><span>Панель Elica</span><strong id="feedback-status">—</strong></article>
<article class="status-item glass-tile"><span>OUT5 физически</span><strong id="relay5-status">—</strong></article>
</div>
<p id="diagnostic-note" class="diagnostic-note">Получаем данные…</p>
</section>
</main>
<script type="module" src="/ui/static/js/elica.js"></script>
</body>
</html>
-303
View File
@@ -1,303 +0,0 @@
const query = new URLSearchParams(window.location.search);
export const isDemo = query.get("demo") === "1";
const demoState = {
online: true,
running: true,
last_seen: new Date().toISOString(),
last_error: null,
tion: {
power: true,
heater: true,
heating: false,
sound: true,
mode: "outside",
out_temp: 21,
in_temp: 20,
target_temp: 21,
fan_speed: 3,
filter_remain: 136.7,
device_time: "22:45",
request_error_code: 0,
model: "S4",
light: true,
},
auto: {
available: true,
state: "inactive",
reason: null,
target_speed: null,
auto_speed: null,
target_heater: null,
auto_heater: null,
temperature: 25.9,
temperature_source: "qingping",
last_error: null,
config_error: null,
},
qingping: {
online: true,
temperature: 25.9,
humidity: 69.4,
co2: 780,
pm25: 0,
pm10: 0,
battery: 100,
last_error: null,
},
schedule: {
available: true,
enabled: true,
running: true,
paused: false,
current_action: "set",
current_time: "22:45",
next_time: "10:00",
next_action: "set",
override_until_time: "10:00",
auto_active: false,
auto_fallback_speed: 2,
auto_target_temp: 21,
scheduled_settings: { speed: 2, target_temp: 21, heater: true },
override_active: true,
override_until: new Date(Date.now() + 8 * 3600_000).toISOString(),
override_settings: { speed: 3 },
last_error: null,
},
};
const demoScheduleConfig = {
version: 1,
enabled: true,
timezone: "local",
templates: {
workday: [
{ time: "07:30", action: { type: "set", power: true, speed: 3, heater: true, target_temp: 21 } },
{ time: "09:00", action: { type: "auto", speed: 2, target_temp: 21 } },
{ time: "22:45", action: { type: "set", speed: 1 } },
],
weekend: [
{ time: "09:30", action: { type: "set", power: true, speed: 3, heater: true, target_temp: 21 } },
{ time: "11:00", action: { type: "auto", speed: 2, target_temp: 21 } },
{ time: "23:00", action: { type: "set", speed: 1 } },
],
},
days: { mon: "workday", tue: "workday", wed: "workday", thu: "workday", fri: "workday", sat: "weekend", sun: "weekend" },
};
const copy = value => JSON.parse(JSON.stringify(value));
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
function mutateDemo(path) {
const tion = demoState.tion;
const schedule = demoState.schedule;
let match;
if ((match = path.match(/^\/api\/tion\/speed\/(\d)$/))) {
tion.fan_speed = Number(match[1]);
schedule.override_active = true;
schedule.override_until_time ||= schedule.next_time;
schedule.override_settings.speed = tion.fan_speed;
} else if ((match = path.match(/^\/api\/tion\/temperature\/(\d+)$/))) {
tion.target_temp = Number(match[1]);
schedule.override_active = true;
schedule.override_until_time ||= schedule.next_time;
schedule.override_settings.target_temp = tion.target_temp;
} else if ((match = path.match(/^\/api\/tion\/(power|heater|sound|light)\/(on|off)$/))) {
tion[match[1]] = match[2] === "on";
schedule.override_active = true;
schedule.override_settings[match[1]] = tion[match[1]];
} else if ((match = path.match(/^\/api\/tion\/mode\/(outside|recirculation)$/))) {
tion.mode = match[1];
schedule.override_active = true;
schedule.override_settings.mode = match[1];
} else if (path === "/api/schedule/override/clear") {
schedule.override_active = false;
schedule.override_until = null;
schedule.override_until_time = null;
schedule.override_settings = {};
} else if (path === "/api/schedule/pause") {
schedule.paused = true;
schedule.override_active = false;
schedule.override_until_time = null;
} else if (path === "/api/schedule/resume") {
schedule.paused = false;
}
demoState.last_seen = new Date().toISOString();
}
async function request(path, options = {}) {
if (isDemo) {
await wait(options.method === "POST" ? 220 : 80);
if (path === "/api/schedule/config") {
if (options.method === "PUT") {
const replacement = JSON.parse(options.body);
Object.keys(demoScheduleConfig).forEach(key => delete demoScheduleConfig[key]);
Object.assign(demoScheduleConfig, replacement);
return { ok: true, config: copy(demoScheduleConfig) };
}
return copy(demoScheduleConfig);
}
if (options.method === "POST") mutateDemo(path);
return copy(demoState);
}
const response = await fetch(path, {
cache: "no-store",
headers: { Accept: "application/json" },
...options,
});
if (!response.ok) {
let message = `Ошибка ${response.status}`;
try {
const body = await response.json();
if (body.detail && typeof body.detail === "object") {
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
} else {
message = body.detail || body.message || message;
}
} catch (_) {}
throw new Error(typeof message === "string" ? message : JSON.stringify(message));
}
return response.json();
}
export const api = {
status: () => request("/api/status"),
post: path => request(path, { method: "POST" }),
scheduleConfig: () => request("/api/schedule/config"),
saveScheduleConfig: config => request("/api/schedule/config", {
method: "PUT",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify(config),
}),
};
export function configureTheme(button) {
const allowed = ["auto", "light", "dark"];
const explicit = query.get("theme");
let mode = allowed.includes(explicit) ? explicit : (localStorage.getItem("tion-theme") || "auto");
const apply = () => {
const dark = mode === "dark" || (mode === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.dataset.theme = dark ? "dark" : "light";
document.documentElement.dataset.themeMode = mode;
if (button) {
button.title = `Тема: ${mode === "auto" ? "системная" : mode === "dark" ? "тёмная" : "светлая"}`;
button.setAttribute("aria-label", button.title);
}
};
apply();
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => mode === "auto" && apply());
if (button) button.addEventListener("click", () => {
mode = allowed[(allowed.indexOf(mode) + 1) % allowed.length];
localStorage.setItem("tion-theme", mode);
apply();
});
return () => mode;
}
export function setRangeProgress(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
input.style.setProperty("--progress", `${((value - min) / (max - min)) * 100}%`);
}
export function airQuality(co2) {
if (!Number.isFinite(Number(co2))) return { label: "Нет данных", tone: "muted", pct: 0 };
const value = Number(co2);
if (value < 700) return { label: "Отличный воздух", tone: "good", pct: value / 20 };
if (value < 900) return { label: "Хороший воздух", tone: "good", pct: value / 20 };
if (value < 1300) return { label: "Повышенный CO₂", tone: "warn", pct: value / 20 };
if (value < 1600) return { label: "Душно", tone: "warn", pct: value / 20 };
return { label: "Нужна вентиляция", tone: "bad", pct: Math.min(100, value / 20) };
}
const AIR_METER_STOPS = [
[400, [35, 143, 83]],
[700, [46, 166, 99]],
[820, [82, 181, 111]],
[900, [190, 153, 55]],
[1200, [214, 128, 45]],
[1500, [215, 83, 55]],
[2000, [188, 48, 72]],
];
const interpolateChannel = (start, end, amount) => Math.round(start + (end - start) * amount);
export function airMeterPalette(co2) {
const value = Number(co2);
if (!Number.isFinite(value)) {
return {
color: "rgb(105, 137, 158)",
glow: "rgba(83, 123, 150, .2)",
};
}
const bounded = Math.max(AIR_METER_STOPS[0][0], Math.min(AIR_METER_STOPS.at(-1)[0], value));
let lower = AIR_METER_STOPS[0];
let upper = AIR_METER_STOPS.at(-1);
for (let index = 1; index < AIR_METER_STOPS.length; index += 1) {
if (bounded <= AIR_METER_STOPS[index][0]) {
lower = AIR_METER_STOPS[index - 1];
upper = AIR_METER_STOPS[index];
break;
}
}
const amount = upper[0] === lower[0] ? 0 : (bounded - lower[0]) / (upper[0] - lower[0]);
const [red, green, blue] = lower[1].map((channel, index) => interpolateChannel(channel, upper[1][index], amount));
return {
color: `rgb(${red}, ${green}, ${blue})`,
glow: `rgba(${red}, ${green}, ${blue}, .26)`,
};
}
export function modeInfo(status) {
const schedule = status?.schedule || {};
if (!schedule.available) return { label: "Без расписания", detail: "Недоступно", tone: "muted" };
if (schedule.paused) return { label: "Ручной режим", detail: "Расписание на паузе", tone: "warn" };
if (schedule.override_active) return {
label: "Ручное управление",
detail: schedule.override_until_time ? `До ${schedule.override_until_time}` : "До следующей точки",
tone: "warn",
};
if (schedule.auto_active) return { label: "AUTO", detail: "По качеству воздуха", tone: "info" };
return { label: "Расписание", detail: "Активно", tone: "info" };
}
export const numberOrDash = (value, digits = 0) => {
const number = Number(value);
return Number.isFinite(number) ? number.toFixed(digits) : "—";
};
export function showToast(message, error = false) {
let region = document.querySelector(".toast-region");
if (!region) {
region = document.createElement("div");
region.className = "toast-region";
document.body.append(region);
}
const toast = document.createElement("div");
toast.className = `toast${error ? " error" : ""}`;
toast.textContent = message;
region.append(toast);
setTimeout(() => toast.remove(), 3200);
}
export function panelUrl(themeMode = "auto", hash = "") {
const url = new URL("/ui/tion", window.location.origin);
url.searchParams.set("theme", themeMode);
if (isDemo) url.searchParams.set("demo", "1");
url.hash = hash;
return url.toString();
}
-190
View File
@@ -1,190 +0,0 @@
import { configureTheme, showToast } from "./api.js";
const requestedLayout = new URLSearchParams(window.location.search).get("layout");
const layoutMode = ["horizontal", "vertical"].includes(requestedLayout) ? requestedLayout : null;
const wideLayout = window.matchMedia("(min-width: 800px)");
function applyLayout() {
document.documentElement.dataset.widgetLayout = layoutMode || (wideLayout.matches ? "horizontal" : "vertical");
}
applyLayout();
wideLayout.addEventListener("change", () => !layoutMode && applyLayout());
const $ = selector => document.querySelector(selector);
const $$ = selector => [...document.querySelectorAll(selector)];
const themeMode = configureTheme($("#theme-button"));
let state = null;
let busy = false;
let polling = false;
function setPill(label, tone) {
const element = $("#connection");
element.textContent = label;
element.className = `pill ${tone}`;
}
function drawToggle(selector, active, label = null) {
const button = $(selector);
const enabled = Boolean(active);
button.setAttribute("aria-pressed", String(enabled));
button.textContent = label || (enabled ? "ON" : "OFF");
}
function ready(status) {
return Boolean(status?.running && status?.mqtt_connected && status?.device_online);
}
function feedbackReady(status) {
return ready(status) && Boolean(status?.feedback_ready);
}
function drawSpeed(value) {
const speed = Math.max(0, Math.min(4, Number(value) || 0));
const output = $("#speed");
output.textContent = speed || "—";
output.classList.remove("skeleton");
$$('[data-speed]').forEach(button => {
const segment = Number(button.dataset.speed);
button.classList.toggle("active", speed > 0 && segment <= speed);
button.setAttribute("aria-pressed", String(segment === speed));
});
}
function render(status) {
state = status;
const elica = status?.elica || {};
const external = status?.external_fan || {};
const controllerOnline = ready(status);
const panelOnline = feedbackReady(status);
if (!status?.running) setPill("Сервис остановлен", "bad");
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
else if (!status?.device_online) setPill("ESP32 offline", "bad");
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
else setPill("Online", "good");
$("#header-detail").textContent = elica.power
? `Вытяжка включена${elica.speed ? ` · скорость ${elica.speed}` : ""}`
: "Вытяжная вентиляция";
drawSpeed(elica.speed);
$("#speed-note").textContent = panelOnline
? (elica.power ? "Фактическая ступень по индикаторам Elica" : "Выбор скорости включит вытяжку")
: "Ждём синхронизацию панели Elica";
drawToggle("#power-toggle", elica.power);
$("#power-detail").textContent = elica.power ? "Включена" : "Выключена";
if (external.available && typeof external.on === "boolean") {
drawToggle("#external-fan-toggle", external.on);
$("#external-fan-card").dataset.on = String(external.on);
$("#external-fan-detail").textContent = external.on ? "Работает · NC замкнут" : "Остановлен · NC разомкнут";
} else {
drawToggle("#external-fan-toggle", false, "—");
$("#external-fan-card").dataset.on = "false";
$("#external-fan-detail").textContent = "Ждём OUT5";
}
drawToggle("#timer-toggle", elica.timer);
$("#timer-detail").textContent = elica.timer ? "Активен" : "Выключен";
const hoodDisabled = busy || !panelOnline;
$("#power-toggle").disabled = hoodDisabled;
$$('[data-speed]').forEach(button => { button.disabled = hoodDisabled; });
$("#timer-toggle").disabled = hoodDisabled;
$("#light-toggle").disabled = hoodDisabled;
$("#external-fan-toggle").disabled = busy || !controllerOnline || !external.available;
}
async function request(path, options = {}) {
const response = await fetch(path, {
cache: "no-store",
headers: { Accept: "application/json" },
...options,
});
if (!response.ok) {
let message = `Ошибка ${response.status}`;
try {
const body = await response.json();
if (body?.detail && typeof body.detail === "object") {
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
} else message = body?.detail || body?.message || message;
} catch (_) {}
throw new Error(String(message));
}
return response.json();
}
async function refresh(silent = false) {
if (polling) return;
polling = true;
try { render(await request("/api/elica/status")); }
catch (error) {
setPill("API недоступен", "bad");
if (!silent) showToast(error.message, true);
} finally { polling = false; }
}
async function act(path, source, optimistic = null) {
if (busy) return;
busy = true;
optimistic?.();
if (state) render(state);
source?.setAttribute("disabled", "");
try { render(await request(path, { method: "POST" })); }
catch (error) { showToast(error.message, true); await refresh(true); }
finally {
busy = false;
source?.removeAttribute("disabled");
if (state) render(state);
}
}
$("#power-toggle").addEventListener("click", event => {
const next = !Boolean(state?.elica?.power);
act(`/api/elica/power/${next ? "on" : "off"}`, event.currentTarget, () => {
if (state?.elica) state.elica.power = next;
drawToggle("#power-toggle", next);
});
});
$$('[data-speed]').forEach(button => button.addEventListener("click", () => {
const speed = Number(button.dataset.speed);
act(`/api/elica/speed/${speed}`, button, () => {
if (state?.elica) { state.elica.power = true; state.elica.speed = speed; }
drawSpeed(speed);
});
}));
$("#timer-toggle").addEventListener("click", event => {
const next = !Boolean(state?.elica?.timer);
act(`/api/elica/timer/${next ? "on" : "off"}`, event.currentTarget, () => {
if (state?.elica) state.elica.timer = next;
drawToggle("#timer-toggle", next);
});
});
$("#light-toggle").addEventListener("click", event => {
act("/api/elica/light/toggle", event.currentTarget);
});
$("#external-fan-toggle").addEventListener("click", event => {
const next = !Boolean(state?.external_fan?.on);
act(`/api/elica/external-fan/${next ? "on" : "off"}`, event.currentTarget, () => {
if (state?.external_fan) state.external_fan.on = next;
drawToggle("#external-fan-toggle", next);
$("#external-fan-card").dataset.on = String(next);
});
});
$("#open-panel").addEventListener("click", () => {
const url = new URL("/ui/elica", window.location.origin);
url.searchParams.set("theme", themeMode());
window.open(url.toString(), "_blank", "noopener");
});
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(true); });
refresh();
setInterval(() => !document.hidden && !busy && refresh(true), 1500);
-241
View File
@@ -1,241 +0,0 @@
import { configureTheme, showToast } from "./api.js";
const $ = selector => document.querySelector(selector);
const $$ = selector => [...document.querySelectorAll(selector)];
const connection = $("#connection");
const powerToggle = $("#power-toggle");
const powerCaption = $("#power-caption");
const speedValue = $("#speed-value");
const speedCaption = $("#speed-caption");
const speedButtons = $$("[data-speed]");
const timerToggle = $("#timer-toggle");
const timerCaption = $("#timer-caption");
const lightToggle = $("#light-toggle");
const externalFanToggle = $("#external-fan-toggle");
const externalFanCaption = $("#external-fan-caption");
const externalFanCard = $("#external-fan-card");
const mqttStatus = $("#mqtt-status");
const deviceStatus = $("#device-status");
const feedbackStatus = $("#feedback-status");
const relay5Status = $("#relay5-status");
const diagnosticNote = $("#diagnostic-note");
const updatedAt = $("#updated-at");
const refreshButton = $("#refresh-button");
const themeButton = $("#theme-button");
configureTheme(themeButton);
let latest = null;
let polling = false;
let commandBusy = false;
let refreshTimer = null;
function setTextState(element, text, tone = "") {
element.textContent = text;
element.className = tone;
}
function setPill(text, tone) {
connection.textContent = text;
connection.className = `pill ${tone}`;
}
function setToggle(button, enabled, label = null) {
const isOn = Boolean(enabled);
button.setAttribute("aria-pressed", String(isOn));
const text = button.querySelector("span");
if (text) text.textContent = label || (isOn ? "ON" : "OFF");
else button.textContent = label || (isOn ? "ON" : "OFF");
}
function controllerReady(status) {
return Boolean(
status?.running &&
status?.mqtt_connected &&
status?.device_online
);
}
function hoodReady(status) {
return controllerReady(status) && Boolean(status?.feedback_ready);
}
function render(status) {
latest = status;
const logical = status?.elica || {};
const external = status?.external_fan || {};
const ready = controllerReady(status);
const feedbackReady = hoodReady(status);
if (!status?.running) setPill("Сервис остановлен", "bad");
else if (!status?.mqtt_connected) setPill("MQTT нет связи", "bad");
else if (!status?.device_online) setPill("ESP32 offline", "bad");
else if (!status?.feedback_ready) setPill("Синхронизация", "warn");
else setPill("Online", "good");
setToggle(powerToggle, logical.power);
powerCaption.textContent = logical.power
? `Включена${logical.speed ? ` · скорость ${logical.speed}` : ""}`
: "Вытяжка выключена";
const speed = Number(logical.speed) || 0;
speedValue.textContent = speed || "—";
speedButtons.forEach(button => {
button.classList.toggle("active", speed > 0 && Number(button.dataset.speed) <= speed);
});
speedCaption.textContent = feedbackReady
? (logical.power ? "Фактическая скорость по индикаторам Elica." : "При выборе скорости вытяжка включится автоматически.")
: "Ждём синхронизацию входов панели Elica.";
setToggle(timerToggle, logical.timer);
timerCaption.textContent = logical.timer
? "Таймер активен · индикатор скорости мигает"
: "Таймер выключен";
if (external.available && typeof external.on === "boolean") {
setToggle(externalFanToggle, external.on);
externalFanCard.dataset.on = String(external.on);
externalFanCaption.textContent = external.on
? "Включён · NC замкнут, OUT5 выключен"
: "Выключен · NC разомкнут, OUT5 включен";
} else {
setToggle(externalFanToggle, false, "—");
externalFanCard.dataset.on = "false";
externalFanCaption.textContent = "Ждём обратную связь OUT5";
}
setTextState(mqttStatus, status?.mqtt_connected ? "Подключён" : "Нет связи", status?.mqtt_connected ? "good" : "bad");
setTextState(deviceStatus, status?.device_online ? "Online" : "Offline", status?.device_online ? "good" : "bad");
setTextState(feedbackStatus, status?.feedback_ready ? "Синхронизирована" : "Ожидание", status?.feedback_ready ? "good" : "warn");
if (external.available) {
setTextState(relay5Status, external.relay_on ? "ON · NC открыт" : "OFF · NC закрыт", external.relay_on ? "warn" : "good");
} else {
setTextState(relay5Status, "Нет данных", "warn");
}
const missing = status?.missing_feedback_inputs || [];
diagnosticNote.textContent = missing.length
? `Не получены входы Elica: ${missing.join(", ")}.`
: "Состояния вытяжки подтверждаются по MQTT и физическим входам ESP32.";
const stamp = status?.last_message_at ? new Date(status.last_message_at) : new Date();
updatedAt.textContent = Number.isNaN(stamp.getTime())
? "—"
: `Обновлено ${stamp.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}`;
const disableHood = commandBusy || !feedbackReady;
powerToggle.disabled = disableHood;
speedButtons.forEach(button => { button.disabled = disableHood; });
timerToggle.disabled = disableHood;
lightToggle.disabled = disableHood;
externalFanToggle.disabled = commandBusy || !ready || !external.available;
document.body.classList.toggle("pending", commandBusy);
}
async function request(path, options = {}) {
const response = await fetch(path, {
cache: "no-store",
headers: { Accept: "application/json" },
...options,
});
if (!response.ok) {
let message = `Ошибка ${response.status}`;
try {
const body = await response.json();
if (body?.detail && typeof body.detail === "object") {
message = [body.detail.message, body.detail.error].filter(Boolean).join(": ") || message;
} else {
message = body?.detail || body?.message || message;
}
} catch (_) {}
throw new Error(String(message));
}
return response.json();
}
async function refresh({ silent = false } = {}) {
if (polling) return;
polling = true;
try {
render(await request("/api/elica/status"));
} catch (error) {
setPill("API недоступен", "bad");
if (!silent) showToast(error.message, true);
} finally {
polling = false;
}
}
async function command(path, optimistic = null) {
if (commandBusy) return;
commandBusy = true;
if (latest) render(latest);
if (optimistic) optimistic();
try {
const status = await request(path, { method: "POST" });
render(status);
} catch (error) {
showToast(error.message, true);
await refresh({ silent: true });
} finally {
commandBusy = false;
if (latest) render(latest);
}
}
powerToggle.addEventListener("click", () => {
const next = !Boolean(latest?.elica?.power);
command(`/api/elica/power/${next ? "on" : "off"}`, () => {
setToggle(powerToggle, next);
powerCaption.textContent = next ? "Включаем…" : "Выключаем…";
});
});
speedButtons.forEach(button => button.addEventListener("click", () => {
const speed = Number(button.dataset.speed);
command(`/api/elica/speed/${speed}`, () => {
speedValue.textContent = String(speed);
speedButtons.forEach(item => item.classList.toggle("active", item === button));
speedCaption.textContent = `Устанавливаем скорость ${speed}…`;
});
}));
timerToggle.addEventListener("click", () => {
const next = !Boolean(latest?.elica?.timer);
command(`/api/elica/timer/${next ? "on" : "off"}`, () => {
setToggle(timerToggle, next);
timerCaption.textContent = next ? "Включаем таймер…" : "Выключаем таймер…";
});
});
lightToggle.addEventListener("click", () => {
command("/api/elica/light/toggle", () => {
lightToggle.textContent = "Команда…";
setTimeout(() => { lightToggle.textContent = "Переключить"; }, 700);
});
});
externalFanToggle.addEventListener("click", () => {
const next = !Boolean(latest?.external_fan?.on);
command(`/api/elica/external-fan/${next ? "on" : "off"}`, () => {
setToggle(externalFanToggle, next);
externalFanCard.dataset.on = String(next);
externalFanCaption.textContent = next ? "Включаем…" : "Выключаем…";
});
});
refreshButton.addEventListener("click", () => refresh());
document.addEventListener("visibilitychange", () => {
if (!document.hidden) refresh({ silent: true });
});
refresh();
refreshTimer = window.setInterval(() => refresh({ silent: true }), 1000);
window.addEventListener("beforeunload", () => window.clearInterval(refreshTimer));
-172
View File
@@ -1,172 +0,0 @@
import { api, airMeterPalette, airQuality, configureTheme, isDemo, modeInfo, numberOrDash, panelUrl, showToast } from "./api.js";
const requestedLayout = new URLSearchParams(window.location.search).get("layout");
const layoutMode = ["horizontal", "vertical"].includes(requestedLayout) ? requestedLayout : null;
const wideLayout = window.matchMedia("(min-width: 800px)");
function applyLayout() {
document.documentElement.dataset.widgetLayout = layoutMode || (wideLayout.matches ? "horizontal" : "vertical");
}
applyLayout();
wideLayout.addEventListener("change", () => !layoutMode && applyLayout());
const $ = selector => document.querySelector(selector);
const themeMode = configureTheme($("#theme-button"));
let state = null;
let busy = false;
if (isDemo) $("#demo-note").hidden = false;
function setText(selector, value) { $(selector).textContent = value; }
function setPill(element, label, tone) { element.textContent = label; element.className = `pill ${tone}`; }
function toneClass(tone) { return ["good", "warn", "bad"].includes(tone) ? tone : "muted"; }
function updateSpeedVisual(value) {
const speed = Math.max(1, Math.min(6, Number(value) || 1));
setText("#speed", speed);
$("#speed").classList.remove("skeleton");
document.querySelectorAll("[data-speed]").forEach(button => {
const segment = Number(button.dataset.speed);
button.classList.toggle("active", segment <= speed);
button.setAttribute("aria-pressed", String(segment === speed));
});
}
function updateTemperatureVisual(value) {
const temperature = Math.max(5, Math.min(30, Number(value) || 5));
setText("#target-temp", temperature);
$("#target-temp").classList.remove("skeleton");
$("#temperature-range").value = temperature;
}
function drawToggle(selector, active) {
const button = $(selector);
button.setAttribute("aria-pressed", String(Boolean(active)));
button.textContent = active ? "ON" : "OFF";
}
function render(status) {
state = status;
const tion = status.tion || {};
const sensor = status.qingping || {};
const schedule = status.schedule || {};
const mode = modeInfo(status);
const quality = airQuality(sensor.co2);
const headerMode = schedule.override_active && schedule.override_until_time
? `Ручной до ${schedule.override_until_time}`
: mode.label;
setPill($("#connection"), status.online ? "Online" : "Offline", status.online ? "good" : "bad");
setPill($("#mode-pill"), headerMode, mode.tone);
setText("#mode-detail", mode.detail);
updateSpeedVisual(tion.fan_speed);
setText("#speed-note", status.auto?.state === "active" && status.auto?.target_speed
? `AUTO выбрал скорость ${status.auto.target_speed}`
: `Ступень ${numberOrDash(tion.fan_speed)} из 6`);
updateTemperatureVisual(tion.target_temp);
setText("#heating-note", tion.heating ? "Сейчас нагревает входящий воздух" : tion.heater ? "Обогрев разрешён" : "Желаемая температура воздуха");
drawToggle("#power-toggle", tion.power);
drawToggle("#heater-toggle", tion.heater);
setText("#power-detail", tion.power ? "Устройство включено" : "Устройство выключено");
setText("#heater-detail", tion.heating ? "Сейчас нагревает" : tion.heater ? "Автоматически" : "Выключен");
setText("#co2", numberOrDash(sensor.co2));
setText("#air-label", quality.label);
const airTone = toneClass(quality.tone);
const airPalette = airMeterPalette(sensor.co2);
const airCard = $(".air-card");
$("#air-label").className = `quality-chip ${airTone}`;
airCard.dataset.airTone = airTone;
airCard.style.setProperty("--air-color", airPalette.color);
airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setText("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1));
setText("#humidity", numberOrDash(sensor.humidity));
setText("#current-time", schedule.current_time || tion.device_time || "—");
setText("#next-time", schedule.next_time || "—");
}
async function refresh(silent = false) {
try { render(await api.status()); }
catch (error) {
setPill($("#connection"), "Ошибка", "bad");
if (!silent) showToast(error.message, true);
}
}
async function act(path, source) {
if (busy) return;
busy = true;
source?.setAttribute("disabled", "");
try { await api.post(path); await refresh(true); }
catch (error) { showToast(error.message, true); await refresh(true); }
finally { busy = false; source?.removeAttribute("disabled"); }
}
function stepped(kind, delta, source) {
if (busy || !state?.tion) return;
const isSpeed = kind === "speed";
const current = Number(isSpeed ? state.tion.fan_speed : state.tion.target_temp);
const min = isSpeed ? 1 : 5;
const max = isSpeed ? 6 : 30;
const value = Math.min(max, Math.max(min, current + delta));
if (!Number.isFinite(value) || value === current) return;
if (isSpeed) {
state.tion.fan_speed = value;
updateSpeedVisual(value);
} else {
state.tion.target_temp = value;
updateTemperatureVisual(value);
}
act(`/api/tion/${isSpeed ? "speed" : "temperature"}/${value}`, source);
}
document.querySelectorAll("[data-step]").forEach(button => button.addEventListener("click", () => {
stepped(button.dataset.step, Number(button.dataset.delta), button);
}));
document.querySelectorAll("[data-speed]").forEach(button => button.addEventListener("click", () => {
if (busy || !state?.tion) return;
const value = Number(button.dataset.speed);
state.tion.fan_speed = value;
updateSpeedVisual(value);
act(`/api/tion/speed/${value}`, button);
}));
$("#temperature-range").addEventListener("input", event => setText("#target-temp", event.target.value));
$("#temperature-range").addEventListener("change", event => {
if (busy || !state?.tion) return;
const value = Number(event.target.value);
state.tion.target_temp = value;
updateTemperatureVisual(value);
act(`/api/tion/temperature/${value}`, event.target);
});
$("#power-toggle").addEventListener("click", event => {
if (busy || !state?.tion) return;
const value = !state.tion.power;
state.tion.power = value;
drawToggle("#power-toggle", value);
setText("#power-detail", value ? "Устройство включено" : "Устройство выключено");
act(`/api/tion/power/${value ? "on" : "off"}`, event.currentTarget);
});
$("#heater-toggle").addEventListener("click", event => {
if (busy || !state?.tion) return;
const value = !state.tion.heater;
state.tion.heater = value;
drawToggle("#heater-toggle", value);
setText("#heater-detail", value ? "Автоматически" : "Выключен");
act(`/api/tion/heater/${value ? "on" : "off"}`, event.currentTarget);
});
$("#open-panel").addEventListener("click", () => window.open(panelUrl(themeMode()), "_blank", "noopener"));
$("#air-link").addEventListener("click", () => window.open(panelUrl(themeMode(), "air"), "_blank", "noopener"));
$("#schedule-link").addEventListener("click", () => window.open(panelUrl(themeMode(), "schedule"), "_blank", "noopener"));
refresh();
setInterval(() => !document.hidden && !busy && refresh(true), 3000);
-476
View File
@@ -1,476 +0,0 @@
import { api, airMeterPalette, airQuality, configureTheme, isDemo, modeInfo, numberOrDash, setRangeProgress, showToast } from "./api.js";
const $ = selector => document.querySelector(selector);
configureTheme($("#theme-button"));
let state = null;
let busy = false;
let scheduleDraft = null;
let activeTemplate = null;
const weekdays = [
["mon", "Понедельник"],
["tue", "Вторник"],
["wed", "Среда"],
["thu", "Четверг"],
["fri", "Пятница"],
["sat", "Суббота"],
["sun", "Воскресенье"],
];
const templateNames = { workday: "Будний", weekend: "Выходной" };
const clone = value => JSON.parse(JSON.stringify(value));
function templateLabel(name) {
return templateNames[name] || name;
}
if (isDemo) $("#demo-note").hidden = false;
function text(selector, value) { $(selector).textContent = value; }
function setPill(selector, label, tone) { const element = $(selector); element.textContent = label; element.className = `pill ${tone}`; }
function toggle(selector, active, label = "") {
const button = $(selector);
button.setAttribute("aria-pressed", String(Boolean(active)));
button.textContent = `${label}${label ? " " : ""}${active ? "ON" : "OFF"}`;
}
function setRange(selector, value) {
const input = $(selector);
if (Number.isFinite(Number(value))) input.value = value;
setRangeProgress(input);
}
function updateSpeedVisual(value) {
const speed = Math.max(1, Math.min(6, Number(value) || 1));
text("#speed-value", speed);
setRange("#speed-range", speed);
document.querySelectorAll(".speed-segments button").forEach((segment, index) => {
segment.classList.toggle("active", index < speed);
segment.setAttribute("aria-pressed", String(index + 1 === speed));
});
}
function updateTemperatureVisual(value) {
const temperature = Math.max(5, Math.min(30, Number(value) || 5));
text("#temperature-value", temperature);
setRange("#temperature-range", temperature);
}
function actionLabel(value) {
return ({ set: "Настройка режима", auto: "Автоматический режим", off: "Выключение" })[value] || "Точка расписания";
}
function renderAir(sensor, tion) {
const quality = airQuality(sensor.co2);
const airTone = ["good", "warn", "bad"].includes(quality.tone) ? quality.tone : "muted";
const airPalette = airMeterPalette(sensor.co2);
const airCard = $(".co2-card");
text("#co2", numberOrDash(sensor.co2));
text("#air-label", quality.label);
text("#air-advice", quality.tone === "good" ? "Проветривание работает нормально" : quality.tone === "warn" ? "Автоматика при необходимости повысит скорость" : quality.tone === "bad" ? "Рекомендуется усилить вентиляцию" : "Ожидаем показания датчика");
$("#air-label").className = `quality-chip ${airTone}`;
airCard.dataset.airTone = airTone;
airCard.style.setProperty("--air-color", airPalette.color);
airCard.style.setProperty("--air-glow", airPalette.glow);
$("#co2-progress").style.width = `${Math.max(0, Math.min(100, quality.pct))}%`;
setPill("#sensor-status", sensor.online ? "Online" : "Offline", sensor.online ? "good" : "bad");
text("#room-temp", numberOrDash(sensor.temperature ?? tion.in_temp, 1));
text("#humidity", numberOrDash(sensor.humidity));
text("#pm25", numberOrDash(sensor.pm25));
text("#pm10", numberOrDash(sensor.pm10));
const pm25 = Number(sensor.pm25);
const pm10 = Number(sensor.pm10);
text("#pm25-quality", Number.isFinite(pm25) ? (pm25 <= 15 ? "Отлично" : pm25 <= 35 ? "Норма" : "Повышено") : "—");
text("#pm10-quality", Number.isFinite(pm10) ? (pm10 <= 30 ? "Отлично" : pm10 <= 60 ? "Норма" : "Повышено") : "—");
}
function renderSchedule(status) {
const schedule = status.schedule || {};
const mode = modeInfo(status);
text("#current-time", schedule.current_time || status.tion?.device_time || "—");
text("#next-time", schedule.next_time || "—");
text("#current-action", actionLabel(schedule.current_action));
text("#next-action", actionLabel(schedule.next_action));
text("#mode-title", mode.label);
text("#mode-detail", mode.detail);
setPill("#schedule-state", schedule.paused ? "Пауза" : schedule.enabled ? "Активно" : "Выкл", schedule.paused ? "warn" : schedule.enabled ? "info" : "muted");
const headerMode = schedule.override_active && schedule.override_until_time
? `Ручной до ${schedule.override_until_time}`
: mode.label;
setPill("#mode-pill", headerMode, mode.tone);
$("#mode-banner").className = `mode-banner ${mode.tone === "info" ? "info" : mode.tone === "muted" ? "muted" : "warn"}`;
$("#auto-button").disabled = !schedule.available || (!schedule.override_active && !schedule.paused);
$("#pause-button strong").textContent = schedule.paused ? "Возобновить расписание" : "Пауза расписания";
$("#pause-button small").textContent = schedule.paused ? "Продолжить по расписанию" : "Временно приостановить";
}
function render(status) {
state = status;
const tion = status.tion || {};
const sensor = status.qingping || {};
setPill("#connection", status.online ? "Online" : "Offline", status.online ? "good" : "bad");
updateSpeedVisual(tion.fan_speed);
updateTemperatureVisual(tion.target_temp);
text("#speed-note", status.auto?.state === "active" && status.auto?.target_speed ? `AUTO выбрал скорость ${status.auto.target_speed}` : `Ступень ${numberOrDash(tion.fan_speed)} из 6`);
text("#temperature-note", tion.heating ? "Сейчас нагревает входящий воздух" : "Желаемая температура в помещении");
toggle("#power-toggle", tion.power);
toggle("#heater-toggle", tion.heater);
toggle("#sound-toggle", tion.sound, "Звук");
toggle("#light-toggle", tion.light, "Свет");
text("#power-caption", tion.power ? "Устройство включено" : "Устройство выключено");
text("#heater-caption", tion.heating ? "Сейчас нагревает воздух" : "Поддержание температуры");
$("#mode-outside").classList.toggle("active", tion.mode === "outside");
$("#mode-recirculation").classList.toggle("active", tion.mode === "recirculation");
text("#mode-name", tion.mode === "recirculation" ? "Рециркуляция" : "Приточная вентиляция");
text("#outside-temp", numberOrDash(tion.out_temp));
text("#filter-remain", numberOrDash(tion.filter_remain));
const filterPercent = Math.max(0, Math.min(100, Number(tion.filter_remain || 0) / 2));
$("#filter-progress").style.width = `${filterPercent}%`;
text("#filter-percent", `${Math.round(filterPercent)}%`);
text("#model", tion.model || "—");
text("#battery", numberOrDash(sensor.battery));
renderAir(sensor, tion);
renderSchedule(status);
text("#updated-at", `Обновлено ${new Date().toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", second: "2-digit" })}`);
}
async function refresh(silent = false) {
try { render(await api.status()); }
catch (error) {
setPill("#connection", "Ошибка связи", "bad");
if (!silent) showToast(error.message, true);
}
}
async function act(path, source) {
if (busy) return;
busy = true;
source?.setAttribute("disabled", "");
source?.setAttribute("aria-busy", "true");
try { await api.post(path); await refresh(true); }
catch (error) { showToast(error.message, true); await refresh(true); }
finally { busy = false; source?.removeAttribute("disabled"); source?.removeAttribute("aria-busy"); }
}
function stepped(kind, delta, source) {
if (busy) return;
const isSpeed = kind === "speed";
const current = Number(isSpeed ? state?.tion?.fan_speed : state?.tion?.target_temp);
const min = isSpeed ? 1 : 5;
const max = isSpeed ? 6 : 30;
const value = Math.min(max, Math.max(min, current + delta));
if (Number.isFinite(value) && value !== current) {
if (isSpeed) {
state.tion.fan_speed = value;
updateSpeedVisual(value);
} else {
state.tion.target_temp = value;
updateTemperatureVisual(value);
}
act(`/api/tion/${isSpeed ? "speed" : "temperature"}/${value}`, source);
}
}
function optionList(values, current, emptyLabel = "Не менять") {
const items = emptyLabel === null ? [] : [["", emptyLabel]];
items.push(...values);
return items.map(([value, label]) => `<option value="${value}"${String(current ?? "") === String(value) ? " selected" : ""}>${label}</option>`).join("");
}
function booleanSetting(value) {
return value === true ? "on" : value === false ? "off" : "";
}
function pointMarkup(point, index) {
const action = point?.action || {};
const type = action.type === "auto" ? "auto" : "set";
const speedOptions = Array.from({ length: 6 }, (_, item) => [String(item + 1), String(item + 1)]);
const booleanOptions = [["on", "Включить"], ["off", "Выключить"]];
return `
<article class="point-editor ${type}" data-index="${index}">
<div class="point-header">
<span class="point-number">${index + 1}</span>
<label>Время<input data-field="time" type="time" value="${point?.time || ""}" required></label>
<label class="point-action">Действие<select data-field="type"><option value="set"${type === "set" ? " selected" : ""}>Задать параметры</option><option value="auto"${type === "auto" ? " selected" : ""}>AUTO по воздуху</option></select></label>
<button class="remove-point" data-remove-point="${index}" type="button" aria-label="Удалить точку">×</button>
</div>
<div class="point-settings">
<label class="point-setting">Скорость<select data-setting="speed">${optionList(speedOptions, action.speed, "Не менять")}</select></label>
<label class="point-setting">Температура<input data-setting="target_temp" type="number" min="5" max="30" step="1" value="${action.target_temp ?? ""}" placeholder="—"></label>
<label class="point-setting" data-set-only>Питание<select data-setting="power">${optionList(booleanOptions, booleanSetting(action.power))}</select></label>
<label class="point-setting" data-set-only>Обогрев<select data-setting="heater">${optionList(booleanOptions, booleanSetting(action.heater))}</select></label>
<label class="point-setting" data-set-only>Воздух<select data-setting="mode">${optionList([["outside", "С улицы"], ["recirculation", "Рециркуляция"]], action.mode)}</select></label>
<label class="point-setting" data-set-only>Звук<select data-setting="sound">${optionList(booleanOptions, booleanSetting(action.sound))}</select></label>
<label class="point-setting" data-set-only>Подсветка<select data-setting="light">${optionList(booleanOptions, booleanSetting(action.light))}</select></label>
</div>
</article>`;
}
function readRenderedPoints(strict = false) {
const points = [...document.querySelectorAll(".point-editor")].map(card => {
const time = card.querySelector('[data-field="time"]').value;
const type = card.querySelector('[data-field="type"]').value;
const action = { type };
card.querySelectorAll("[data-setting]").forEach(input => {
const field = input.dataset.setting;
const raw = input.value;
if (raw === "" || (type === "auto" && !["speed", "target_temp"].includes(field))) return;
if (["speed", "target_temp"].includes(field)) action[field] = Number(raw);
else if (["power", "heater", "sound", "light"].includes(field)) action[field] = raw === "on";
else action[field] = raw;
});
return { time, action };
});
if (strict) validateTemplate(activeTemplate, points);
return points;
}
function validateTemplate(name, points) {
const label = templateLabel(name);
if (!Array.isArray(points) || !points.length) throw new Error(`Шаблон «${label}» не может быть пустым`);
const times = new Set();
points.forEach((point, index) => {
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(point.time || "")) throw new Error(`Проверьте время в точке ${index + 1} шаблона «${label}»`);
if (times.has(point.time)) throw new Error(`В шаблоне «${label}» время ${point.time} указано дважды`);
times.add(point.time);
const action = point.action || {};
if (!["set", "auto"].includes(action.type)) throw new Error(`Неизвестное действие в шаблоне «${label}»`);
if (action.speed !== undefined && (!Number.isInteger(action.speed) || action.speed < 1 || action.speed > 6)) throw new Error(`Скорость в шаблоне «${label}» должна быть от 1 до 6`);
if (action.target_temp !== undefined && (!Number.isInteger(action.target_temp) || action.target_temp < 5 || action.target_temp > 30)) throw new Error(`Температура в шаблоне «${label}» должна быть от 5 до 30°`);
if (action.type === "auto" && action.speed === undefined) throw new Error(`Для AUTO в шаблоне «${label}» укажите базовую скорость`);
if (action.type === "set" && Object.keys(action).length === 1) throw new Error(`В точке ${point.time} шаблона «${label}» не выбран ни один параметр`);
});
}
function validateScheduleDraft() {
const names = Object.keys(scheduleDraft?.templates || {});
if (!names.length) throw new Error("В расписании должен быть хотя бы один шаблон");
names.forEach(name => validateTemplate(name, scheduleDraft.templates[name]));
weekdays.forEach(([day, label]) => {
if (!names.includes(scheduleDraft.days?.[day])) throw new Error(`Для дня «${label}» не выбран шаблон`);
});
}
function commitActiveTemplate(strict = false) {
if (scheduleDraft && activeTemplate) scheduleDraft.templates[activeTemplate] = readRenderedPoints(strict);
}
function renderTemplateUsage() {
const usedBy = weekdays.filter(([day]) => scheduleDraft.days?.[day] === activeTemplate).map(([, label]) => label.toLowerCase());
text("#template-usage", usedBy.length ? `Используют: ${usedBy.join(", ")}` : "Пока не назначен ни одному дню");
}
function renderTemplateSelector() {
const select = $("#template-select");
select.replaceChildren(...Object.keys(scheduleDraft.templates).map(name => new Option(templateLabel(name), name, false, name === activeTemplate)));
$("#delete-template").disabled = Object.keys(scheduleDraft.templates).length <= 1;
}
function renderDayAssignments() {
const host = $("#day-assignments");
const templateNames = Object.keys(scheduleDraft.templates);
host.replaceChildren(...weekdays.map(([day, label]) => {
const wrapper = document.createElement("label");
wrapper.className = "day-assignment";
wrapper.textContent = label;
const select = document.createElement("select");
select.dataset.day = day;
select.replaceChildren(...templateNames.map(name => new Option(templateLabel(name), name, false, scheduleDraft.days?.[day] === name)));
wrapper.append(select);
return wrapper;
}));
}
function renderSchedulePoints() {
const points = scheduleDraft.templates[activeTemplate] || [];
$("#schedule-points").innerHTML = points.length
? points.map(pointMarkup).join("")
: '<div class="empty-points">В этом шаблоне пока нет точек</div>';
renderTemplateUsage();
}
function setEditorStatus(message = "", error = false) {
const status = $("#schedule-editor-status");
status.textContent = message;
status.classList.toggle("error", error);
}
async function openScheduleEditor() {
const source = $("#schedule-edit-button");
source.disabled = true;
source.setAttribute("aria-busy", "true");
try {
scheduleDraft = clone(await api.scheduleConfig());
const names = Object.keys(scheduleDraft.templates || {});
if (!names.length) throw new Error("В расписании нет шаблонов");
const dayKeys = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
activeTemplate = scheduleDraft.days?.[dayKeys[new Date().getDay()]] || names[0];
$("#schedule-enabled").checked = scheduleDraft.enabled !== false;
renderTemplateSelector();
renderDayAssignments();
renderSchedulePoints();
setEditorStatus();
$("#schedule-dialog").showModal();
} catch (error) {
showToast(`Не удалось открыть редактор: ${error.message}`, true);
} finally {
source.disabled = false;
source.removeAttribute("aria-busy");
}
}
function closeScheduleEditor() {
$("#schedule-dialog").close();
scheduleDraft = null;
activeTemplate = null;
}
async function saveScheduleEditor(event) {
event.preventDefault();
if (!scheduleDraft) return;
const saveButton = $("#schedule-save-button");
try {
commitActiveTemplate(true);
scheduleDraft.enabled = $("#schedule-enabled").checked;
validateScheduleDraft();
Object.values(scheduleDraft.templates).forEach(points => points.sort((left, right) => left.time.localeCompare(right.time)));
setEditorStatus("Сохраняем…");
saveButton.disabled = true;
saveButton.setAttribute("aria-busy", "true");
const result = await api.saveScheduleConfig(scheduleDraft);
$("#schedule-dialog").close();
scheduleDraft = null;
activeTemplate = null;
showToast(result.restart_required ? "Расписание сохранено. Перезапустите сервис для применения" : "Расписание сохранено и применено");
await refresh(true);
} catch (error) {
setEditorStatus(error.message, true);
} finally {
saveButton.disabled = false;
saveButton.removeAttribute("aria-busy");
}
}
document.querySelectorAll("[data-step]").forEach(button => button.addEventListener("click", () => stepped(button.dataset.step, Number(button.dataset.delta), button)));
document.querySelectorAll(".speed-segments button").forEach(button => button.addEventListener("click", () => {
if (busy || !state?.tion) return;
const value = Number(button.dataset.speed);
state.tion.fan_speed = value;
updateSpeedVisual(value);
act(`/api/tion/speed/${value}`, button);
}));
$("#speed-range").addEventListener("input", event => updateSpeedVisual(event.target.value));
$("#speed-range").addEventListener("change", event => act(`/api/tion/speed/${event.target.value}`, event.target));
$("#temperature-range").addEventListener("input", event => { setRangeProgress(event.target); text("#temperature-value", event.target.value); });
$("#temperature-range").addEventListener("change", event => act(`/api/tion/temperature/${event.target.value}`, event.target));
$("#power-toggle").addEventListener("click", event => act(`/api/tion/power/${state?.tion?.power ? "off" : "on"}`, event.currentTarget));
$("#heater-toggle").addEventListener("click", event => act(`/api/tion/heater/${state?.tion?.heater ? "off" : "on"}`, event.currentTarget));
$("#sound-toggle").addEventListener("click", event => act(`/api/tion/sound/${state?.tion?.sound ? "off" : "on"}`, event.currentTarget));
$("#light-toggle").addEventListener("click", event => act(`/api/tion/light/${state?.tion?.light ? "off" : "on"}`, event.currentTarget));
$("#mode-outside").addEventListener("click", event => act("/api/tion/mode/outside", event.currentTarget));
$("#mode-recirculation").addEventListener("click", event => act("/api/tion/mode/recirculation", event.currentTarget));
$("#auto-button").addEventListener("click", event => act(state?.schedule?.paused ? "/api/schedule/resume" : "/api/schedule/override/clear", event.currentTarget));
$("#pause-button").addEventListener("click", event => act(state?.schedule?.paused ? "/api/schedule/resume" : "/api/schedule/pause", event.currentTarget));
$("#refresh-button").addEventListener("click", event => { event.currentTarget.animate([{ transform: "rotate(0)" }, { transform: "rotate(360deg)" }], { duration: 450 }); refresh(); });
$("#schedule-edit-button").addEventListener("click", openScheduleEditor);
$("#schedule-close-button").addEventListener("click", closeScheduleEditor);
$("#schedule-cancel-button").addEventListener("click", closeScheduleEditor);
$("#schedule-form").addEventListener("submit", saveScheduleEditor);
$("#schedule-dialog").addEventListener("close", () => { scheduleDraft = null; activeTemplate = null; });
$("#template-select").addEventListener("change", event => {
if (!scheduleDraft) return;
commitActiveTemplate(false);
activeTemplate = event.target.value;
renderSchedulePoints();
});
$("#duplicate-template").addEventListener("click", () => {
if (!scheduleDraft || !activeTemplate) return;
commitActiveTemplate(false);
const base = `${activeTemplate}-copy`;
let name = base;
let suffix = 2;
while (scheduleDraft.templates[name]) name = `${base}-${suffix++}`;
scheduleDraft.templates[name] = clone(scheduleDraft.templates[activeTemplate]);
activeTemplate = name;
renderTemplateSelector();
renderDayAssignments();
renderSchedulePoints();
setEditorStatus(`Создан шаблон «${templateLabel(name)}». Назначьте его нужным дням`);
});
$("#delete-template").addEventListener("click", () => {
if (!scheduleDraft || Object.keys(scheduleDraft.templates).length <= 1) return;
if (!window.confirm(`Удалить шаблон «${templateLabel(activeTemplate)}»?`)) return;
const removed = activeTemplate;
delete scheduleDraft.templates[removed];
activeTemplate = Object.keys(scheduleDraft.templates)[0];
weekdays.forEach(([day]) => {
if (scheduleDraft.days[day] === removed) scheduleDraft.days[day] = activeTemplate;
});
renderTemplateSelector();
renderDayAssignments();
renderSchedulePoints();
setEditorStatus(`Шаблон «${templateLabel(removed)}» удалён`);
});
$("#day-assignments").addEventListener("change", event => {
const select = event.target.closest("[data-day]");
if (!select || !scheduleDraft) return;
scheduleDraft.days[select.dataset.day] = select.value;
renderTemplateUsage();
});
$("#schedule-points").addEventListener("change", event => {
if (event.target.dataset.field !== "type") return;
const card = event.target.closest(".point-editor");
const isAuto = event.target.value === "auto";
card.classList.toggle("auto", isAuto);
card.classList.toggle("set", !isAuto);
const speed = card.querySelector('[data-setting="speed"]');
if (isAuto && !speed.value) speed.value = "2";
});
$("#schedule-points").addEventListener("click", event => {
const button = event.target.closest("[data-remove-point]");
if (!button || !scheduleDraft) return;
commitActiveTemplate(false);
scheduleDraft.templates[activeTemplate].splice(Number(button.dataset.removePoint), 1);
renderSchedulePoints();
});
$("#add-schedule-point").addEventListener("click", () => {
if (!scheduleDraft) return;
commitActiveTemplate(false);
const points = scheduleDraft.templates[activeTemplate];
const used = new Set(points.map(point => point.time));
const existingTimes = points.map(point => {
const [hours, minute] = String(point.time || "").split(":").map(Number);
return hours * 60 + minute;
}).filter(Number.isFinite);
let minutes = existingTimes.length ? (Math.max(...existingTimes) + 60) % 1440 : 8 * 60;
for (let attempt = 0; attempt < 48; attempt += 1) {
const candidate = `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
if (!used.has(candidate)) {
points.push({ time: candidate, action: { type: "set", speed: 2 } });
break;
}
minutes = (minutes + 30) % 1440;
}
points.sort((left, right) => left.time.localeCompare(right.time));
renderSchedulePoints();
$("#schedule-points .point-editor:last-of-type")?.scrollIntoView({ behavior: "smooth", block: "nearest" });
});
setRangeProgress($("#speed-range"));
setRangeProgress($("#temperature-range"));
refresh();
setInterval(() => !document.hidden && !busy && refresh(true), 3000);
-129
View File
@@ -1,129 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Tion 4S — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/widget.css">
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
<main class="widget" aria-live="polite">
<header class="widget-header">
<div class="identity">
<span class="brand-icon" aria-hidden="true">
<svg class="ui-icon"><use href="/ui/static/assets/icons.svg#wind"></use></svg>
</span>
<span class="identity-copy">
<span class="title-row"><h1>Tion 4S</h1><span id="connection" class="pill muted">Загрузка</span></span>
<small>Приточная вентиляция</small>
</span>
</div>
<button id="theme-button" class="theme-button" type="button" title="Сменить тему">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
</button>
<div class="status-row">
<span id="mode-pill" class="pill muted">—</span>
<span id="mode-detail" class="mode-detail">Загрузка состояния</span>
</div>
</header>
<section class="widget-tile control-card speed-card" aria-labelledby="speed-title">
<div class="card-title">
<svg class="ui-icon feature-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg>
<span><h2 id="speed-title">Скорость вентиляции</h2><p id="speed-note">Ступень — из 6</p></span>
</div>
<div class="hero-control">
<button class="hero-step" data-step="speed" data-delta="-1" type="button" aria-label="Уменьшить скорость">−</button>
<strong id="speed" class="hero-value value skeleton">0</strong>
<button class="hero-step primary" data-step="speed" data-delta="1" type="button" aria-label="Увеличить скорость">+</button>
</div>
<div id="speed-segments" class="speed-segments" role="group" aria-label="Выбор скорости">
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
<button type="button" data-speed="5" aria-label="Скорость 5"></button>
<button type="button" data-speed="6" aria-label="Скорость 6"></button>
</div>
<div class="scale-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span></div>
</section>
<section class="widget-tile control-card temperature-card" aria-labelledby="temperature-title">
<div class="card-title">
<svg class="ui-icon feature-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#thermometer"></use></svg>
<span><h2 id="temperature-title">Целевая температура</h2><p id="heating-note">Желаемая температура воздуха</p></span>
</div>
<div class="hero-control">
<button class="hero-step" data-step="temperature" data-delta="-1" type="button" aria-label="Уменьшить температуру">−</button>
<strong class="hero-value value"><span id="target-temp" class="skeleton">00</span>°</strong>
<button class="hero-step primary" data-step="temperature" data-delta="1" type="button" aria-label="Увеличить температуру">+</button>
</div>
<input id="temperature-range" class="temperature-range" type="range" min="5" max="30" step="1" value="21" aria-label="Целевая температура">
<div class="temperature-labels" aria-hidden="true"><span>5°</span><span>15°</span><span>20°</span><span>25°</span><span>30°</span></div>
</section>
<section class="switch-grid" aria-label="Питание и обогрев">
<article class="widget-tile switch-card power-card">
<div class="switch-title">
<svg class="ui-icon switch-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg>
<span><h2>Питание</h2><small id="power-detail">Устройство выключено</small></span>
</div>
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article class="widget-tile switch-card heater-card">
<div class="switch-title">
<svg class="ui-icon switch-icon orange" aria-hidden="true"><use href="/ui/static/assets/icons.svg#heat"></use></svg>
<span><h2>Обогрев</h2><small id="heater-detail">Выключен</small></span>
</div>
<button id="heater-toggle" class="glass-switch orange" type="button" aria-pressed="false">OFF</button>
</article>
</section>
<section class="widget-tile info-card air-card" data-air-tone="muted" aria-labelledby="air-title">
<header class="section-title">
<span><svg class="ui-icon section-icon leaf" aria-hidden="true"><use href="/ui/static/assets/icons.svg#leaf"></use></svg><h2 id="air-title">Воздух в комнате</h2></span>
<button id="air-link" class="open-section" type="button" aria-label="Открыть показатели воздуха в панели">↗</button>
</header>
<div class="co2-summary">
<span class="co2-label">CO₂</span>
<strong><span id="co2" class="value">—</span> <small>ppm</small></strong>
<span id="air-label" class="quality-chip muted">Нет данных</span>
</div>
<div class="co2-meter" aria-hidden="true"><i id="co2-progress"></i></div>
<div class="meter-labels" aria-hidden="true"><span>400</span><span>800</span><span>1200</span><span>2000</span></div>
<div class="mini-metrics">
<div class="mini-metric">
<svg class="ui-icon metric-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#thermometer"></use></svg>
<span><small>Температура</small><strong><span id="room-temp" class="value">—</span>°</strong></span>
</div>
<div class="mini-metric">
<svg class="ui-icon metric-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#drop"></use></svg>
<span><small>Влажность</small><strong><span id="humidity" class="value">—</span>%</strong></span>
</div>
</div>
</section>
<section class="widget-tile info-card schedule-card" aria-labelledby="schedule-title">
<header class="section-title">
<span><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg><h2 id="schedule-title">Расписание</h2></span>
<button id="schedule-link" class="open-section" type="button" aria-label="Открыть расписание в панели">↗</button>
</header>
<div class="schedule-times">
<span><small>Сейчас</small><strong id="current-time" class="value">—</strong></span>
<i aria-hidden="true"></i>
<span><small>Следующая точка</small><strong id="next-time" class="value">—</strong></span>
</div>
</section>
<button id="open-panel" class="open-panel" type="button">
<svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#wind"></use></svg>
<span>Открыть полную панель</span><b aria-hidden="true">↗</b>
</button>
<span id="demo-note" class="demo-note" hidden>Демонстрационный режим — команды не отправляются устройству</span>
</main>
<script type="module" src="/ui/static/js/tion-widget.js"></script>
</body>
</html>
-163
View File
@@ -1,163 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Tion 4S — панель управления</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/panel.css">
</head>
<body>
<div class="ambient"></div>
<main class="climate-panel glass" aria-live="polite">
<header class="panel-header">
<div class="identity">
<h1>Tion 4S</h1>
<span id="connection" class="pill muted">Загрузка</span>
<span id="mode-pill" class="pill muted">—</span>
</div>
<div class="header-tools">
<div class="ventilation-badge glass-tile">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M3 7h9a3 3 0 1 0-2.6-4.5M3 12h15a3 3 0 1 1-2.7 4.3M3 17h7" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/></svg>
<span><strong>Приточная вентиляция</strong><small>Чистый воздух для вашего дома</small></span>
</div>
<button id="refresh-button" class="icon-button" type="button" title="Обновить данные">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M20 11a8 8 0 1 0-2.34 5.66M20 5v6h-6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<button id="theme-button" class="icon-button" type="button" title="Сменить тему">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.64 5.64l1.42 1.42m9.88 9.88 1.42 1.42m0-12.72-1.42 1.42M7.06 16.94l-1.42 1.42" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="12" cy="12" r="4" stroke="currentColor" stroke-width="1.8"/></svg>
</button>
</div>
</header>
<section class="primary-controls" aria-label="Основное управление">
<article class="control-card glass-tile speed-card">
<div class="card-title"><svg class="ui-icon feature-icon fan-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#fan"></use></svg><span><h2>Скорость вентиляции</h2><p id="speed-note">Текущая ступень вентилятора</p></span></div>
<div class="hero-control">
<button class="hero-step" data-step="speed" data-delta="-1" type="button" aria-label="Уменьшить скорость">−</button>
<strong id="speed-value" class="hero-value">—</strong>
<button class="hero-step primary" data-step="speed" data-delta="1" type="button" aria-label="Увеличить скорость">+</button>
</div>
<input id="speed-range" class="range speed-range" type="range" min="1" max="6" step="1" value="3" aria-label="Скорость вентилятора">
<div class="speed-segments" aria-label="Выбор скорости">
<button type="button" data-speed="1" aria-label="Скорость 1"></button>
<button type="button" data-speed="2" aria-label="Скорость 2"></button>
<button type="button" data-speed="3" aria-label="Скорость 3"></button>
<button type="button" data-speed="4" aria-label="Скорость 4"></button>
<button type="button" data-speed="5" aria-label="Скорость 5"></button>
<button type="button" data-speed="6" aria-label="Скорость 6"></button>
</div>
<div class="speed-labels" aria-hidden="true"><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span></div>
</article>
<article class="control-card glass-tile temperature-card">
<div class="card-title"><svg class="ui-icon feature-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#thermometer"></use></svg><span><h2>Цель (температура)</h2><p id="temperature-note">Желаемая температура воздуха</p></span></div>
<div class="hero-control">
<button class="hero-step" data-step="temperature" data-delta="-1" type="button" aria-label="Уменьшить температуру">−</button>
<strong class="hero-value"><span id="temperature-value">—</span>°</strong>
<button class="hero-step primary" data-step="temperature" data-delta="1" type="button" aria-label="Увеличить температуру">+</button>
</div>
<input id="temperature-range" class="range temperature-range" type="range" min="5" max="30" step="1" value="21" aria-label="Целевая температура">
<div class="temperature-labels" aria-hidden="true"><span>5°</span><span>10°</span><span>15°</span><span>20°</span><span>25°</span><span>30°</span></div>
</article>
<article class="switch-card glass-tile power-card">
<div class="card-title compact"><svg class="ui-icon feature-icon green" aria-hidden="true"><use href="/ui/static/assets/icons.svg#power"></use></svg><span><h2>Питание</h2><p id="power-caption">Устройство выключено</p></span></div>
<button id="power-toggle" class="glass-switch green" type="button" aria-pressed="false">OFF</button>
</article>
<article class="switch-card glass-tile heater-card">
<div class="card-title compact"><svg class="ui-icon feature-icon orange" aria-hidden="true"><use href="/ui/static/assets/icons.svg#heat"></use></svg><span><h2>Обогрев</h2><p id="heater-caption">Поддержание температуры</p></span></div>
<button id="heater-toggle" class="glass-switch orange" type="button" aria-pressed="false">OFF</button>
</article>
</section>
<section id="air" class="content-section glass-section" aria-labelledby="air-title">
<div class="section-title">
<div><svg class="ui-icon section-icon leaf" aria-hidden="true"><use href="/ui/static/assets/icons.svg#leaf"></use></svg><h2 id="air-title">Показатели воздуха</h2></div>
<span id="sensor-status" class="pill muted">Датчик</span>
<span id="updated-at" class="updated">Обновление…</span>
</div>
<div class="air-grid">
<article class="metric-card co2-card glass-tile" data-air-tone="muted">
<div class="metric-head"><span>CO₂</span><span id="air-label" class="quality-chip muted">Нет данных</span></div>
<strong><span id="co2">—</span> <small>ppm</small></strong>
<p id="air-advice">Ожидаем показания датчика</p>
<div class="meter co2-meter"><i id="co2-progress"></i></div>
<div class="meter-labels"><span>400</span><span>800</span><span>1200</span><span>2000</span></div>
</article>
<article class="metric-card glass-tile"><div class="metric-heading"><svg class="ui-icon metric-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#thermometer"></use></svg><span>Температура<br>в помещении</span></div><strong><span id="room-temp">—</span>°</strong></article>
<article class="metric-card glass-tile"><div class="metric-heading"><svg class="ui-icon metric-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#drop"></use></svg><span>Влажность</span></div><strong><span id="humidity">—</span>%</strong></article>
<article class="metric-card glass-tile"><div class="metric-heading"><svg class="ui-icon metric-icon particles" aria-hidden="true"><use href="/ui/static/assets/icons.svg#particles"></use></svg><span>PM2.5</span></div><strong><span id="pm25">—</span> <small>мкг/м³</small></strong><span id="pm25-quality" class="quality-chip small">—</span></article>
<article class="metric-card glass-tile"><div class="metric-heading"><svg class="ui-icon metric-icon particles" aria-hidden="true"><use href="/ui/static/assets/icons.svg#particles"></use></svg><span>PM10</span></div><strong><span id="pm10">—</span> <small>мкг/м³</small></strong><span id="pm10-quality" class="quality-chip small">—</span></article>
<article class="metric-card filter-card glass-tile"><div class="metric-heading"><svg class="ui-icon metric-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#filter"></use></svg><span>Фильтр</span></div><strong><span id="filter-remain">—</span> <small>дней осталось</small></strong><div class="filter-line"><div class="meter filter-meter"><i id="filter-progress"></i></div><span id="filter-percent">—</span></div></article>
</div>
</section>
<div class="bottom-grid">
<section id="schedule" class="content-section glass-section schedule-section" aria-labelledby="schedule-title">
<div class="section-title"><div><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg><h2 id="schedule-title">Расписание</h2></div><div class="schedule-title-tools"><button id="schedule-edit-button" class="schedule-edit-button" type="button"><svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#settings"></use></svg><span>Изменить</span></button><span id="schedule-state" class="pill muted">—</span></div></div>
<div class="schedule-layout">
<div class="schedule-times glass-tile">
<div><span>Текущая точка</span><strong id="current-time">—</strong><small id="current-action">Нет данных</small></div><i></i><div><span>Следующая точка</span><strong id="next-time">—</strong><small id="next-action">Нет данных</small></div>
</div>
<div class="schedule-buttons">
<button id="auto-button" class="schedule-button auto" type="button"><svg class="ui-icon action-symbol" aria-hidden="true"><use href="/ui/static/assets/icons.svg#auto"></use></svg><span><strong>Вернуться в AUTO</strong><small>Отменить ручной режим</small></span></button>
<button id="pause-button" class="schedule-button pause" type="button"><svg class="ui-icon action-symbol" aria-hidden="true"><use href="/ui/static/assets/icons.svg#pause"></use></svg><span><strong>Пауза расписания</strong><small>Временно приостановить</small></span></button>
</div>
</div>
<div id="mode-banner" class="mode-banner warn"><span id="mode-title">Загрузка состояния</span><small id="mode-detail">Пожалуйста, подождите</small></div>
</section>
<section class="content-section glass-section extras-section" aria-labelledby="extras-title">
<div class="section-title"><div><svg class="ui-icon section-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#settings"></use></svg><h2 id="extras-title">Дополнительно</h2></div></div>
<div class="extras-grid">
<article class="extra-card glass-tile"><svg class="ui-icon extra-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#home"></use></svg><span><small>На улице</small><strong><span id="outside-temp">—</span>°</strong></span></article>
<article class="extra-card mode-card glass-tile">
<svg class="ui-icon extra-icon wind" aria-hidden="true"><use href="/ui/static/assets/icons.svg#wind"></use></svg><span><small>Режим работы</small><strong id="mode-name">Приточная вентиляция</strong><em>Подача и очистка воздуха</em></span>
<div class="segments" role="group" aria-label="Режим забора воздуха"><button id="mode-outside" class="segment" type="button">С улицы</button><button id="mode-recirculation" class="segment" type="button">Рециркуляция</button></div>
</article>
</div>
<div class="micro-settings">
<span>Модель <strong id="model">—</strong></span><span>Батарея Qingping <strong><span id="battery">—</span>%</strong></span>
<button id="sound-toggle" class="micro-toggle" type="button" aria-pressed="false">Звук OFF</button><button id="light-toggle" class="micro-toggle" type="button" aria-pressed="false">Свет OFF</button>
</div>
</section>
</div>
<span id="demo-note" class="demo-note" hidden>Демонстрационный режим — команды не отправляются устройству</span>
</main>
<dialog id="schedule-dialog" class="schedule-dialog" aria-labelledby="schedule-dialog-title">
<form id="schedule-form" class="schedule-editor">
<header class="editor-header">
<span class="editor-heading"><svg class="ui-icon" aria-hidden="true"><use href="/ui/static/assets/icons.svg#clock"></use></svg><span><h2 id="schedule-dialog-title">Редактор расписания</h2><small>Изменения сохраняются в config/schedule.yaml</small></span></span>
<button id="schedule-close-button" class="editor-close" type="button" aria-label="Закрыть редактор">×</button>
</header>
<div class="editor-scroll">
<label class="schedule-enabled"><input id="schedule-enabled" type="checkbox"><span><strong>Расписание включено</strong><small>Если выключить, автоматические точки применяться не будут</small></span></label>
<section class="editor-section" aria-labelledby="days-title">
<div class="editor-section-title"><span><h3 id="days-title">Дни недели</h3><small>Назначьте каждому дню один из шаблонов</small></span></div>
<div id="day-assignments" class="day-assignments"></div>
</section>
<section class="editor-section" aria-labelledby="points-title">
<div class="editor-section-title template-toolbar">
<span><h3 id="points-title">Точки расписания</h3><small id="template-usage">Выберите шаблон</small></span>
<label>Шаблон<select id="template-select"></select></label>
<span class="template-actions"><button id="duplicate-template" type="button">Дублировать</button><button id="delete-template" type="button">Удалить</button></span>
</div>
<div id="schedule-points" class="schedule-points"></div>
<button id="add-schedule-point" class="add-schedule-point" type="button">+ Добавить точку</button>
</section>
</div>
<footer class="editor-footer">
<span id="schedule-editor-status" class="editor-status" role="status"></span>
<button id="schedule-cancel-button" class="editor-button secondary" type="button">Отмена</button>
<button id="schedule-save-button" class="editor-button primary" type="submit">Сохранить расписание</button>
</footer>
</form>
</dialog>
<script type="module" src="/ui/static/js/tion.js"></script>
</body>
</html>