From 52db06e0c81bf7f5ec75da40250ddb700d333db2 Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Wed, 31 May 2023 22:27:46 +0300 Subject: save --- src/home/mqtt/relay.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/home/mqtt/relay.py (limited to 'src/home/mqtt/relay.py') diff --git a/src/home/mqtt/relay.py b/src/home/mqtt/relay.py new file mode 100644 index 0000000..cf657f7 --- /dev/null +++ b/src/home/mqtt/relay.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +import paho.mqtt.client as mqtt +import re +import logging + +from .mqtt import MQTTBase + + +class MQTTRelayClient(MQTTBase): + _home_id: str + + def __init__(self, home_id: str): + super().__init__(clean_session=True) + self._home_id = home_id + + def on_connect(self, client: mqtt.Client, userdata, flags, rc): + super().on_connect(client, userdata, flags, rc) + + topic = f'home/{self._home_id}/#' + self._logger.info(f"subscribing to {topic}") + + client.subscribe(topic, qos=1) + + def on_message(self, client: mqtt.Client, userdata, msg): + try: + match = re.match(r'^home/(.*?)/relay/(stat|power)(?:/(.+))?$', msg.topic) + self._logger.info(f'topic: {msg.topic}') + if not match: + return + + name = match.group(1) + subtopic = match.group(2) + + if name != self._home_id: + return + + if subtopic == 'stat': + stat_name, stat_value = match.group(3).split('/') + self._logger.info(f'stat: {stat_name} = {stat_value}') + + except Exception as e: + self._logger.exception(str(e)) + + +class MQTTRelayController(MQTTBase): + _home_id: str + + def __init__(self, home_id: str): + super().__init__(clean_session=True) + self._home_id = home_id + + def set_power(self, enable: bool): + self._client.publish(f'home/{self._home_id}/relay/power', + payload=int(enable), + qos=1) + self._client.loop_write() + + def send_stat(self, stat: dict): + pass -- cgit v1.2.3