-
Notifications
You must be signed in to change notification settings - Fork 5
/
lights.py
executable file
·1589 lines (1328 loc) · 55.5 KB
/
lights.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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import sys
if sys.version_info < (3, 3):
sys.stdout.write("Sorry, This module requires Python 3.3 (or higher), not Python 2.x. You are using Python {0}.{1}\n".format(sys.version_info[0],sys.version_info[1]))
sys.exit(1)
from appJar import gui
import os
import time
import binascii
import lifxlan
#import colorsys
from colour import Color
import math
import sys
from time import sleep
from lifxlan import BLUE, CYAN, GREEN, ORANGE, PINK, PURPLE, RED, YELLOW
from configobj import ConfigObj
import pickle as pkl
from random import randint
from platform import system
from PIL import Image
import appJar as aJ
import numpy as np
import cv2
from scipy.stats import itemfreq
from mss import mss
import inspect
myos = system()
if (myos == 'Windows') or (myos == 'Darwin'):
from PIL import ImageGrab
elif (myos == 'Linux'):
import pyscreenshot as ImageGrab
if (myos == 'Windows'):
mygreen = 'lime'
elif (myos == 'Darwin') or (myos == 'Linux') :
mygreen = 'green'
def lineno():
"""Returns the current line number in our program."""
return inspect.currentframe().f_back.f_lineno
def abs_resource_path(relative_path):
if (myos == 'Windows'):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = os.path.abspath(".")
except Exception:
print("Error finding path")
return os.path.join(base_path, relative_path)
elif (myos == 'Darwin') or (myos == 'Linux') :
""" Get absolute path to resource, works for dev and for PyInstaller """
#base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(os.getenv("HOME"), relative_path)
def resource_path(relative_path):
if (myos == 'Windows'):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
elif (myos == 'Darwin') or (myos == 'Linux') :
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
DECIMATE = 1 # skip every DECIMATE number of pixels to speed up calculation
TRANSIENT_TIP = "If selected, return to the original color after the specified number of cycles. If not selected, set light to specified color"
PERIOD_TIP = "Period is the length of one cycle in milliseconds"
CYCLES_TIP = "Cycles is the number of times to repeat the waveform"
DUTY_CYCLE_TIP = "Duty Cycle is an integer between -32768 and 32767. Its effect is most obvious with the Pulse waveform. Set Duty Cycle to 0 to spend an equal amount of time on the original color and the new color. Set Duty Cycle to positive to spend more time on the original color. Set Duty Cycle to negative to spend more time on the new color"
EXPECTED_TIP = "Select 0 to find all available bulbs. Select any number to look for exactly that number of bulbs"
TRANSITION_TIME_TIP = "The time (in ms) that a color transition takes"
FOLLOW_DESKTOP_TIP = "Make your bulbs' color match your desktop"
DESKTOP_MODE_TIP = "Select between following the whole desktop screen or just a small portion of it (useful for letterbox movies)"
HUE_DELTA_TIP = "The amount the hue will change every interval (between 0 and 65535)"
CYCLE_INTERVAL_TIP = "The time (in ms) between each update"
CYCLE_SATURATION_TIP = "How saturated you want the hue to be (between 0 and 65535)"
EXPECTED_BULBS = 0
TRANSITION_TIME_DEFAULT = 400
CONFIG = abs_resource_path("lights.ini")
PICKLE = abs_resource_path("lifxList.pkl")
SCENE1_C = abs_resource_path("scene1_c.pkl")
SCENE1_P = abs_resource_path("scene1_p.pkl")
SCENE2_C = abs_resource_path("scene2_c.pkl")
SCENE2_P = abs_resource_path("scene2_p.pkl")
SCENE3_C = abs_resource_path("scene3_c.pkl")
SCENE3_P = abs_resource_path("scene3_p.pkl")
CYCLES = "Cycles"
TRANSITION_TIME = "Transition Time(ms)"
FOLLOW_DESKTOP = "Start Following Desktop"
DESKTOP_MODE = "Desktop Mode"
SELECT_MODE = "Select Mode"
REGION_COLOR = "regioncolor"
MAX_SATURATION = "Max Saturation"
MAX_BRIGHTNESS = "Max Brightness"
COLOR_CYCLE = "Color Cycle"
CYCLE_INTERVAL = "Update Interval(ms)" #update interval
SCALE = "Scale"
CYCLE_INTERVAL_SCALE = CYCLE_INTERVAL + SCALE
HUE_DELTA = "Hue Delta"
HUE_DELTA_SCALE = HUE_DELTA + SCALE
TRANSITION_TIME2 = "Transition Time (ms)"
TRANSITION_TIME2_SCALE = TRANSITION_TIME2 + SCALE
START_COLOR_CYCLE = "Start Color Cycle"
CYCLE_COLOR = "CycleColor"
CYCLE_HUE_DELTA = 600
CYCLE_INTERVAL_MS = 2000
original_colors = {}
config = {}
bulbs = []
selected_bulb = 0
details = str(0)
gSelectAll = False
lan = 0
gExpectedBulbs = EXPECTED_BULBS
lifxList = []
lifxDict = {}
gwaveformcolor = "#FF0000"
is_follow = False
test_string = """
"""
original_colors1 = {}
original_powers1 = {}
original_colors2 = {}
original_powers2 = {}
original_colors3 = {}
original_powers3 = {}
r = None
selectedMode = "Whole Screen"
maxSaturation = False
maxBrightness = False
is_cycle = False
gCycleHue = 0
gCycleInterval = CYCLE_INTERVAL_MS
gCycleDelta = CYCLE_HUE_DELTA
gTransitionTime = TRANSITION_TIME_DEFAULT
gCycleSaturation = 65535
gCycleBrightness = 65535
gCycleKelvin = 3500
class App(aJ.gui):
def __init__(self, *args, **kwargs):
aJ.gui.__init__(self, *args, **kwargs)
def winfo_screenheight(self):
# shortcut to height
# alternatively return self.topLevel.winfo_screenheight() since topLevel is Tk (root) instance!
return self.appWindow.winfo_screenheight()
def winfo_screenwidth(self):
# shortcut to width
# alternatively return self.topLevel.winfo_screenwidth() since topLevel is Tk (root) instance!
return self.appWindow.winfo_screenwidth()
def SceneNameChanged(name):
#print(name, "Entry changed")
config[name] = app.getEntry(name)
config.write()
def Scene(name):
global original_colors1
global original_powers1
global original_colors2
global original_powers2
global original_colors3
global original_powers3
global lan
global config
print(name, "button pressed")
if len(bulbs) < 1:
app.errorBox("Error", "Error. No bulbs were found yet. Please click the 'Find Bulbs' button and try again.")
return
try:
if name == 'Save Scene 1':
print("Saving Scene 1")
original_colors1 = lan.get_color_all_lights()
original_powers1 = lan.get_power_all_lights()
#print("colors:",original_colors)
#print(type(original_colors1))
pkl.dump(original_colors1, open(SCENE1_C, "wb" ))
pkl.dump(original_powers1, open(SCENE1_P, "wb" ))
elif name == 'Restore Scene 1':
print("Restoring Scene 1")
if (os.path.exists(SCENE1_C) and os.path.exists(SCENE1_P) ):
original_colors1 = pkl.load(open(SCENE1_C, "rb"))
original_powers1 = pkl.load(open(SCENE1_P, "rb"))
if ( (len(original_colors1) == 0) or (len(original_powers1) == 0) ):
print("Nothing saved yet.")
return
print("Restoring original color to all lights...")
#print("colors:",original_colors)
for light in original_colors1:
light.set_color(original_colors1[light])
sleep(1)
print("Restoring original power to all lights...")
for light in original_powers1:
light.set_power(original_powers1[light])
elif name == 'Save Scene 2':
print("Saving Scene 2")
original_colors2 = lan.get_color_all_lights()
original_powers2 = lan.get_power_all_lights()
#print("colors:",original_colors)
pkl.dump(original_colors2, open(SCENE2_C, "wb" ))
pkl.dump(original_powers2, open(SCENE2_P, "wb" ))
elif name == 'Restore Scene 2':
print("Restoring Scene 2")
if (os.path.exists(SCENE2_C) and os.path.exists(SCENE2_P) ):
original_colors2 = pkl.load(open(SCENE2_C, "rb"))
original_powers2 = pkl.load(open(SCENE2_P, "rb"))
if ( (len(original_colors2) == 0) or (len(original_powers2) == 0) ):
print("Nothing saved yet.")
return
print("Restoring original color to all lights...")
#print("colors:",original_colors)
for light in original_colors2:
light.set_color(original_colors2[light])
sleep(1)
print("Restoring original power to all lights...")
for light in original_powers2:
light.set_power(original_powers2[light])
elif name == 'Save Scene 3':
print("Saving Scene 3")
original_colors3 = lan.get_color_all_lights()
original_powers3 = lan.get_power_all_lights()
#print("colors:",original_colors)
pkl.dump(original_colors3, open(SCENE3_C, "wb" ))
pkl.dump(original_powers3, open(SCENE3_P, "wb" ))
elif name == 'Restore Scene 3':
print("Restoring Scene 3")
if (os.path.exists(SCENE3_C) and os.path.exists(SCENE3_P) ):
original_colors3 = pkl.load(open(SCENE3_C, "rb"))
original_powers3 = pkl.load(open(SCENE3_P, "rb"))
if ( (len(original_colors3) == 0) or (len(original_powers3) == 0) ):
print("Nothing saved yet.")
return
print("Restoring original color to all lights...")
#print("colors:",original_colors)
for light in original_colors3:
light.set_color(original_colors3[light])
sleep(1)
print("Restoring original power to all lights...")
for light in original_powers3:
light.set_power(original_powers3[light])
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
app.errorBox("Error", str(e) + "\n\n Scene Operation failed. This feature is buggy and only works about 50% of the time. Sometimes, you can still save and restore a scene despite this error. If you keep getting this error and can not perform a 'Restore', try restarting the app then try again.")
return
def updateSliders(hsbk):
#print("h:",hsbk[0])
#print("s:",hsbk[1])
#print("b:",hsbk[2])
#print("k:",hsbk[3])
global gCycleHue
global gCycleSaturation
global gCycleBrightness
global gCycleKelvin
app.setSpinBox("hueSpin", int(hsbk[0]), callFunction=False)
app.setSpinBox("satSpin", int(hsbk[1]), callFunction=False)
app.setSpinBox("briSpin", int(hsbk[2]), callFunction=False)
app.setSpinBox("kelSpin", int(hsbk[3]), callFunction=False)
app.setScale("hueScale", int(hsbk[0]), callFunction=False)
app.setScale("satScale", int(hsbk[1]), callFunction=False)
app.setScale("briScale", int(hsbk[2]), callFunction=False)
app.setScale("kelScale", int(hsbk[3]), callFunction=False)
rgb1 = hsv_to_rgb((hsbk[0]/65535), (hsbk[1]/65535), (hsbk[2]/65535));#print("rgb1:",rgb1)
c = Color(rgb=(rgb1[0], rgb1[1], rgb1[2]))
#print("c:",c)
app.setLabelBg("bulbcolor", c.hex_l)
gCycleHue = hsbk[0]
gCycleSaturation = hsbk[1]
gCycleBrightness = hsbk[2]
gCycleKelvin = hsbk[3]
def RGBtoHSBK (RGB, temperature = 3500):
cmax = max(RGB)
cmin = min(RGB)
cdel = cmax - cmin
brightness = int((cmax/255) * 65535)
if cdel != 0:
saturation = int(((cdel) / cmax) * 65535)
redc = (cmax - RGB[0]) / (cdel)
greenc = (cmax - RGB[1]) / (cdel)
bluec = (cmax - RGB[2]) / (cdel)
if RGB[0] == cmax:
hue = bluec - greenc
else:
if RGB[1] == cmax:
hue = 2 + redc - bluec
else:
hue = 4 + greenc - redc
hue = hue / 6
if hue < 0:
hue = hue + 1
hue = int(hue*65535)
else:
saturation = 0
hue = 0
return (hue, saturation, brightness, temperature)
# function to convert the scale values to an RGB hex code
def getHSBK():
global gCycleHue
global gCycleSaturation
global gCycleBrightness
global gCycleKelvin
H = app.getScale("hueScale")
S = app.getScale("satScale")
B = app.getScale("briScale")
K = app.getScale("kelScale")
gCycleHue = int(H)
gCycleSaturation = int(S)
gCycleBrightness = int(B)
gCycleKelvin = int(K)
#RGB = "#"+str(R)+str(G)+str(B)
return {'H':H, 'S':S,'B':B, 'K':K }
# funciton to update widgets
def updateHSB(name):
# this stops the changes in slider/spin from constantly calling each other
#print ("name:",name)
# split the widget's name into the type & colour
colour = name[0:3]
widg = name[3:]
# get the current RGB value
HSBK = getHSBK()
#print("HSB:",HSB,"type(HSB)",type(HSB))
#print("H",HSB["H"])
#print("S",HSB["S"])
#print("B",HSB["B"])
# depending on the type, get & set...
if widg == "Scale":
value = app.getScale(name)
app.setSpinBox(colour + "Spin", value, callFunction = False)
elif widg == "Spin":
value = app.getSpinBox(name)
app.setScale(colour + "Scale", value, callFunction = False)
# update the label
h = HSBK["H"] / 65535.0;#print("h:",h)
s = HSBK["S"] / 65535.0;#print("s:",s)
v = HSBK["B"] / 65535.0;#print("v:",v)
k = HSBK["K"];#print("v:",v)
rgb1 = hsv_to_rgb(h, s, v);#print("rgb1:",rgb1)
c = Color(rgb=(rgb1[0], rgb1[1], rgb1[2]))
#print("c:",c)
app.setLabelBg("bulbcolor", c.hex_l)
global selected_bulb
bulbHSBK = [HSBK["H"],HSBK["S"],HSBK["B"],HSBK["K"]]
#print ("bulbHSBK:",bulbHSBK)
app.thread(updateBulbs, bulbHSBK )
#app.setEntry("colCode", RGB)
def updateBulbs(bulbHSBK):
global bulbs
global selected_bulb
try:
if (selected_bulb == "Select All Bulbs In LAN"):
lan.set_color_all_lights(bulbHSBK, duration=0, rapid=False)
elif (selected_bulb == "Select All Recalled Bulbs"):
for bulb in bulbs:
bulb.set_color(bulbHSBK, duration=0, rapid=False)
elif selected_bulb:
#print("sending color",hsv)
selected_bulb.set_color(bulbHSBK, duration=0, rapid=False)
except Exception as e:
#print (bulb)
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
'''
def selectTypeChanged(name):
global bulbs
if len(bulbs) < 1:
app.errorBox("Error", "Error. No bulbs were found yet. Please click the 'Find Bulbs' button and try again.")
app.setCheckBox("Select All", ticked=False, callFunction=False)
return
global gSelectAll
gSelectAll = (app.getOptionBox(SELECT_MODE)) ;print("gSelectAll: ",gSelectAll)
#app.getCheckBox("Select All")
#print("gSelectAll:",gSelectAll)
'''
def expectedPressed (name):
global gExpectedBulbs
global config
gExpectedBulbs = int(app.getSpinBox("Expected Bulbs"))
config['expectedbulbs'] = gExpectedBulbs
config.write()
print("gExpectedBulbs:",gExpectedBulbs)
def rgb_to_hsv(r, g, b):
r = float(r)
g = float(g)
b = float(b)
high = max(r, g, b)
low = min(r, g, b)
h, s, v = high, high, high
d = high - low
s = 0 if high == 0 else d / high
if high == low:
h = 0.0
else:
h = {
r: (g - b) / d + (6 if g < b else 0),
g: (b - r) / d + 2,
b: (r - g) / d + 4,
}[high]
h /= 6
return h, s, v
def hsv_to_rgb(h, s, v):
i = math.floor(h * 6)
f = h * 6 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
r, g, b = [
(v, t, p),
(q, v, p),
(p, v, t),
(p, q, v),
(t, p, v),
(v, p, q),
][int(i % 6)]
return r, g, b
def modeChanged():
global selectedMode
selectedMode = (app.getOptionBox("Desktop Mode"))#;print("selectedMode: ",selectedMode)
def listChanged():
app.clearTextArea("Result"); # TODO. Put this in another thread
app.setTextArea("Result", "Loading bulb details") # TODO. Put this in another thread
selected = (app.getOptionBox("LIFX Bulbs"))#;print("selected: ",selected)
global bulbs
global selected_bulb
global details
try:
for bulb in bulbs:
if (bulb.label == selected):
#print("Found selected bulb")
selected_bulb = bulb
details = str(selected_bulb)
#print("type(bulb)",type(bulb))
#print(bulb)
#print("breaking")
break
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
app.errorBox("Error", str(e))
app.clearTextArea("Result");
app.setTextArea("Result", str(e))
return
if ((selected == "Select All Bulbs In LAN") or (selected == "Select All Recalled Bulbs")):
app.clearTextArea("Result");
selected_bulb = selected
return
app.clearTextArea("Result")
app.setTextArea("Result", details)
try:
if "Power: On" in details:
#print ("BULB is ON")
app.setButtonImage("Light", resource_path("bulb_on.gif"))
elif "Power: Off" in details:
#print ("BULB is OFF ")
app.setButtonImage("Light", resource_path("bulb_off.gif"))
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
app.setButton ( "Light", "Toggle " + selected )
app.showButton("Light")
color = bulb.get_color();#print(color[0],color[1],color[2]);
h = color[0] / 65535.0;#print("h:",h)
s = color[1] / 65535.0;#print("s:",s)
v = color[2] / 65535.0;#print("v:",v)
rgb1 = hsv_to_rgb(h, s, v);#print("rgb1:",rgb1)
c = Color(rgb=(rgb1[0], rgb1[1], rgb1[2]))
#print("c:",c)
app.setLabelBg("bulbcolor", c.hex_l)
updateSliders(color)
def finder():
global bulbList
global lan
global gExpectedBulbs
global config
global lifxList
global lifxDict
global config
bulbList.clear()
bulbList.append("-Select Bulb-")
bulbList.append("Select All Bulbs In LAN")
bulbList.append("Select All Recalled Bulbs")
try:
global bulbs
#print("finder().gExpectedBulbs:",gExpectedBulbs)
lan = lifxlan.LifxLAN(int(gExpectedBulbs) if int(gExpectedBulbs) != 0 else None)
bulbs = lan.get_lights()
#print(type(bulbs))
#print(bulbs[0].label)
if len(bulbs) < 1:
app.errorBox("Error", "No bulbs found. Please try again. If you switched WiFi networks, please re-start the app and try again.")
app.setLabelBg("lbl2", "red")
app.setLabel("lbl2", "Found 0 bulbs")
return
else:
app.setLabelBg("lbl2", mygreen)
app.hideLabel("f1")
print(bulbs)
app.setLabel("lbl2", "Found " + str(len(bulbs)) + " bulbs")
del lifxList[:]
for bulb in bulbs:
#print(".get_label()",bulb.get_label()) # this gets the actual label
#print(".label:",bulb.label) # this returns None
label = bulb.get_label()
ip = bulb.ip_addr
mac = bulb.mac_addr
#print (label,ip,mac)
lifxDict['label'] = label
lifxDict['mac'] = mac
lifxDict['ip'] = ip
lifxList.append(lifxDict.copy())
bulbList.append(label)
app.changeOptionBox("LIFX Bulbs", bulbList, callFunction=False)
app.showButton ( "Pick Color" )
#print(lifxList)
#config['bulbs'] = lifxList
pkl.dump(lifxList, open(PICKLE, "wb" )) #this pickles
#exit(0)
#config.write()
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
app.setLabelBg("lbl2", "gray")
app.setLabel("lbl2", "Found 0 bulbs")
app.errorBox("Error", str(e) + "\n\nPlease try again. If you keep getting this error, check/toggle your WiFi, ensure that 'Expected Bulbs' is either 0 or the number of bulbs you have and finally, try restarting the app")
# config['bulbs'] = bulbs
# config.write()
print ("finder() Ended")
def press(name):
global bulbs
global details
global gSelectAll
global lan
global gwaveformcolor
global selected_bulb
global gCycleHue
global gCycleBrightness
global gCycleSaturation
#print(name, "button pressed")
if (name == "Find Bulbs"):
finder()
elif (name == "All Off"):
if len(bulbs) < 1:
return
lan.set_power_all_lights(False, rapid=True)
elif (name == "All Random"):
if len(bulbs) < 1:
return
selected = (app.getOptionBox("LIFX Bulbs"))
for bulb in bulbs:
hue = (randint(0, 65535))
sat = (randint(40000, 65535))
bulb.set_color([hue, sat, 65535, 3500], duration=0, rapid=True)
if (bulb.label == selected):
h = hue / 65535.0;#print("h:",h)
s = sat / 65535.0;#print("s:",s)
v = 1;#print("v:",v)
rgb1 = hsv_to_rgb(h, s, v);#print("rgb1:",rgb1)
c = Color(rgb=(rgb1[0], rgb1[1], rgb1[2]))
app.setLabelBg("bulbcolor", c.hex_l)
updateSliders([hue,sat,65535,3500])
elif (name == "All On"):
if len(bulbs) < 1:
return
lan.set_power_all_lights(True, rapid=True)
elif (name == "All White"):
if len(bulbs) < 1:
return
lan.set_color_all_lights([0,0,65535,3500], duration=0, rapid=True)
updateSliders([0,0,65535,3500])
app.setLabelBg("bulbcolor", "#FFFFFF")
elif (name == "Execute"):
waveform = app.getRadioButton("waveform")
config['waveform'] = waveform
if waveform == "Saw":
waveform = 0
elif waveform == "Sine":
waveform = 1
elif waveform == "HalfSine":
waveform = 2
elif waveform == "Triangle":
waveform = 3
elif waveform == "Pulse (Strobe)":
waveform = 4
#print ("waveform:",waveform)
is_transient = app.getCheckBox("Transient")
config['transient'] = is_transient
if (is_transient):
is_transient = 1
else:
is_transient = 0
#print("is_transient:",is_transient)
#pickedColor = app.getLabelBg("lblwaveformcolor")
#print("gwaveformcolor:",gwaveformcolor)
config['secondary_color'] = gwaveformcolor
c = Color(str(gwaveformcolor))
hsv = rgb_to_hsv(c.red, c.green, c.blue)
#print("hsv:",hsv)
bulbHSBK = [hsv[0] * 65535.0,hsv[1] * 65535.0,hsv[2] * 65535.0,3500]
#print (bulbHSBK)
period = app.getEntry("Period(ms)")
cycles = app.getEntry(CYCLES)
duty_cycle = app.getEntry("Duty Cycle")
config['period'] = period
config['cycles'] = cycles
config['duty_cycle'] = duty_cycle
config.write()
#print("period:",period)
#print("cycles:",cycles)
#print("duty_cycle:",duty_cycle)
if (selected_bulb == "Select All Bulbs In LAN"):
lan.set_waveform_all_lights(is_transient, bulbHSBK, period, cycles, duty_cycle, waveform, [1])
elif (selected_bulb == "Select All Recalled Bulbs"):
for bulb in bulbs:
bulb.set_waveform(is_transient, bulbHSBK, period, cycles, duty_cycle, waveform)
elif selected_bulb:
#print("sending color",hsv)
selected_bulb.set_waveform(is_transient, bulbHSBK, period, cycles, duty_cycle, waveform)
else:
app.errorBox("Error", "Error. No bulb was selected. Please select a bulb from the pull-down menu (or tick the 'Select All' checkbox) and try again.")
return
elif (name == "Secondary Color"):
pickedColor = app.colourBox(colour="#FF0000")
app.setLabelBg("lblwaveformcolor", pickedColor)
gwaveformcolor = pickedColor
elif (name == "Pick Color"):
pickedColor = app.colourBox(colour="#FFFFFF")
app.setLabelBg("bulbcolor", pickedColor)
#print("pickedColor:",pickedColor)
if pickedColor == None:
return
c = Color(str(pickedColor))
hsv = rgb_to_hsv(c.red, c.green, c.blue)
#print("hsv:",hsv)
bulbHSBK = [hsv[0] * 65535.0,hsv[1] * 65535.0,hsv[2] * 65535.0,3500]
gCycleHue = bulbHSBK[0]
gCycleSaturation = bulbHSBK[1]
gCycleBrightness = bulbHSBK[2]
#print ("bulbHSBK:",bulbHSBK)
updateBulbs(bulbHSBK)
if (selected_bulb == "Select All Bulbs In LAN"):
lan.set_color_all_lights(bulbHSBK, duration=0, rapid=False)
elif (selected_bulb == "Select All Recalled Bulbs"):
for bulb in bulbs:
bulb.set_color(bulbHSBK, duration=0, rapid=False)
elif selected_bulb:
#print("sending color",hsv)
selected_bulb.set_color(bulbHSBK, duration=0, rapid=False)
else:
app.errorBox("Error", "Error. No bulb was selected. Please select a bulb from the pull-down menu (or tick the 'Select All' checkbox) and try again.")
return
updateSliders(bulbHSBK)
elif (name == "Light"):
#print("selected: ",selected_bulb.label)
#print("Power is Currently: {}".format(selected_bulb.power_level))
try:
onOff = selected_bulb.power_level;
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
app.errorBox("Error", str(e) + "\n\nTry selecting a bulb from the list first.")
return
#selected_bulb.set_power(not selected_bulb.get_power(), duration=0, rapid=True)
if "Power: Off" in details:
selected_bulb.set_power(65535, duration=0, rapid=False)
try:
app.setButtonImage("Light", resource_path("bulb_on.gif"));#print("PowerOn");
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
details = details.replace("Power: Off", "Power: On");
app.clearTextArea("Result")
app.setTextArea("Result", details)
else:
selected_bulb.set_power(0, duration=0, rapid=False)
try:
app.setButtonImage("Light", resource_path("bulb_off.gif"));#print("PowerOff");
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
details = details.replace("Power: On", "Power: Off"); #print("details:\n",details)
app.clearTextArea("Result")
app.setTextArea("Result", details)
app.setButton ( "Light", "Toggle " + (app.getOptionBox("LIFX Bulbs")) )
app.showButton("Light")
#listChanged()
def rainbow_press(name):
global gExpectedBulbs
global bulbs
global lan
#print ("len(bulbs):",len(bulbs))
try:
print("Discovering lights...")
lan = lifxlan.LifxLAN(int(gExpectedBulbs) if int(gExpectedBulbs) != 0 else None)
if lan is None:
print("Error finding bulbs")
return
bulbs = lan.get_lights()
if len(bulbs) < 1:
print("No bulbs found. Exiting.")
return
#print("lan:",lan,"type(lan):",type(lan))
original_colors = lan.get_color_all_lights()
original_powers = lan.get_power_all_lights()
print("Turning on all lights...")
lan.set_power_all_lights(True)
sleep(1)
print("Flashy fast rainbow")
rainbow(lan, 0.4)
#print("Smooth slow rainbow")
#rainbow(lan, 1, smooth=True)
print("Restoring original color to all lights...")
for light in original_colors:
light.set_color(original_colors[light])
sleep(1)
print("Restoring original power to all lights...")
for light in original_powers:
light.set_power(original_powers[light])
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
def rainbow(lan, duration_secs=0.5, smooth=False):
colors = [RED, ORANGE, YELLOW, GREEN, CYAN, BLUE, PURPLE, PINK]
transition_time_ms = duration_secs * 1000 if smooth else 500
rapid = True if duration_secs < 1 else False
for i in range(0, 3):
for color in colors:
lan.set_color_all_lights(color, transition_time_ms, rapid)
sleep(duration_secs)
def maxPressed(name):
global maxSaturation
global maxBrightness
if (name == MAX_SATURATION):
maxSaturation = app.getCheckBox(MAX_SATURATION)
print(name, " is ", maxSaturation)
config['maxSaturation'] = maxSaturation
elif (name == MAX_BRIGHTNESS):
maxBrightness = app.getCheckBox(MAX_BRIGHTNESS)
print(name, " is ", maxBrightness)
config['maxBrightness']=maxBrightness
config.write()
def followDesktop():
global gSelectAll
global lan
global is_follow
global selected_bulb
global r
global maxSaturation
global maxBrightness
global bulbs
screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()
print("screen_width:", screen_width, " screen_height:", screen_height)
print("Follow:", is_follow)
duration = app.getEntry(TRANSITION_TIME)
is_evening = app.getCheckBox("Evening Mode")
config['transtime'] = duration
config['is_evening'] = is_evening
config.write()
print("r:", r)
print("Starting Loop")
left = r[0] # The x-offset of where your crop box starts
top = r[1] # The y-offset of where your crop box starts
width = r[2] # The width of crop box
height = r[3] # The height of crop box
box = (left, top, left + width, top + height)
if (is_follow):
app.hideEntry(TRANSITION_TIME)
app.hideOptionBox(DESKTOP_MODE)
app.showLabel(REGION_COLOR)
app.hideCheckBox("Evening Mode")
sct = mss()
while (is_follow):
start = time.time()
try:
# fast screenshot with mss module
sct_img = sct.grab(box)
image = Image.frombytes('RGB', sct_img.size, sct_img.rgb)
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
try:
# downsample to 1/10th and calculate average RGB color
pixels = np.array(image, dtype=np.float32)
pixels = pixels[::10,::10,:]
pixels = np.transpose(pixels)
dominant_color = [np.mean(channel) for channel in pixels]
c = Color(rgb=(dominant_color[0]/255, dominant_color[1]/255, dominant_color[2]/255))
app.setLabelBg(REGION_COLOR, c.hex_l)
# get HSVK color from RGB color
# during evenings, kelvin is 3500 (default value returned above)
# during the daytime, saturated colors are still 3500 K,
# but the whiter the color, the cooler, up to 5000 K
(h, s, v, k) = RGBtoHSBK(dominant_color)
if not is_evening:
k = int(5000 - (s/65535 * 1500))
if (maxSaturation) and (s > 6553):
s = 65535
if (maxBrightness) and (True):
v = 65535
bulbHSBK = [h, s, v, k]
try:
if (selected_bulb == "Select All Recalled Bulbs"):
for bulb in bulbs:
#print("bulb:{}".format(bulb))
bulb.set_color(bulbHSBK, duration=duration, rapid=True)
elif (selected_bulb == "Select All Bulbs In LAN"):
lan.set_color_all_lights(bulbHSBK, duration=duration, rapid=True)
elif selected_bulb:
selected_bulb.set_color(bulbHSBK, duration=duration, rapid=True)
else:
app.errorBox("Error", "Error. No bulb was selected. Please select a bulb from the pull-down menu (or tick the 'Select All' checkbox) and try again.")
app.setCheckBox("FOLLOW_DESKTOP", False)
is_follow = False
return
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
except Exception as e:
print ("Line:{}. Ignoring error:{}".format(lineno(),str(e)))
# rate limit to prevent from spamming bulbs
# the theoretical max speed that the bulbs can handle is one packet
# every 0.05 seconds, but empirically I found that 0.1 sec looked better
max_speed_sec = 0.1
elapsed_time = time.time() - start
wait_time = max_speed_sec - elapsed_time
if wait_time > 0:
sleep(wait_time)
#print(elapsed_time, time.time()-start)
print("Exiting loop")
def followDesktopPressed(name):
global is_follow
global r
global selectedMode
is_follow = app.getCheckBox(FOLLOW_DESKTOP)
app.showEntry(TRANSITION_TIME)
app.showOptionBox(DESKTOP_MODE)
app.showCheckBox("Evening Mode")
app.hideLabel(REGION_COLOR)
if (is_follow):
print("Pressed:", name, " Follow:", is_follow)
if (selectedMode == "Whole Screen"):
print("Doing Whole Screen processing")
screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()
r = (0, 0, screen_width, screen_height)
else:
print("Doing Partial Screen processing")
app.setTransparency(0)
app.infoBox("Select Region", "A new window entitled \"Screenshot\" will pop up. Drag a rectangle around the region of interest and press ENTER . This region's dominant color will be sent to the bulbs to match. To Cancel, press c .", parent=None)
myos = system()
if (myos == 'Linux') or (myos == 'Darwin'):
print("Mac OS detected.")
open_cv_image = np.array(ImageGrab.grab().convert('RGB'))
elif (myos == 'Windows'):
print("Windows OS detected.")
open_cv_image = np.array(image)
# Convert RGB to BGR
im = open_cv_image[:,:,::-1].copy()