summaryrefslogtreecommitdiff
path: root/src/home/mqtt/relay.py
blob: cf657f795522e66f17d6bd8253e51dbc0a832820 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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