aboutsummaryrefslogtreecommitdiff
path: root/src/home/mqtt/relay.py
blob: 0c6084f8e8b1556afbb219e1ad880d840c20c9aa (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import paho.mqtt.client as mqtt
import re
import datetime

from .mqtt import MQTTBase
from typing import Optional, Union
from .payload.relay import (
    InitialStatPayload,
    StatPayload,
    PowerPayload,
    OTAPayload,
    OTAResultPayload
)


class MQTTRelayDevice:
    id: str
    secret: Optional[str]

    def __init__(self, id: str, secret: Optional[str] = None):
        self.id = id
        self.secret = secret


class MQTTRelay(MQTTBase):
    _devices: list[MQTTRelayDevice]
    _message_callback: Optional[callable]
    _ota_publish_callback: Optional[callable]

    def __init__(self,
                 devices: Union[MQTTRelayDevice, list[MQTTRelayDevice]],
                 subscribe_to_updates=True):
        super().__init__(clean_session=True)
        if not isinstance(devices, list):
            devices = [devices]
        self._devices = devices
        self._message_callback = None
        self._ota_publish_callback = None
        self._subscribe_to_updates = subscribe_to_updates
        self._ota_mid = None

    def on_connect(self, client: mqtt.Client, userdata, flags, rc):
        super().on_connect(client, userdata, flags, rc)

        if self._subscribe_to_updates:
            for device in self._devices:
                topic = f'hk/{device.id}/relay/#'
                self._logger.debug(f"subscribing to {topic}")
                client.subscribe(topic, qos=1)

    def on_publish(self, client: mqtt.Client, userdata, mid):
        if self._ota_mid is not None and mid == self._ota_mid and self._ota_publish_callback:
            self._ota_publish_callback()

    def set_message_callback(self, callback: callable):
        self._message_callback = callback

    def on_message(self, client: mqtt.Client, userdata, msg):
        try:
            match = re.match(r'^hk/(.*?)/relay/(stat|stat1|power|otares)$', msg.topic)
            self._logger.debug(f'topic: {msg.topic}')
            if not match:
                return

            device_id = match.group(1)
            subtopic = match.group(2)

            try:
                next(d for d in self._devices if d.id == device_id)
            except StopIteration:
                return

            message = None
            if subtopic == 'stat':
                message = StatPayload.unpack(msg.payload)
            elif subtopic == 'stat1':
                message = InitialStatPayload.unpack(msg.payload)
            elif subtopic == 'power':
                message = PowerPayload.unpack(msg.payload)
            elif subtopic == 'otares':
                message = OTAResultPayload.unpack(msg.payload)

            if message and self._message_callback:
                self._message_callback(device_id, message)

        except Exception as e:
            self._logger.exception(str(e))

    def set_power(self, device_id, enable: bool):
        device = next(d for d in self._devices if d.id == device_id)
        assert device.secret is not None, 'device secret not specified'

        payload = PowerPayload(secret=device.secret,
                               state=enable)
        self._client.publish(f'hk/{device.id}/relay/power',
                             payload=payload.pack(),
                             qos=1)
        self._client.loop_write()

    def push_ota(self,
                 device_id,
                 filename: str,
                 publish_callback: callable,
                 qos: int):
        device = next(d for d in self._devices if d.id == device_id)
        assert device.secret is not None, 'device secret not specified'

        self._ota_publish_callback = publish_callback
        payload = OTAPayload(secret=device.secret, filename=filename)
        publish_result = self._client.publish(f'hk/{device.id}/relay/admin/ota',
                                              payload=payload.pack(),
                                              qos=qos)
        self._ota_mid = publish_result.mid
        self._client.loop_write()


class MQTTRelayState:
    enabled: bool
    update_time: datetime.datetime
    rssi: int
    fw_version: int
    ever_updated: bool

    def __init__(self):
        self.ever_updated = False
        self.enabled = False
        self.rssi = 0

    def update(self,
               enabled: bool,
               rssi: int,
               fw_version=None):
        self.ever_updated = True
        self.enabled = enabled
        self.rssi = rssi
        self.update_time = datetime.datetime.now()
        if fw_version:
            self.fw_version = fw_version