From 5e04013e2d58cd1f32a923b3406d936586f3d5f4 Mon Sep 17 00:00:00 2001 From: Fedorov Dmitriy Date: Tue, 22 Sep 2026 21:23:05 +0300 Subject: [PATCH] =?UTF-8?q?work:=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=BE=D0=BD=D0=B0?= =?UTF-8?q?=D0=BB=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20?= =?UTF-8?q?=D1=81=D0=BE=D1=81=D1=82=D0=BE=D1=8F=D0=BD=D0=B8=D0=B9=20=D0=B2?= =?UTF-8?q?=D1=85=D0=BE=D0=B4=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/elica/models.py | 16 ++++----- app/elica/service.py | 60 +++++++++++++++++++++++++++++++ tests/test_esp32_elica_service.py | 14 ++++++++ 3 files changed, 82 insertions(+), 8 deletions(-) diff --git a/app/elica/models.py b/app/elica/models.py index db2a33e..395d974 100644 --- a/app/elica/models.py +++ b/app/elica/models.py @@ -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: diff --git a/app/elica/service.py b/app/elica/service.py index c107bb3..266a24d 100644 --- a/app/elica/service.py +++ b/app/elica/service.py @@ -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( diff --git a/tests/test_esp32_elica_service.py b/tests/test_esp32_elica_service.py index 1648936..f120212 100644 --- a/tests/test_esp32_elica_service.py +++ b/tests/test_esp32_elica_service.py @@ -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()) \ No newline at end of file