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
|
import datetime
from typing import Optional
from .. import MqttModule, MqttPayload, MqttNode
MODULE_NAME = 'MqttRelayModule'
class MqttPowerSwitchPayload(MqttPayload):
FORMAT = '=12sB'
PACKER = {
'state': lambda n: int(n),
'secret': lambda s: s.encode('utf-8')
}
UNPACKER = {
'state': lambda n: bool(n),
'secret': lambda s: s.decode('utf-8')
}
secret: str
state: bool
class MqttPowerStatusPayload(MqttPayload):
FORMAT = '=B'
PACKER = {
'opened': lambda n: int(n),
}
UNPACKER = {
'opened': lambda n: bool(n),
}
opened: bool
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
class MqttRelayModule(MqttModule):
_legacy_topics: bool
def __init__(self, legacy_topics=False, *args, **kwargs):
super().__init__(*args, **kwargs)
self._legacy_topics = legacy_topics
def on_connect(self, mqtt: MqttNode):
super().on_connect(mqtt)
mqtt.subscribe_module(self._get_switch_topic(), self)
mqtt.subscribe_module('relay/status', self)
def switchpower(self,
enable: bool):
payload = MqttPowerSwitchPayload(secret=self._mqtt_node_ref.secret,
state=enable)
self._mqtt_node_ref.publish(self._get_switch_topic(),
payload=payload.pack())
def handle_payload(self, mqtt: MqttNode, topic: str, payload: bytes) -> Optional[MqttPayload]:
message = None
if topic == self._get_switch_topic():
message = MqttPowerSwitchPayload.unpack(payload)
elif topic == 'relay/status':
message = MqttPowerStatusPayload.unpack(payload)
if message is not None:
self._logger.debug(message)
return message
def _get_switch_topic(self) -> str:
return 'relay/power' if self._legacy_topics else 'relay/switch'
|