work: функционал для работы с вятяжкой
* Добавил полный функционал управления elica через esp32 по MQTT * Добавил в прошивку принудительную блокировку внешнего винтелятора при работающей вытяжке * Добавил веб-панели для управления вытяжкой
This commit is contained in:
+124
-7
@@ -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
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user