-
Notifications
You must be signed in to change notification settings - Fork 4
/
broadlink_cli2
304 lines (278 loc) · 10.2 KB
/
broadlink_cli2
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
import enum
import argparse
import base64
import codecs
import time
import os
import win32gui
import win32con
import win32api
import ctypes
import ctypes.wintypes
import broadlink
from broadlink.const import DEFAULT_PORT
from broadlink.exceptions import ReadError, StorageError
import array, struct
import os.path
#import json
TICK = 32.84
TIMEOUT = 30
IR_TOKEN = 0x26
hwnd = win32gui.FindWindow('TFAddButton', '')
def auto_int(x):
return int(x, 0)
def to_microseconds(bytes):
result = []
# print bytes[0] # 0x26 = 38for IR
index = 4
while index < len(bytes):
chunk = bytes[index]
index += 1
if chunk == 0:
chunk = bytes[index]
chunk = 256 * chunk + bytes[index + 1]
index += 2
result.append(int(round(chunk * TICK)))
if chunk == 0x0d05:
break
return result
def durations_to_broadlink(durations):
result = bytearray()
result.append(IR_TOKEN)
result.append(0)
result.append(len(durations) % 256)
result.append(len(durations) / 256)
for dur in durations:
num = int(round(dur / TICK))
if num > 255:
result.append(0)
result.append(num / 256)
result.append(num % 256)
return result
def format_durations(data):
result = ''
for i in range(0, len(data)):
if len(result) > 0:
result += ' '
result += ('+' if i % 2 == 0 else '-') + str(data[i])
return result
def parse_durations(str):
result = []
for s in str.split():
result.append(abs(int(s)))
return result
def copy_data(hwnd, message, dwData = 0):
buffer = array.array('u', message + '\x00')
buffer_address, buffer_length = buffer.buffer_info()
copy_struct = struct.pack('PLP', dwData, buffer_length * buffer.itemsize, buffer_address)
return win32gui.SendMessage(hwnd, win32con.WM_COPYDATA, None, copy_struct)
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument("--device", help="device definition as 'type host mac'")
parser.add_argument("--type", type=auto_int, default=0x2712, help="type of device")
parser.add_argument("--host", help="host address")
parser.add_argument("--mac", help="mac address (hex reverse), as used by python-broadlink library")
parser.add_argument("--temperature", action="store_true", help="request temperature from device")
parser.add_argument("--humidity", action="store_true", help="request humidity from device")
parser.add_argument("--energy", action="store_true", help="request energy consumption from device")
parser.add_argument("--check", action="store_true", help="check current power state")
parser.add_argument("--checknl", action="store_true", help="check current nightlight state")
parser.add_argument("--turnon", action="store_true", help="turn on device")
parser.add_argument("--turnoff", action="store_true", help="turn off device")
parser.add_argument("--turnnlon", action="store_true", help="turn on nightlight on the device")
parser.add_argument("--turnnloff", action="store_true", help="turn off nightlight on the device")
parser.add_argument("--switch", action="store_true", help="switch state from on to off and off to on")
parser.add_argument("--send", action="store_true", help="send command")
parser.add_argument("--sensors", action="store_true", help="check all sensors")
parser.add_argument("--learn", action="store_true", help="learn command")
parser.add_argument("--rfscanlearn", action="store_true", help="rf scan learning")
parser.add_argument("--learnfile", help="save learned command to a specified file")
parser.add_argument("--durations", action="store_true",
help="use durations in micro seconds instead of the Broadlink format")
parser.add_argument("--convert", action="store_true", help="convert input data to durati/ons")
parser.add_argument("--joinwifi", nargs=3, help="Args are SSID PASSPHRASE to configure Broadlink device with")
parser.add_argument("--getlightstate", action="store_true", help="Get light bulb state")
parser.add_argument("--setlightstate", help="Set light bulb state")
parser.add_argument("data", nargs='*', help="Data to send or convert")
args = parser.parse_args()
if args.device:
values = args.device.split()
devtype = int(values[0], 0)
host = values[1]
mac = bytearray.fromhex(values[2])
elif args.mac:
devtype = args.type
host = args.host
mac = bytearray.fromhex(args.mac)
if args.host or args.device:
dev = broadlink.gendevice(devtype, (host, DEFAULT_PORT), mac)
dev.auth()
if args.joinwifi:
broadlink.setup(args.joinwifi[0], args.joinwifi[1], int(args.joinwifi[2]))
if args.convert:
data = bytearray.fromhex(''.join(args.data))
durations = to_microseconds(data)
print(format_durations(durations))
if args.temperature:
print(dev.check_temperature())
if args.humidity:
print(dev.check_humidity())
if args.energy:
print(dev.get_energy())
if args.sensors:
data = dev.check_sensors()
for key in data:
print("{} {}".format(key, data[key]))
if args.send:
data = durations_to_broadlink(parse_durations(' '.join(args.data))) \
if args.durations else bytearray.fromhex(''.join(args.data))
dev.send_data(data)
if args.learn or (args.learnfile and not args.rfscanlearn):
dev.enter_learning()
# print("Learning...")
copy_data(hwnd, 'LearnStatus;Learning...')
start = time.time()
while time.time() - start < TIMEOUT:
time.sleep(1)
try:
data = dev.check_data()
except (ReadError, StorageError):
continue
else:
break
else:
# print("No data received...")
copy_data(hwnd, 'LearnStatus;No data received...')
exit(1)
learned = format_durations(to_microseconds(bytearray(data))) \
if args.durations \
else ''.join(format(x, '02x') for x in bytearray(data))
if args.learn:
# print("Command : {}".format(learned))
copy_data(hwnd, 'LearnStatus;Command : ' + learned)
if args.learnfile:
print("Saving to {}".format(args.learnfile))
with open(args.learnfile, "w") as text_file:
text_file.write(learned)
if args.check:
if dev.check_power():
print('* ON *')
else:
print('* OFF *')
if args.checknl:
if dev.check_nightlight():
print('* ON *')
else:
print('* OFF *')
if args.turnon:
dev.set_power(True)
if dev.check_power():
print('== Turned * ON * ==')
else:
print('!! Still OFF !!')
if args.turnoff:
dev.set_power(False)
if dev.check_power():
print('!! Still ON !!')
else:
print('== Turned * OFF * ==')
if args.turnnlon:
dev.set_nightlight(True)
if dev.check_nightlight():
print('== Turned * ON * ==')
else:
print('!! Still OFF !!')
if args.turnnloff:
dev.set_nightlight(False)
if dev.check_nightlight():
print('!! Still ON !!')
else:
print('== Turned * OFF * ==')
if args.switch:
if dev.check_power():
dev.set_power(False)
print('* Switch to OFF *')
else:
dev.set_power(True)
print('* Switch to ON *')
if args.rfscanlearn:
dev.sweep_frequency()
copy_data(hwnd, 'LearnStatus;Learning RF Frequency, press and hold the button to learn...')
print("Learning RF Frequency, press and hold the button to learn...")
start = time.time()
while time.time() - start < TIMEOUT:
time.sleep(1)
if dev.check_frequency():
break
else:
print("RF Frequency not found")
dev.cancel_sweep_frequency()
exit(1)
copy_data(hwnd, 'LearnStatus;Found RF Frequency - 1 of 2!')
print("Found RF Frequency - 1 of 2!")
copy_data(hwnd, 'LearnStatus;You can now let go of the button')
print("You can now let go of the button")
while not os.path.exists("waitfile"):
time.sleep(1)
print("To complete learning, single press the button you want to learn")
dev.find_rf_packet()
start = time.time()
while time.time() - start < TIMEOUT:
time.sleep(1)
try:
data = dev.check_data()
except (ReadError, StorageError):
continue
else:
break
else:
copy_data(hwnd, 'LearnStatus;No data received...')
print("No data received...")
exit(1)
0
copy_data(hwnd, 'LearnStatus;Found RF Frequency - 2 of 2!')
print("Found RF Frequency - 2 of 2!")
learned = format_durations(to_microseconds(bytearray(data))) \
if args.durations \
else ''.join(format(x, '02x') for x in bytearray(data))
if args.learnfile is None:
copy_data(hwnd, 'LearnStatus;Command : ' + learned)
if args.learnfile is not None:
print("Saving to {}".format(args.learnfile))
with open(args.learnfile, "w") as text_file:
text_file.write(learned)
if args.getlightstate:
state = dev.get_state()
print("State : {}".format(state))
if args.setlightstate:
values = args.setlightstate.split()
for i in range(len(values)):
values2 = values[i].split("=")
if values2[0] == "pwr":
dev.set_state(pwr=int(values2[1]))
if values2[0] == "red":
dev.set_state(red=int(values2[1]))
if values2[0] == "green":
dev.set_state(green=int(values2[1]))
if values2[0] == "blue":
dev.set_state(blue=int(values2[1]))
if values2[0] == "brightness":
dev.set_state(brightness=int(values2[1]))
if values2[0] == "colortemp":
dev.set_state(colortemp=int(values2[1]))
if values2[0] == "hue":
dev.set_state(hue=int(values2[1]))
if values2[0] == "saturation":
dev.set_state(saturation=int(values2[1]))
if values2[0] == "transitionduration":
dev.set_state(transitionduration=int(values2[1]))
if values2[0] == "maxworktime":
dev.set_state(maxworktime=int(values2[1]))
if values2[0] == "bulb_colormode":
dev.set_state(bulb_colormode=int(values2[1]))
if values2[0] == "bulb_scenes":
dev.set_state(bulb_scenes=values2[1])
if values2[0] == "bulb_scene":
dev.set_state(bulb_scene=int(values2[1]))
if values2[0] == "bulb_sceneidx":
dev.set_state(bulb_sceneidx=int(values2[1]))