From 774d16f10a9b45fe0d3e7d1bd2be3c4c4028b83f Mon Sep 17 00:00:00 2001 From: Fedorov Dmitriy Date: Sun, 27 Sep 2026 00:00:26 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20v=201.4.0=20=D0=9F=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=BE=D0=BD?= =?UTF-8?q?=D0=B0=D0=BB=20=D0=B4=D0=BB=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=8B=20=D1=81=20=D0=B2=D1=8F=D1=82=D1=8F=D0=B6=D0=BA?= =?UTF-8?q?=D0=BE=D0=B9=20=20=20=20=20*=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BF=D0=BE=D0=BB=D0=BD=D1=8B=D0=B9=20=D1=84?= =?UTF-8?q?=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=BE=D0=BD=D0=B0=D0=BB=20=D1=83?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20elica?= =?UTF-8?q?=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20esp32=20=D0=BF=D0=BE=20MQTT?= =?UTF-8?q?=20=20=20=20=20*=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=20=D0=B2=20=D0=BF=D1=80=D0=BE=D1=88=D0=B8=D0=B2=D0=BA=D1=83=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=BD=D1=83=D0=B4=D0=B8=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=83=D1=8E=20=D0=B1=D0=BB=D0=BE=D0=BA=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=BA=D1=83=20=D0=B2=D0=BD=D0=B5=D1=88=D0=BD=D0=B5?= =?UTF-8?q?=D0=B3=D0=BE=20=D0=B2=D0=B8=D0=BD=D1=82=D0=B5=D0=BB=D1=8F=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B0=20=D0=BF=D1=80=D0=B8=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D1=8E=D1=89=D0=B5=D0=B9=20=D0=B2=D1=8B=D1=82?= =?UTF-8?q?=D1=8F=D0=B6=D0=BA=D0=B5=20=20=20=20=20*=20=D0=94=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=B2=D0=B5=D0=B1-=D0=BF=D0=B0?= =?UTF-8?q?=D0=BD=D0=B5=D0=BB=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D1=83=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B2=D1=8B?= =?UTF-8?q?=D1=82=D1=8F=D0=B6=D0=BA=D0=BE=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/ClimatController.iml | 1 + Version.toml | 6 +- app/api.py | 131 +++- app/elica/__init__.py | 14 + app/elica/config.py | 88 +++ app/elica/controller.py | 312 ++++++++ app/elica/models.py | 70 ++ app/elica/service.py | 691 ++++++++++++++++++ app/my_dataclasses.py | 4 + hardware/esp32_relay_exhaust/elica-relay.yaml | 348 +++++++++ hardware/esp32_relay_exhaust/readme.txt | 28 + .../esp32_relay_exhaust/secrets.yaml.template | 15 + tests/test_esp32_elica_service.py | 112 +++ web/exhaust-widget.html | 85 +++ web/exhaust.html | 118 +++ web/js/api.js | 2 +- 16 files changed, 2014 insertions(+), 11 deletions(-) create mode 100644 app/elica/__init__.py create mode 100644 app/elica/config.py create mode 100644 app/elica/controller.py create mode 100644 app/elica/models.py create mode 100644 app/elica/service.py create mode 100644 hardware/esp32_relay_exhaust/elica-relay.yaml create mode 100644 hardware/esp32_relay_exhaust/readme.txt create mode 100644 hardware/esp32_relay_exhaust/secrets.yaml.template create mode 100644 tests/test_esp32_elica_service.py create mode 100644 web/exhaust-widget.html create mode 100644 web/exhaust.html diff --git a/.idea/ClimatController.iml b/.idea/ClimatController.iml index dcdb726..1b03116 100644 --- a/.idea/ClimatController.iml +++ b/.idea/ClimatController.iml @@ -3,6 +3,7 @@ + diff --git a/Version.toml b/Version.toml index 1f850b7..1fe6d79 100644 --- a/Version.toml +++ b/Version.toml @@ -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" diff --git a/app/api.py b/app/api.py index d6fbf21..6ce0577 100644 --- a/app/api.py +++ b/app/api.py @@ -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 # ---------------------------------------------------------------------- diff --git a/app/elica/__init__.py b/app/elica/__init__.py new file mode 100644 index 0000000..d3e6120 --- /dev/null +++ b/app/elica/__init__.py @@ -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", +] diff --git a/app/elica/config.py b/app/elica/config.py new file mode 100644 index 0000000..a2afbbc --- /dev/null +++ b/app/elica/config.py @@ -0,0 +1,88 @@ +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" + diff --git a/app/elica/controller.py b/app/elica/controller.py new file mode 100644 index 0000000..627a9eb --- /dev/null +++ b/app/elica/controller.py @@ -0,0 +1,312 @@ +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") \ No newline at end of file diff --git a/app/elica/models.py b/app/elica/models.py new file mode 100644 index 0000000..473eabc --- /dev/null +++ b/app/elica/models.py @@ -0,0 +1,70 @@ +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) diff --git a/app/elica/service.py b/app/elica/service.py new file mode 100644 index 0000000..41c62c7 --- /dev/null +++ b/app/elica/service.py @@ -0,0 +1,691 @@ +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) \ No newline at end of file diff --git a/app/my_dataclasses.py b/app/my_dataclasses.py index 72663e1..eeddaa5 100644 --- a/app/my_dataclasses.py +++ b/app/my_dataclasses.py @@ -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 diff --git a/hardware/esp32_relay_exhaust/elica-relay.yaml b/hardware/esp32_relay_exhaust/elica-relay.yaml new file mode 100644 index 0000000..fbd38a9 --- /dev/null +++ b/hardware/esp32_relay_exhaust/elica-relay.yaml @@ -0,0 +1,348 @@ +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" diff --git a/hardware/esp32_relay_exhaust/readme.txt b/hardware/esp32_relay_exhaust/readme.txt new file mode 100644 index 0000000..e30c288 --- /dev/null +++ b/hardware/esp32_relay_exhaust/readme.txt @@ -0,0 +1,28 @@ +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. \ No newline at end of file diff --git a/hardware/esp32_relay_exhaust/secrets.yaml.template b/hardware/esp32_relay_exhaust/secrets.yaml.template new file mode 100644 index 0000000..dd608ea --- /dev/null +++ b/hardware/esp32_relay_exhaust/secrets.yaml.template @@ -0,0 +1,15 @@ +# 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" diff --git a/tests/test_esp32_elica_service.py b/tests/test_esp32_elica_service.py new file mode 100644 index 0000000..009459f --- /dev/null +++ b/tests/test_esp32_elica_service.py @@ -0,0 +1,112 @@ +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()) \ No newline at end of file diff --git a/web/exhaust-widget.html b/web/exhaust-widget.html new file mode 100644 index 0000000..5d4788a --- /dev/null +++ b/web/exhaust-widget.html @@ -0,0 +1,85 @@ + + + + + + + Elica — виджет + + + + + + +
+
+
+ + +

Elica

Загрузка
+ Вытяжная вентиляция +
+
+ +
+ +
+
+ +

Скорость вытяжки

Фактическая ступень Elica

+
+
+ + 0 + +
+
+ + + + +
+ +
+ +
+
+
+ +

Вытяжка

Выключена
+
+ +
+
+
+ +

Внешний

OUT5 · NC
+
+ +
+
+ +
+
+ ТаймерВыключен + +
+ +
+ ПодсветкаИмпульсное управление + +
+
+ + +
+ + + diff --git a/web/exhaust.html b/web/exhaust.html new file mode 100644 index 0000000..1bf2c20 --- /dev/null +++ b/web/exhaust.html @@ -0,0 +1,118 @@ + + + + + + + Elica — управление вытяжкой + + + + + + + +
+
+
+ + +

Elica

Загрузка
+ Кухонная вытяжка и внешний вытяжной вентилятор +
+
+ +
+
+ + Вытяжная вентиляцияУправление Elica и внешним вентилятором +
+ + + + + +
+
+ +
+
+
+ +

Скорость вытяжки

Скорость определяется по индикаторам Elica

+
+
+ + — + +
+
+ + + + +
+ +
+ +
+
+ +

Питание

Ожидаем состояние панели

+
+ +
+ +
+
+ +

Внешний вентилятор

Ожидаем состояние OUT5

+
+ +
+ +
+
+
+ +

Таймер

По миганию индикатора скорости

+
+ +
+
+
+
+ +

Подсветка

Без обратной связи по состоянию

+
+ +
+
+
+ +
+
+

Связь с контроллером

+ — +
+
+
MQTT—
+
ESP32—
+
Панель Elica—
+
OUT5 физически—
+
+

Получаем данные…

+
+
+ + + + diff --git a/web/js/api.js b/web/js/api.js index 25c9eb7..a2c8096 100644 --- a/web/js/api.js +++ b/web/js/api.js @@ -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;