File: yeelight_dual_switch.py

package info (click to toggle)
python-miio 0.5.12-5
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 1,888 kB
  • sloc: python: 23,425; makefile: 9
file content (238 lines) | stat: -rw-r--r-- 8,643 bytes parent folder | download | duplicates (3)
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import enum
from typing import Any, Dict

import click

from .click_common import EnumType, command, format_output
from .exceptions import DeviceException
from .miot_device import DeviceStatus, MiotDevice, MiotMapping


class YeelightDualControlModuleException(DeviceException):
    pass


class Switch(enum.Enum):
    First = 0
    Second = 1


_MAPPINGS: MiotMapping = {
    "yeelink.switch.sw1": {
        # http://miot-spec.org/miot-spec-v2/instance?type=urn:miot-spec-v2:device:switch:0000A003:yeelink-sw1:1:0000C809
        # First Switch (siid=2)
        "switch_1_state": {"siid": 2, "piid": 1},  # bool
        "switch_1_default_state": {"siid": 2, "piid": 2},  # 0 - Off, 1 - On
        "switch_1_off_delay": {
            "siid": 2,
            "piid": 3,
        },  # -1 - Off, [1, 43200] - delay in sec
        # Second Switch (siid=3)
        "switch_2_state": {"siid": 3, "piid": 1},  # bool
        "switch_2_default_state": {"siid": 3, "piid": 2},  # 0 - Off, 1 - On
        "switch_2_off_delay": {
            "siid": 3,
            "piid": 3,
        },  # -1 - Off, [1, 43200] - delay in sec
        # Extensions (siid=4)
        "interlock": {"siid": 4, "piid": 1},  # bool
        "flex_mode": {"siid": 4, "piid": 2},  # 0 - Off, 1 - On
        "rc_list": {"siid": 4, "piid": 3},  # string
        "rc_list_for_del": {"siid": 4, "piid": 4},  # string
        "toggle": {"siid": 4, "piid": 5},  # 0 - First switch, 1 - Second switch
    }
}


class DualControlModuleStatus(DeviceStatus):
    def __init__(self, data: Dict[str, Any]) -> None:
        """
        Response of Yeelight Dual Control Module
        {
            'id': 1,
            'result': [
                {'did': 'switch_1_state', 'siid': 2, 'piid': 1, 'code': 0, 'value': False},
                {'did': 'switch_1_default_state', 'siid': 2, 'piid': 2, 'code': 0, 'value': True},
                {'did': 'switch_1_off_delay', 'siid': 2, 'piid': 3, 'code': 0, 'value': 300},
                {'did': 'switch_2_state', 'siid': 3, 'piid': 1, 'code': 0, 'value': False},
                {'did': 'switch_2_default_state', 'siid': 3, 'piid': 2, 'code': 0, 'value': False},
                {'did': 'switch_2_off_delay', 'siid': 3, 'piid': 3, 'code': 0, 'value': 0},
                {'did': 'interlock', 'siid': 4, 'piid': 1, 'code': 0, 'value': False},
                {'did': 'flex_mode', 'siid': 4, 'piid': 2, 'code': 0, 'value': True},
                {'did': 'rc_list', 'siid': 4, 'piid': 2, 'code': 0, 'value': '[{"mac":"9db0eb4124f8","evtid":4097,"pid":339,"beaconkey":"3691bc0679eef9596bb63abf"}]'},
            ]
        }
        """
        self.data = data

    @property
    def switch_1_state(self) -> bool:
        """First switch state."""
        return bool(self.data["switch_1_state"])

    @property
    def switch_1_default_state(self) -> bool:
        """First switch default state."""
        return bool(self.data["switch_1_default_state"])

    @property
    def switch_1_off_delay(self) -> int:
        """First switch off delay."""
        return self.data["switch_1_off_delay"]

    @property
    def switch_2_state(self) -> bool:
        """Second switch state."""
        return bool(self.data["switch_2_state"])

    @property
    def switch_2_default_state(self) -> bool:
        """Second switch default state."""
        return bool(self.data["switch_2_default_state"])

    @property
    def switch_2_off_delay(self) -> int:
        """Second switch off delay."""
        return self.data["switch_2_off_delay"]

    @property
    def interlock(self) -> bool:
        """Interlock."""
        return bool(self.data["interlock"])

    @property
    def flex_mode(self) -> int:
        """Flex mode."""
        return self.data["flex_mode"]

    @property
    def rc_list(self) -> str:
        """List of paired remote controls."""
        return self.data["rc_list"]


class YeelightDualControlModule(MiotDevice):
    """Main class representing the Yeelight Dual Control Module (yeelink.switch.sw1)
    which uses MIoT protocol."""

    _mappings = _MAPPINGS

    @command(
        default_output=format_output(
            "",
            "First Switch Status: {result.switch_1_state}\n"
            "First Switch Default State: {result.switch_1_default_state}\n"
            "First Switch Delay: {result.switch_1_off_delay}\n"
            "Second Switch Status: {result.switch_2_state}\n"
            "Second Switch Default State: {result.switch_2_default_state}\n"
            "Second Switch Delay: {result.switch_2_off_delay}\n"
            "Interlock: {result.interlock}\n"
            "Flex Mode: {result.flex_mode}\n"
            "RC list: {result.rc_list}\n",
        )
    )
    def status(self) -> DualControlModuleStatus:
        """Retrieve properties."""
        p = [
            "switch_1_state",
            "switch_1_default_state",
            "switch_1_off_delay",
            "switch_2_state",
            "switch_2_default_state",
            "switch_2_off_delay",
            "interlock",
            "flex_mode",
            "rc_list",
        ]
        # Filter only readable properties for status
        properties = [
            {"did": k, **v}
            for k, v in filter(lambda item: item[0] in p, self._get_mapping().items())
        ]
        values = self.get_properties(properties)
        return DualControlModuleStatus(
            dict(map(lambda v: (v["did"], v["value"]), values))
        )

    @command(
        click.argument("switch", type=EnumType(Switch)),
        default_output=format_output("Turn {switch} switch on"),
    )
    def on(self, switch: Switch):
        """Turn switch on."""
        if switch == Switch.First:
            return self.set_property("switch_1_state", True)
        elif switch == Switch.Second:
            return self.set_property("switch_2_state", True)

    @command(
        click.argument("switch", type=EnumType(Switch)),
        default_output=format_output("Turn {switch} switch off"),
    )
    def off(self, switch: Switch):
        """Turn switch off."""
        if switch == Switch.First:
            return self.set_property("switch_1_state", False)
        elif switch == Switch.Second:
            return self.set_property("switch_2_state", False)

    @command(
        click.argument("switch", type=EnumType(Switch)),
        default_output=format_output("Toggle {switch} switch"),
    )
    def toggle(self, switch: Switch):
        """Toggle switch."""
        return self.set_property("toggle", switch.value)

    @command(
        click.argument("state", type=bool),
        click.argument("switch", type=EnumType(Switch)),
        default_output=format_output("Set {switch} switch default state to: {state}"),
    )
    def set_default_state(self, state: bool, switch: Switch):
        """Set switch default state."""
        if switch == Switch.First:
            return self.set_property("switch_1_default_state", int(state))
        elif switch == Switch.Second:
            return self.set_property("switch_2_default_state", int(state))

    @command(
        click.argument("delay", type=int),
        click.argument("switch", type=EnumType(Switch)),
        default_output=format_output("Set {switch} switch off delay to {delay} sec."),
    )
    def set_switch_off_delay(self, delay: int, switch: Switch):
        """Set switch off delay, should be between -1 to 43200 (in seconds)"""
        if delay < -1 or delay > 43200:
            raise YeelightDualControlModuleException(
                "Invalid switch delay: %s (should be between -1 to 43200)" % delay
            )

        if switch == Switch.First:
            return self.set_property("switch_1_off_delay", delay)
        elif switch == Switch.Second:
            return self.set_property("switch_2_off_delay", delay)

    @command(
        click.argument("flex_mode", type=bool),
        default_output=format_output("Set flex mode to: {flex_mode}"),
    )
    def set_flex_mode(self, flex_mode: bool):
        """Set flex mode."""
        return self.set_property("flex_mode", int(flex_mode))

    @command(
        click.argument("rc_mac", type=str),
        default_output=format_output("Delete remote control with MAC: {rc_mac}"),
    )
    def delete_rc(self, rc_mac: str):
        """Delete remote control by MAC."""
        return self.set_property("rc_list_for_del", rc_mac)

    @command(
        click.argument("interlock", type=bool),
        default_output=format_output("Set interlock to: {interlock}"),
    )
    def set_interlock(self, interlock: bool):
        """Set interlock."""
        return self.set_property("interlock", interlock)