Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4169b0c3e5 | ||
|
|
8ece9ba131 | ||
|
|
f6e00842d8 | ||
|
|
5e04013e2d | ||
|
|
8d61712642 |
@@ -0,0 +1,81 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
# Индикаторы 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"
|
||||||
|
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
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.
|
||||||
|
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)
|
||||||
@@ -0,0 +1,536 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
@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")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Подписки сервиса
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
#Статус
|
||||||
|
_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._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),
|
||||||
|
)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 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._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:
|
||||||
|
"""Отслеживает скорость и мигание индикатора таймера."""
|
||||||
|
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."""
|
||||||
|
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]
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 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(),
|
||||||
|
**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)
|
||||||
|
await self.wait_relay_state(relay, True)
|
||||||
|
await asyncio.sleep(duration_ms / 1000)
|
||||||
|
self.set_relay(relay, False)
|
||||||
|
await self.wait_relay_state(relay, False)
|
||||||
|
|
||||||
|
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."""
|
||||||
|
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),
|
||||||
|
),
|
||||||
|
power_led=self.input_state(self._config.power_input),
|
||||||
|
)
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
|
||||||
class ExhaustConfig:
|
|
||||||
mqtt_host: str
|
|
||||||
mqtt_port: int = 1883
|
|
||||||
|
|
||||||
# Topic устройства в Tasmota
|
|
||||||
topic: str = "exhaust"
|
|
||||||
|
|
||||||
# Длительность виртуального нажатия кнопки
|
|
||||||
pulse_ms: int = 300
|
|
||||||
|
|
||||||
# Соответствие реле функциям Elica.
|
|
||||||
# Если после приезда платы каналы окажутся другими,
|
|
||||||
# меняем только конфигурацию.
|
|
||||||
power_relay: int = 1
|
|
||||||
speed_relay: int = 2
|
|
||||||
light_relay: int = 3
|
|
||||||
timer_relay: int = 4
|
|
||||||
|
|
||||||
@property
|
|
||||||
def command_prefix(self) -> str:
|
|
||||||
return f"cmnd/{self.topic}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def state_prefix(self) -> str:
|
|
||||||
return f"stat/{self.topic}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def telemetry_prefix(self) -> str:
|
|
||||||
return f"tele/{self.topic}"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def lwt_topic(self) -> str:
|
|
||||||
return f"{self.telemetry_prefix}/LWT"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def state_topic(self) -> str:
|
|
||||||
return f"{self.telemetry_prefix}/STATE"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def status2_topic(self) -> str:
|
|
||||||
return f"{self.state_prefix}/STATUS2"
|
|
||||||
|
|
||||||
@property
|
|
||||||
def result_topic(self) -> str:
|
|
||||||
return f"{self.state_prefix}/RESULT"
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
from dataclasses import asdict, dataclass
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
|
||||||
class ExhaustState:
|
|
||||||
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
|
|
||||||
|
|
||||||
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
|
|
||||||
@@ -1,332 +0,0 @@
|
|||||||
import logging
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from dataclasses import replace
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
import paho.mqtt.client as mqtt
|
|
||||||
|
|
||||||
from .config import ExhaustConfig
|
|
||||||
from .models import ExhaustState
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
class ExhaustService:
|
|
||||||
"""
|
|
||||||
Сервис управления вытяжкой.
|
|
||||||
|
|
||||||
Пока не работает с MQTT и ESP.
|
|
||||||
На данном этапе только хранит состояние.
|
|
||||||
"""
|
|
||||||
def __init__(self, config: ExhaustConfig):
|
|
||||||
|
|
||||||
self._config = config
|
|
||||||
|
|
||||||
self._state = ExhaustState()
|
|
||||||
self._running = False
|
|
||||||
self._client: mqtt.Client | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@property
|
|
||||||
def config(self) -> ExhaustConfig:
|
|
||||||
return self._config
|
|
||||||
|
|
||||||
@property
|
|
||||||
def state(self) -> ExhaustState:
|
|
||||||
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-exhaust",
|
|
||||||
)
|
|
||||||
|
|
||||||
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,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _on_connect(
|
|
||||||
self,
|
|
||||||
_client,
|
|
||||||
_userdata,
|
|
||||||
_flags,
|
|
||||||
reason_code,
|
|
||||||
_properties=None,
|
|
||||||
) -> None:
|
|
||||||
if reason_code != 0:
|
|
||||||
logger.error(
|
|
||||||
"Exhaust MQTT connection failed: %s",
|
|
||||||
reason_code,
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.info("Exhaust MQTT connected")
|
|
||||||
|
|
||||||
_client.subscribe(self._config.lwt_topic)
|
|
||||||
_client.subscribe(self._config.state_topic)
|
|
||||||
_client.subscribe(self._config.status2_topic)
|
|
||||||
_client.subscribe(self._config.result_topic)
|
|
||||||
|
|
||||||
self._state = replace(
|
|
||||||
self._state,
|
|
||||||
mqtt_connected=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _on_disconnect(
|
|
||||||
self,
|
|
||||||
_client,
|
|
||||||
_userdata,
|
|
||||||
_disconnect_flags,
|
|
||||||
reason_code,
|
|
||||||
_properties=None,
|
|
||||||
) -> None:
|
|
||||||
logger.warning(
|
|
||||||
"Exhaust MQTT disconnected: %s",
|
|
||||||
reason_code,
|
|
||||||
)
|
|
||||||
|
|
||||||
self._state = replace(
|
|
||||||
self._state,
|
|
||||||
mqtt_connected=False,
|
|
||||||
device_online=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _on_message(
|
|
||||||
self,
|
|
||||||
_client,
|
|
||||||
_userdata,
|
|
||||||
message,
|
|
||||||
) -> None:
|
|
||||||
|
|
||||||
if message.topic == self._config.lwt_topic:
|
|
||||||
self._handle_lwt(message)
|
|
||||||
return
|
|
||||||
|
|
||||||
if message.topic == self._config.state_topic:
|
|
||||||
self._handle_state(message)
|
|
||||||
return
|
|
||||||
|
|
||||||
if message.topic == self._config.status2_topic:
|
|
||||||
self._handle_status2(message)
|
|
||||||
return
|
|
||||||
|
|
||||||
if message.topic == self._config.result_topic:
|
|
||||||
self._handle_result(message)
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
def _handle_lwt(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,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _handle_state(self, message) -> None:
|
|
||||||
import json
|
|
||||||
|
|
||||||
try:
|
|
||||||
payload = json.loads(
|
|
||||||
message.payload.decode("utf-8")
|
|
||||||
)
|
|
||||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
||||||
logger.warning(
|
|
||||||
"Invalid Exhaust STATE payload"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
|
|
||||||
wifi = payload.get("Wifi") or {}
|
|
||||||
|
|
||||||
self._state = replace(
|
|
||||||
self._state,
|
|
||||||
last_message_at=now,
|
|
||||||
uptime_seconds=payload.get("UptimeSec"),
|
|
||||||
wifi_rssi=wifi.get("RSSI"),
|
|
||||||
)
|
|
||||||
|
|
||||||
def request_status(self) -> None:
|
|
||||||
self._publish_command(
|
|
||||||
"Status",
|
|
||||||
"2",
|
|
||||||
)
|
|
||||||
|
|
||||||
def _handle_status2(self, message) -> None:
|
|
||||||
try:
|
|
||||||
payload = json.loads(
|
|
||||||
message.payload.decode("utf-8")
|
|
||||||
)
|
|
||||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
||||||
logger.warning(
|
|
||||||
"Invalid Exhaust STATUS2 payload"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
firmware_info = payload.get("StatusFWR") or {}
|
|
||||||
firmware = firmware_info.get("Version")
|
|
||||||
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
|
|
||||||
self._state = replace(
|
|
||||||
self._state,
|
|
||||||
firmware=firmware,
|
|
||||||
last_message_at=now,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _publish_command(
|
|
||||||
self,
|
|
||||||
command: str,
|
|
||||||
payload: str,
|
|
||||||
) -> None:
|
|
||||||
|
|
||||||
if not self._running:
|
|
||||||
raise RuntimeError("Exhaust service is not running")
|
|
||||||
|
|
||||||
if (
|
|
||||||
self._client is None
|
|
||||||
or not self._state.mqtt_connected
|
|
||||||
):
|
|
||||||
raise RuntimeError("Exhaust MQTT is not connected")
|
|
||||||
|
|
||||||
topic = (
|
|
||||||
f"{self._config.command_prefix}/"
|
|
||||||
f"{command}"
|
|
||||||
)
|
|
||||||
|
|
||||||
result = self._client.publish(
|
|
||||||
topic,
|
|
||||||
payload,
|
|
||||||
retain=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
if result.rc != mqtt.MQTT_ERR_SUCCESS:
|
|
||||||
raise RuntimeError(f"MQTT publish failed: {result.rc}")
|
|
||||||
|
|
||||||
def _press_relay(
|
|
||||||
self,
|
|
||||||
relay: int,
|
|
||||||
) -> None:
|
|
||||||
|
|
||||||
self._publish_command(
|
|
||||||
f"TimedPower{relay}",
|
|
||||||
f"{self._config.pulse_ms},on",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def press_power(self) -> None:
|
|
||||||
self._press_relay(
|
|
||||||
self._config.power_relay
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def press_speed(self) -> None:
|
|
||||||
self._press_relay(
|
|
||||||
self._config.speed_relay
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def press_light(self) -> None:
|
|
||||||
self._press_relay(
|
|
||||||
self._config.light_relay
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def press_timer(self) -> None:
|
|
||||||
self._press_relay(
|
|
||||||
self._config.timer_relay
|
|
||||||
)
|
|
||||||
|
|
||||||
def _handle_result(self,message) -> None:
|
|
||||||
|
|
||||||
try:
|
|
||||||
payload = json.loads(
|
|
||||||
message.payload.decode("utf-8")
|
|
||||||
)
|
|
||||||
except (
|
|
||||||
UnicodeDecodeError,
|
|
||||||
json.JSONDecodeError,
|
|
||||||
):
|
|
||||||
logger.warning(
|
|
||||||
"Invalid Exhaust RESULT payload"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
self._state = replace(
|
|
||||||
self._state,
|
|
||||||
last_message_at=datetime.now(
|
|
||||||
timezone.utc
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.debug("Exhaust Tasmota result: %s",payload)
|
|
||||||
|
|
||||||
def status(self) -> dict:
|
|
||||||
return {
|
|
||||||
"running": self._running,
|
|
||||||
"topic": self._config.topic,
|
|
||||||
"pulse_ms": self._config.pulse_ms,
|
|
||||||
**self._state.to_dict(),
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
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'
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
- 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: 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"
|
||||||
@@ -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.
|
||||||
@@ -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"
|
||||||
@@ -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())
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
# from app.exhaust.config import ExhaustConfig
|
|
||||||
# from app.exhaust.service import ExhaustService
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# config = ExhaustConfig(
|
|
||||||
# mqtt_host="192.168.7.100",
|
|
||||||
# mqtt_port=1883,
|
|
||||||
# topic="exhaust",
|
|
||||||
# )
|
|
||||||
#
|
|
||||||
# service = ExhaustService(config)
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# print("Configuration:")
|
|
||||||
# print("MQTT:", service.config.mqtt_host)
|
|
||||||
# print("Port:", service.config.mqtt_port)
|
|
||||||
# print("Topic:", service.config.topic)
|
|
||||||
# print("Command:", service.config.command_prefix)
|
|
||||||
# print("State:", service.config.state_prefix)
|
|
||||||
# print("Telemetry:", service.config.telemetry_prefix)
|
|
||||||
# print("LWT:", service.config.lwt_topic)
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# print("\nInitial:")
|
|
||||||
# print(service.running)
|
|
||||||
# print(service.state.to_dict())
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# service.start()
|
|
||||||
#
|
|
||||||
# print("\nAfter start:")
|
|
||||||
# print(service.running)
|
|
||||||
# print(service.state.to_dict())
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# service.stop()
|
|
||||||
#
|
|
||||||
# print("\nAfter stop:")
|
|
||||||
# print(service.running)
|
|
||||||
# print(service.state.to_dict())
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
from app.exhaust.config import ExhaustConfig
|
|
||||||
from app.exhaust.service import ExhaustService
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
config = ExhaustConfig(
|
|
||||||
mqtt_host="192.168.7.100",
|
|
||||||
mqtt_port=1883,
|
|
||||||
topic="exhaust",
|
|
||||||
)
|
|
||||||
|
|
||||||
service = ExhaustService(config)
|
|
||||||
|
|
||||||
print("Initial:")
|
|
||||||
print(service.running)
|
|
||||||
print(service.state.to_dict())
|
|
||||||
|
|
||||||
await service.start()
|
|
||||||
|
|
||||||
print("\nStarted. Waiting for MQTT...")
|
|
||||||
await asyncio.sleep(2)
|
|
||||||
|
|
||||||
print("\nRequesting Tasmota status...")
|
|
||||||
service.request_status()
|
|
||||||
|
|
||||||
await asyncio.sleep(2)
|
|
||||||
|
|
||||||
print(service.running)
|
|
||||||
print(service.state.to_dict())
|
|
||||||
|
|
||||||
await service.stop()
|
|
||||||
|
|
||||||
print("\nAfter stop:")
|
|
||||||
print(service.running)
|
|
||||||
print(service.state.to_dict())
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
Reference in New Issue
Block a user