work: Добавил функционал проверки состояний входов

This commit is contained in:
2026-09-22 21:23:05 +03:00
parent 8d61712642
commit 5e04013e2d
3 changed files with 82 additions and 8 deletions
+8 -8
View File
@@ -17,14 +17,14 @@ class ElicaState:
# Фактические состояния OUT1-OUT8,
# полученные от ESPHome через MQTT.
relay_states: tuple[bool, ...] = (
False,
False,
False,
False,
False,
False,
False,
False,
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:
+60
View File
@@ -118,6 +118,9 @@ class ElicaService:
#широковещательная подписка статусов реле
_client.subscribe(self._config.relay_state_wildcard)
# широковещательная подписка статусов входов
_client.subscribe(self._config.input_state_wildcard)
self._state = replace(self._state, mqtt_connected=True)
@@ -160,6 +163,11 @@ class ElicaService:
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
# ------------------------------------------------------------------
@@ -241,6 +249,58 @@ class ElicaService:
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(
+14
View File
@@ -16,6 +16,10 @@ async def main() -> None:
print("Starting ElicaService...")
await service.start( )
try:
# Даём MQTT время подключиться и получить retained elica/status.
await asyncio.sleep(2)
@@ -73,6 +77,14 @@ async def main() -> None:
)
)
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:
@@ -88,5 +100,7 @@ async def main() -> None:
await service.stop()
if __name__ == "__main__":
asyncio.run(main())