summaryrefslogtreecommitdiff
path: root/src/home/mqtt
diff options
context:
space:
mode:
Diffstat (limited to 'src/home/mqtt')
-rw-r--r--src/home/mqtt/relay.py59
1 files changed, 59 insertions, 0 deletions
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