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"
|
||||
@@ -3,7 +3,7 @@ from datetime import datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExhaustState:
|
||||
class ElicaState:
|
||||
mqtt_connected: bool = False
|
||||
device_online: bool = False
|
||||
|
||||
@@ -14,6 +14,19 @@ class ExhaustState:
|
||||
|
||||
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)
|
||||
|
||||
@@ -22,4 +35,5 @@ class ExhaustState:
|
||||
result["last_message_at"].isoformat()
|
||||
)
|
||||
|
||||
return result
|
||||
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(),
|
||||
}
|
||||
@@ -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,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,92 @@
|
||||
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("\nAll 8 relays passed MQTT test.")
|
||||
print("\nFinal state:")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
service.status(),
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
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