Files
ClimatController/app/elica/service.py
T

374 lines
11 KiB
Python

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)
# широковещательная подписка статусов входов
_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),
)
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]
# ------------------------------------------------------------------
# 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(),
}