work: функционал для работы с вятяжкой

* Добавил полный функционал управления elica через esp32 по MQTT
* Добавил в прошивку принудительную блокировку внешнего винтелятора при работающей вытяжке
* Добавил веб-панели для управления вытяжкой
This commit is contained in:
2026-09-26 23:59:01 +03:00
parent 3b3c7a3f13
commit bf832ac86b
12 changed files with 631 additions and 52 deletions
+3 -3
View File
@@ -1,8 +1,8 @@
[version]
major = 1
minor = 3
minor = 4
patch = 0
[build]
date = "2026-09-20"
time = "14:17:42"
date = "2026-09-26"
time = "23:54:18"
+124 -7
View File
@@ -10,12 +10,15 @@ from fastapi.staticfiles import StaticFiles
from pathlib import Path as FilePath
from app.qingping.service import QingpingService
from app.metrics import PrometheusMetricsService
from app.elica import ElicaConfig, ElicaController, ElicaService
from app.my_dataclasses import (
TION_MAC,
QINGPING_MAC,
QINGPING_MQTT_HOST,
QINGPING_MQTT_PORT,
ELICA_MQTT_HOST,
ELICA_MQTT_PORT,
MIN_FAN_SPEED,
MAX_FAN_SPEED,
MIN_TARGET_TEMP,
@@ -87,6 +90,14 @@ qingping_service = QingpingService(
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_load_error: str | None = None
@@ -109,6 +120,7 @@ async def lifespan(app: FastAPI):
await service.start()
await qingping_service.start()
await elica_service.start()
try:
try:
@@ -200,6 +212,7 @@ async def lifespan(app: FastAPI):
if schedule_service is not None:
await schedule_service.stop()
await elica_service.stop()
await qingping_service.stop()
await service.stop()
@@ -225,22 +238,55 @@ app.mount(
@app.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/ui/panel")
return RedirectResponse(url="/ui/tion")
@app.get("/ui", include_in_schema=False)
async def ui_root():
return RedirectResponse(url="/ui/panel")
return RedirectResponse(url="/ui/tion")
# Canonical UI routes. Device-specific names make room for additional
# controllers/widgets without overloading generic "panel"/"widget" names.
@app.get("/ui/tion", include_in_schema=False)
async def ui_tion():
return FileResponse(WEB_ROOT / "tion.html")
@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():
return FileResponse(WEB_ROOT / "widget.html")
async def ui_widget_legacy():
return RedirectResponse(url="/ui/tion-widget")
@app.get("/ui/panel", include_in_schema=False)
async def ui_panel():
return FileResponse(WEB_ROOT / "panel.html")
@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)
@@ -291,9 +337,31 @@ def get_status() -> dict:
"qingping": qingping_service.status(),
"elica": get_elica_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:
if (
@@ -531,6 +599,55 @@ async def 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
# ----------------------------------------------------------------------
+14
View File
@@ -0,0 +1,14 @@
from .config import ElicaConfig
from .controller import ElicaController
from .models import ElicaLogicalState, ElicaPanelState, ElicaState, ExternalFanState
from .service import ElicaService
__all__ = [
"ElicaConfig",
"ElicaController",
"ElicaLogicalState",
"ElicaPanelState",
"ElicaService",
"ElicaState",
"ExternalFanState",
]
+7
View File
@@ -19,6 +19,13 @@ class ElicaConfig:
light_relay: int = 3
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
+96 -29
View File
@@ -19,14 +19,17 @@ class ElicaController:
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:
@@ -77,7 +80,7 @@ class ElicaController:
async def _power_on_locked(self) -> ElicaLogicalState:
"""Включает вытяжку. Вызывается только под self._lock."""
self._ensure_ready()
await self._ensure_ready()
state = self.state
if state.power:
@@ -92,7 +95,7 @@ class ElicaController:
async def _power_off_locked(self) -> ElicaLogicalState:
"""Выключает вытяжку. Вызывается только под self._lock."""
self._ensure_ready()
await self._ensure_ready()
state = self.state
if not state.power:
@@ -122,55 +125,72 @@ class ElicaController:
# ------------------------------------------------------------------
async def set_speed(self, speed: int) -> ElicaLogicalState:
"""
Устанавливает скорость 1-4.
"""Устанавливает скорость 1-4 последовательными нажатиями Speed.
Контроллер нажимает кнопку 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:
self._ensure_ready()
await self._ensure_ready()
state = self.state
if not state.power:
state = await self._power_on_locked()
# У 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",
)
# После включения power LED может обновиться раньше speed LED.
if state.speed == 0:
# После физического отпускания кнопки 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",
)
if state.speed == speed:
return state
current_speed = state.speed
presses = (speed - current_speed) % 4
# Не предполагаем конкретный порядок скоростей.
# После каждого нажатия смотрим, что реально получилось.
for _ in range(4):
previous_speed = state.speed
for _ in range(presses):
expected_speed = current_speed % 4 + 1
await self._service.press_speed()
state = await self._wait_state(
lambda value: (
value.power
and 1 <= value.speed <= 4
and value.speed != previous_speed
lambda value, expected=expected_speed: (
value.power and value.speed == expected
),
"speed change",
f"speed {expected_speed}",
)
if state.speed == speed:
return state
current_speed = expected_speed
raise RuntimeError(
f"Unable to set Elica speed to {speed}; "
f"current speed: {state.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
@@ -183,7 +203,7 @@ class ElicaController:
Состояние подтверждается по миганию индикатора скорости.
"""
async with self._lock:
self._ensure_ready()
await self._ensure_ready()
state = self.state
if not enabled and not state.power:
@@ -228,9 +248,56 @@ class ElicaController:
поэтому light_on/light_off реализовать достоверно нельзя.
"""
async with self._lock:
self._ensure_ready()
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)
# ------------------------------------------------------------------
# Синхронизация начального состояния
# ------------------------------------------------------------------
+15 -3
View File
@@ -20,8 +20,9 @@ class ElicaState:
False, False, False, False,
False, False, False, False,
)
# Фактические состояния IN1-IN8,
# полученные от ESPHome через MQTT.
# Состояния оптовходов IN1-IN8, полученные от ESPHome через MQTT.
# True означает электрически активный вход платы. Для линий
# индикаторов Elica это НЕ равно "LED включён": Elica активна LOW.
input_states: tuple[bool, ...] = (
False, False, False, False,
False, False, False, False,
@@ -55,4 +56,15 @@ class ElicaLogicalState:
timer: bool = False
def to_dict(self) -> dict:
return asdict(self)
return asdict(self)
@dataclass(frozen=True, slots=True)
class ExternalFanState:
available: bool = False
on: bool | None = None
relay: int = 5
relay_on: bool | None = None
normally_closed: bool = True
def to_dict(self) -> dict:
return asdict(self)
+93 -8
View File
@@ -5,7 +5,7 @@ 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
from .models import ElicaState, ElicaPanelState, ElicaLogicalState, ExternalFanState
logger = logging.getLogger(__name__)
@@ -32,7 +32,8 @@ class ElicaService:
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:
@@ -111,6 +112,7 @@ class ElicaService:
logger.info("ESP32 elica MQTT connected")
self._received_input_mask = 0
self._received_relay_mask = 0
# ------------------------------------------------------------------
# Подписки сервиса
@@ -143,6 +145,7 @@ class ElicaService:
logger.info("ESP32 Elica MQTT disconnected: %s",reason_code)
self._received_input_mask = 0
self._received_relay_mask = 0
self._state = replace(
self._state,
@@ -254,6 +257,7 @@ class ElicaService:
relay_states=tuple(relay_states),
last_message_at=datetime.now(timezone.utc),
)
self._received_relay_mask |= 1 << (relay - 1)
# ------------------------------------------------------------------
# Input state
# ------------------------------------------------------------------
@@ -316,6 +320,12 @@ class ElicaService:
def _update_panel_tracker(self) -> None:
"""Отслеживает скорость и мигание индикатора таймера."""
# Пока не получили все пять входов панели, не пытаемся
# интерпретировать их начальные значения. После инверсии Elica
# значение False по умолчанию выглядело бы как включённый LED.
if not self.feedback_ready:
return
panel = self.panel_state
now = time.monotonic()
@@ -356,6 +366,9 @@ class ElicaService:
@property
def logical_state(self) -> ElicaLogicalState:
"""Возвращает интерпретированное состояние вытяжки Elica."""
if not self.feedback_ready:
return ElicaLogicalState()
panel = self.panel_state
now = time.monotonic()
@@ -455,6 +468,43 @@ class ElicaService:
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
# ------------------------------------------------------------------
@@ -465,6 +515,7 @@ class ElicaService:
"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(),
@@ -497,6 +548,32 @@ class ElicaService:
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,
@@ -545,15 +622,23 @@ class ElicaService:
# ------------------------------------------------------------------
@property
def panel_state(self) -> ElicaPanelState:
"""Возвращает текущее физическое состояние индикаторов Elica."""
"""Возвращает фактическое состояние светодиодов панели Elica.
Входы обратной связи имеют обратную полярность относительно LED:
высокий уровень на IN означает, что соответствующий индикатор
Elica погашен, низкий уровень — что индикатор горит.
MQTT-состояние входа поэтому инвертируем именно здесь, на границе
между электрическим состоянием IN и логическим состоянием панели.
"""
return ElicaPanelState(
speed_leds=(
self.input_state(self._config.speed_1_input),
self.input_state(self._config.speed_2_input),
self.input_state(self._config.speed_3_input),
self.input_state(self._config.speed_4_input),
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=self.input_state(self._config.power_input),
power_led=not self.input_state(self._config.power_input),
)
@property
+4
View File
@@ -13,6 +13,10 @@ QINGPING_MAC = "CCB5D131BA93"
QINGPING_MQTT_HOST = "192.168.7.3"
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
MAX_FAN_SPEED = 6
+71 -1
View File
@@ -80,6 +80,18 @@ globals:
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
@@ -114,12 +126,53 @@ interval:
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"
@@ -177,6 +230,15 @@ switch:
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
@@ -186,7 +248,15 @@ switch:
- lambda: id(relay_state) |= 0x10;
- script.execute: write_relays
turn_off_action:
- lambda: id(relay_state) &= ~0x10;
- lambda: |-
// Use the same raw IN5 polarity as the interlock above:
// raw bit 1 means the Elica Power LED is ON.
const bool elica_power_on = (id(input_state) & 0x40) != 0;
if (elica_power_on) {
id(relay_state) |= 0x10;
} else {
id(relay_state) &= ~0x10;
}
- script.execute: write_relays
command_topic: "elica/relay/5/set"
state_topic: "elica/relay/5/state"
+85
View File
@@ -0,0 +1,85 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Elica — виджет</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/widget.css">
<link rel="stylesheet" href="/ui/static/css/exhaust-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/exhaust-widget.js"></script>
</body>
</html>
+118
View File
@@ -0,0 +1,118 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Elica — управление вытяжкой</title>
<link rel="stylesheet" href="/ui/static/css/base.css">
<link rel="stylesheet" href="/ui/static/css/panel.css">
<link rel="stylesheet" href="/ui/static/css/exhaust.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/panel" 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/exhaust.js"></script>
</body>
</html>
+1 -1
View File
@@ -295,7 +295,7 @@ export function showToast(message, error = false) {
}
export function panelUrl(themeMode = "auto", hash = "") {
const url = new URL("/ui/panel", window.location.origin);
const url = new URL("/ui/tion", window.location.origin);
url.searchParams.set("theme", themeMode);
if (isDemo) url.searchParams.set("demo", "1");
url.hash = hash;