work: Изменил конфиг сервиса вытяжки для реальной платы. Добавил yaml конфигурацию платы. Сейчас доступны MQTT -прием статуса и управление реле.
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
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 = 200
|
||||
|
||||
# Физические реле платы ESP32 Relay X8 Modbus.
|
||||
# OUT1-OUT4 используются для кнопок Elica.
|
||||
power_relay: int = 1
|
||||
speed_relay: int = 2
|
||||
light_relay: int = 3
|
||||
timer_relay: int = 4
|
||||
|
||||
@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,39 @@
|
||||
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,
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
import logging
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from .config import ElicaConfig
|
||||
from .models import ElicaState
|
||||
|
||||
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
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
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
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 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),
|
||||
)
|
||||
# ------------------------------------------------------------------
|
||||
# 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,
|
||||
**self._state.to_dict(),
|
||||
}
|
||||
Reference in New Issue
Block a user