-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathyeelight.py
254 lines (206 loc) · 6.96 KB
/
yeelight.py
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# Yelight Smart Bulb plugin
# Specification: http://www.yeelight.com/download/Yeelight_Inter-Operation_Spec.pdf
#
# Supported commands: toggle, set_power, set_bright, start_cf, stop_cf, set_scene,
# cron_add, cron_get, cron_del, set_adjust, set_name, get_prop.
#
# Unsupported (feel free to implement something of this): set_ct_abx, set_rgb,
# set_hsv, set_music.
import json
import re
import socket
import time
from web.w import UpdatesHandler
from utils import get_store
STORE_KEY = 'yeelight'
DEVICE = 'yeelight'
YEE_DISCOVER = [
'M-SEARCH * HTTP/1.1',
'MAN: "ssdp:discover"',
'ST: wifi_bulb'
]
store = get_store()
def toggle(device_id=None):
"""
Toggle the smart LED.
"""
return send_command({
'method': 'toggle',
'params': []
}, device_id)
def set_power(power, effect='smooth', duration=500, device_id=None):
"""
Switch on or off the smart LED.
`power` - Boolean
`effect` - "smooth" or "sudden"
`duration` - duration of smooth effect, ignored if effect is "sudden"
"""
return send_command({
'method': 'set_power',
'params': ['on' if power else 'off', effect, duration]
}, device_id)
def set_bright(brightness, effect='smooth', duration=500, device_id=None):
"""
Change the brightness of a smart LED.
`brightness` - integer from 1 to 100
"""
return send_command({
'method': 'set_bright',
'params': [int(brightness), effect, int(duration)]
}, device_id)
def start_cf(flow_expression, count=1, action=0, device_id=None):
"""
Start a color flow (series of smart LED visible state changes; see the Yeelight specification for details).
`flow_expression` - list of tuples contains 4 elements (duration, mode, value, brightness). Example: [(1000, 2, 2700, 100), (500, 1, 255, 10)]. Again, see the specification for details.
`count` - how many times perform flow expression (0 - loop forever)
`action` - action taken after the flow is stopped (0 - recover to the state before; 1 - stay where the flow is stopped; 2 - turn off smart LED)
"""
return send_command({
'method': 'start_cf',
'params': [count, action, ', '.join([', '.join(map(str, x)) for x in flow_expression])]
}, device_id)
def stop_cf(device_id=None):
"""
Stop a running color flow.
"""
return send_command({
'method': 'stop_cf',
'params': []
}, device_id)
def set_scene(state_type, *args, device_id=None):
"""
Set the smart LED directly to specified state. See the specification for details.
`state_type` - color|hsv|ct|cf|auto_delay_off
`*args` - state type specific parameters
"""
return send_command({
'method': 'set_scene',
'params': [state_type] + list(args)
}, device_id)
def cron_add(state_type, value, device_id=None):
"""
Start a time job on the smart LED.
`state_type` - currently can only be 0 (means power off)
`value` - length of the timer (minutes)
"""
return send_command({
'method': 'cron_add',
'params': [int(state_type), value]
}, device_id)
def cron_get(state_type, device_id=None):
"""
Retrieve current cron jobs of the specified type.
"""
return send_command({
'method': 'cron_get',
'params': [int(state_type)]
}, device_id)
def cron_del(state_type, device_id=None):
"""
Stop the specified cron job.
"""
return send_command({
'method': 'cron_del',
'params': [int(state_type)]
}, device_id)
def set_adjust(action, prop, device_id=None):
"""
Adjust brightness, color temperature or color.
`action` - increase|decrease|circle
`prop` - property to adjust: bright|ct|color
"""
return send_command({
'method': 'set_adjust',
'params': [action, prop]
}, device_id)
def set_name(name, device_id=None):
"""
Set name for a smart LED.
"""
return send_command({
'method': 'set_name',
'params': [name]
}, device_id)
def get_prop(properties=['name', 'power', 'bright'], device_id=None):
"""
Retrieve current properties of a smart LED.
"""
results = send_command({
'method': 'get_prop',
'params': properties
}, device_id)
# Populate stored values
for device in results:
data = dict(zip(properties, device['result']))
update_device(data, device['id'])
return results
def process(data):
data = get_data(data)
if 'id' not in data:
return
add_device(data)
def discover():
from mihome import MULTICAST, SOCKET_BUFSIZE
# Empty stored list
store.delete(STORE_KEY)
address, port = MULTICAST.get('yeelight')
yee_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
yee_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
yee_socket.sendto('\r\n'.join(YEE_DISCOVER).encode(), (address, port))
while True:
data, _ = yee_socket.recvfrom(SOCKET_BUFSIZE)
add_device(get_data(data.decode()))
def get_devices():
stored = store.get(STORE_KEY)
return json.loads(stored.decode() if stored else '[]')
def add_device(data):
devices = get_devices()
for i, device in enumerate(devices[:]):
if device['id'] == data['id']:
devices.pop(i)
devices.append(data)
store.set(STORE_KEY, json.dumps(devices))
def update_device(data, device_id):
devices = get_devices()
for i, device in enumerate(devices[:]):
if device['id'] == device_id:
devices[i].update(data)
store.set(STORE_KEY, json.dumps(devices))
def get_data(data):
data = dict(re.findall(r'(\w+):(.*)', data.replace('\r', '')))
for key in data:
data[key] = data[key].strip()
return data
def send_command(command, device_id=None):
"""
Send command to a bulb. If no bulb id specified, send command to all smart LED bulbs
"""
devices = get_devices()
if device_id is not None:
devices = filter(lambda x: x['id'] == device_id, devices)
results = []
for device in devices:
command.update(id=device['id'])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
address, port = device['Location'].replace('yeelight://', '').split(':')
s.connect((address, int(port)))
s.send(json.dumps(command).encode('ascii') + b'\r\n')
result = json.loads(s.recv(1024).decode())
s.close()
result.update(id=device['id'])
results.append(result)
# Send updates to web
if command['method'] != 'get_prop':
props = get_prop(device_id=device['id'])
if props:
name, power, bright = props[0]['result']
data = {
'device': DEVICE,
'id': device['id'],
'name': name,
'power': power,
'bright': bright
}
UpdatesHandler.send_updates(data)
return results