-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlightcraft.py
More file actions
1732 lines (1616 loc) · 83.8 KB
/
lightcraft.py
File metadata and controls
1732 lines (1616 loc) · 83.8 KB
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
#LightCraft Source Code
#Made by Akash Samanta
#Version 2.8.8
import platform
import asyncio, _thread, os, time, webbrowser, re, subprocess, threading, pygame
from moviepy import VideoFileClip
from bleak import BleakClient
from PIL import Image
from pynput import keyboard
from customtkinter import * # type: ignore
import tkinter as tk
import tkinter.messagebox as messagebox
from CTkColorPicker import * # type: ignore
from functools import wraps
from lightcraft_cli import repeat, enableRepeat, disableRepeat
from mutagen.mp3 import MP3
import sys
import os
if getattr(sys, 'frozen', False):
os.chdir(os.path.dirname(sys.executable))
def get_external_path(relative_path):
try:
base_path = sys._MEIPASS # type: ignore
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
root = CTk()
if os.name == 'posix':
default_address = "EC4A4BDB-FC15-8CC5-FAB1-9EB6181DE9A5"
else:
default_address = "32:06:C2:00:0A:9E"
char_uuid = "FFD9"
isConnected = False
isOn = False
interval = 5
isFlashing = False
isPulsing = True
linkColour = "white"
isPlaying = False
isLinked = False
isLoaded = False
seekAmount = 0.5
isRepeating = False
repeatCmds, repeatCmdsChild = [],[]
defaultColour = "red"
shift_held = False
def on_press(key):
global shift_held
if key == keyboard.Key.shift:
shift_held = True
def on_release(key):
global shift_held
if key == keyboard.Key.shift:
shift_held = False
# Start listener thread
def start_keyboard_listener():
listener = keyboard.Listener(on_press=on_press, on_release=on_release)
listener.daemon = True
listener.start()
start_keyboard_listener()
#Custom Configuration
trailing_flash = leading_flash = trailing_pulse = leading_pulse = trailing_on = leading_on = trailing_off = leading_off = main_on = main_off = 0
trailing_single = leading_single = order_single = []
validColours = {
'red': [255, 0, 0],
'orange': [204, 51, 0],
'yellow': [153, 102, 0],
'brown': [153, 153, 0],
'gold': [204, 204, 0],
'green': [0, 255, 0],
'olive': [75, 128, 0],
'lime': [0, 128, 75],
'coral': [0, 128, 128],
'cyan': [0, 238, 238],
'blue': [0, 0, 255],
'teal': [0, 75, 128],
'indigo': [75, 0, 128],
'purple': [128, 0, 128],
'violet': [238, 0, 238],
'black': [0, 0, 0],
'white': [255, 255, 255],
'pink': [255, 0, 40],
'navy': [255, 0, 128],
'maroon': [255, 0, 204],
}
validFlashCode = {
'rgb_flash': 0x62,
'all_flash': 0x38,
'white_flash': 0x37,
'purple_flash': 0x36,
'cyan_flash': 0x35,
'yellow_flash': 0x34,
'blue_flash': 0x33,
'green_flash': 0x32,
'red_flash': 0x31,
'eyesore_flash': 0x30
}
validPulseCode = {
'gb_pulse': 0x2F,
'rb_pulse': 0x2E,
'rg_pulse': 0x2D,
'white_pulse': 0x2C,
'purple_pulse': 0x2B,
'cyan_pulse': 0x2A,
'yellow_pulse': 0x29,
'blue_pulse': 0x28,
'green_pulse': 0x27,
'red_pulse': 0x26,
'rgb_pulse': 0x61,
'all_pulse': 0x25
}
colourToRGB = {
'red': (255,0,0),
'green': (0,255,0),
'blue': (0,0,255),
'white': (255,255,255)
}
class BluetoothController:
def __init__(self, address, char_uuid):
self.address = address
self.char_uuid = char_uuid
self.client = None
self.loop = asyncio.new_event_loop()
self.connected = False
asyncio.set_event_loop(self.loop)
async def connect(self):
self.client = BleakClient(self.address)
try:
await self.client.connect()
self.connected = True
except Exception as e:
print(f"Failed to connect: {e}")
self.connected = False
def stop(self):
if self.loop.is_running():
self.loop.call_soon_threadsafe(self.loop.stop)
def close_loop():
if not self.loop.is_running():
self.loop.close()
self.loop.call_soon_threadsafe(close_loop)
async def disconnect(self):
if self.client:
await self.client.disconnect()
self.client = None
async def sendCmd(self, data):
if self.client:
await self.client.write_gatt_char(self.char_uuid, data)
def run_coroutine(self, coro):
return asyncio.run_coroutine_threadsafe(coro, self.loop)
def main():
global controller, loop_thread
pygame.init()
def debounce(wait):
def decorator(fn):
last_call = [0]
@wraps(fn)
def debounced(*args, **kwargs):
now = time.time()
if now - last_call[0] >= wait:
last_call[0] = now # type: ignore
return fn(*args, **kwargs)
return debounced
return decorator
#Connection Functions
def connect():
global isConnected
if isConnected:
isConnected = False
link_button.configure(state="disabled",fg_color=("#2b6b8f","#0f4d67"),hover_color=("#2b6b8f","#0f4d67"))
connect_button.configure(image=None,text="Connect", state="normal",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
radio_button_1.configure(state="disabled")
radio_button_2.configure(state="disabled")
radio_button_3.configure(state="disabled")
radio_button_4.configure(state="disabled")
alertButton.configure(state="disabled")
alertText.configure(text="Please connect your LED Strips first")
macInput.configure(state="normal")
macInputButton.configure(state="normal")
uuidInput.configure(state="normal")
uuidInputButton.configure(state="normal")
resetButton.configure(state="normal")
disconnect()
else:
future = controller.run_coroutine(controller.connect())
connect_button.configure(image=None,text="Connecting", state="disabled",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
macInput.configure(state="disabled")
macInputButton.configure(state="disabled")
uuidInput.configure(state="disabled")
uuidInputButton.configure(state="disabled")
resetButton.configure(state="disabled")
root.after(20, lambda: check_connection(future))
def check_connection(future):
global isConnected
if future.done():
if controller.connected:
isConnected = True
connect_button.configure(image=imgtk_bluetooth,text="Connected", fg_color="green", hover_color="#005500", state="normal")
if isLoaded:
link_button.configure(state="normal",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
if settings[4][:-1] == "1":
togglePower()
radio_button_1.configure(state="normal")
radio_button_2.configure(state="normal")
radio_button_3.configure(state="normal")
radio_button_4.configure(state="normal")
alertButton.configure(state="normal")
alertText.configure(text="This feature mimics real-life sounds. Use at your own risk.")
macInput.configure(state="disabled")
macInputButton.configure(state="disabled")
uuidInput.configure(state="disabled")
uuidInputButton.configure(state="disabled")
resetButton.configure(state="disabled")
else:
connect_button.configure(image=None,text="Reconnect", fg_color="#AA0000", hover_color="#880000", state="normal")
messagebox.showerror("Connection Failure", "LightCraft failed to connect with your LED Strips. Please make sure that your Bluetooth is turned on and that your LED Strips are not bonded with another device. Verify the MAC Address in Settings.")
macInput.configure(state="normal")
macInputButton.configure(state="normal")
uuidInput.configure(state="normal")
uuidInputButton.configure(state="normal")
resetButton.configure(state="normal")
else:
root.after(20, lambda: check_connection(future))
def disconnect():
controller.run_coroutine(controller.disconnect())
def togglePower():
global isOn
if not isOn:
isOn = True
power_button.configure(image=imgtk2)
data = bytearray([trailing_on,main_on,leading_on])
else:
isOn = False
power_button.configure(image=imgtk3)
data = bytearray([trailing_off,main_off,leading_off])
controller.run_coroutine(controller.sendCmd(data))
#Commands
def swapPulseFlash():
global isPulsing, isFlashing
if isPulsing:
isPulsing = False
isFlashing = True
pulseflash_var.set(pulseflash_var.get().replace("pulse","flash"))
else:
isPulsing = True
isFlashing = False
pulseflash_var.set(pulseflash_var.get().replace("flash","pulse"))
def sliderColourFun(sliderColour):
if sliderColour in ["all","rgb"]:
sliderColour = "white"
intervalSlider.configure(progress_color=sliderColour)
colorpicker.slider.configure(progress_color=sliderColour)
colorpicker.label.configure(fg_color=sliderColour)
def setBrightness(isUp):
curr_value = colorpicker.slider.get()
if isUp:
new_value = curr_value + 10
if new_value > 255:
new_value = 255
else:
new_value = curr_value - 10
if new_value < 0:
new_value = 0
colorpicker.slider.set(new_value)
colorpicker.update_colors()
sendHex(colorpicker.label.cget("text"))
def setInterval(isUp):
curr_value = intervalSlider.get()
if isUp:
new_value = curr_value + 1
if new_value > 10:
new_value = 10
else:
new_value = curr_value - 1
if new_value < 0:
new_value = 0
intervalSlider.set(new_value)
updateInterval()
@debounce(0.1)
def sendHex(data):
global trailing_single, leading_single, order_single
intervalSlider.configure(progress_color=data)
data = data[1:]
r = int(data[0:2], 16)
g = int(data[2:4], 16)
b = int(data[4:6], 16)
color_map = {'r': r, 'g': g, 'b': b}
rearranged_values = [color_map[color.lower()] for color in order_single]
data = bytearray(trailing_single + rearranged_values + leading_single)
controller.run_coroutine(controller.sendCmd(data))
def sendHexMusic(data):
data = data[1:]
data = bytearray([0x56, int(data[0:2], 16), int(data[2:4], 16), int(data[4:6], 16), 0x00, 0xf0, 0xaa])
controller.run_coroutine(controller.sendCmd(data))
def sendColourMusic(data):
hex_value = '#{:02x}{:02x}{:02x}'.format(*validColours[data])
sendHexMusic(hex_value)
@debounce(1)
def sendRepeatMusic(data,times):
global isRepeating, threadRepeat
isRepeating = True
start = int(data.split("-")[0])-1
end = int(data.split("-")[1])-1
threadRepeat = _thread.start_new_thread(sendRepeatMusicThread, (start, end, int(times)))
def sendRepeatMusicThread(start, end, times):
global isRepeating, cmds
c = start
f = 0
while isRepeating:
if c+1 <= end:
delay = (int(data[c+1].split(",")[1])-int(data[c].split(",")[1]))/1000
else:
c = start
f += 1
if f == times:
isRepeating = False
break
else:
continue
cmd = cmds[c]
func_name, args_str = cmd[:-1].split('(')
args = args_str.split('.') if args_str else []
command_functions[func_name](*args)
time.sleep(delay)
c += 1
@debounce(0.1)
def sendColourCB(button,index):
global settings
if shift_held:
button.configure(fg_color="#FFFFFF")
colorpicker.slider.configure(progress_color="#FFFFFF")
colorpicker.label.configure(text="#FFFFFF",fg_color="#FFFFFF")
sendHex("#FFFFFF")
settings[index] = "#FFFFFF\n"
writesettings()
else:
if colorpicker.dragging == True:
colorpicker.dragging = False
button.configure(fg_color=colorpicker.label.cget("text"))
sendHex(colorpicker.label.cget("text"))
settings[index] = colorpicker.label.cget("text") + "\n"
writesettings()
else:
colorpicker.slider.configure(progress_color=settings[index][:-1])
colorpicker.label.configure(text=settings[index][:-1],fg_color=settings[index][:-1])
sendHex(settings[index][:-1])
@debounce(0.1)
def sendColourWB(r,g,b):
global linkColour
if (r==255 and g==255 and b==255):
linkColour = "white"
elif (r==255 and g==0 and b==0):
linkColour = "red"
elif (r==0 and g==255 and b==0):
linkColour = "green"
elif (r==0 and g==0 and b==255):
linkColour = "blue"
else:
linkColour = "unset"
if linkColour!="unset":
if isPulsing:
pulseflash_var.set(linkColour+"_pulse")
if isFlashing:
pulseflash_var.set(linkColour+"_flash")
colorpicker.update_colors(r,g,b)
sendHex(colorpicker.label.cget("text"))
@debounce(0.1)
def sendPulse(isSet=False):
global isPulsing, isFlashing, linkColour
isPulsing = True
isFlashing = False
if isSet==False:
data = bytearray([trailing_pulse,validPulseCode[pulseflash_var.get()],int(interval),leading_pulse])
linkColour = "unset"
sliderColourFun(pulseflash_var.get().split("_")[0])
else:
data = bytearray([trailing_pulse,validPulseCode[linkColour+"_pulse"],int(interval),leading_pulse])
controller.run_coroutine(controller.sendCmd(data))
def sendPulseMusic(colour, freq):
if colour == "rainbow":
colour = "all"
elif colour == "primary":
colour = "rgb"
elif colour == "red blue":
colour = "rb"
elif colour == "green blue":
colour = "gb"
elif colour == "red green":
colour = "rg"
data = bytearray([trailing_pulse,validPulseCode[colour+"_pulse"],10-int(freq),leading_pulse])
controller.run_coroutine(controller.sendCmd(data))
@debounce(0.1)
def sendFlash(isSet=False):
global isPulsing, isFlashing, linkColour
isPulsing = False
isFlashing = True
if isSet==False:
data = bytearray([trailing_flash,validFlashCode[pulseflash_var.get()],int(interval),leading_flash])
linkColour = "unset"
sliderColourFun(pulseflash_var.get().split("_")[0])
else:
data = bytearray([trailing_flash,validFlashCode[linkColour+"_flash"],int(interval),leading_flash])
controller.run_coroutine(controller.sendCmd(data))
def sendFlashMusic(colour, freq):
if colour == "rainbow":
colour = "all"
elif colour == "primary":
colour = "rgb"
data = bytearray([trailing_flash,validFlashCode[colour+"_flash"],10-int(freq),leading_flash])
controller.run_coroutine(controller.sendCmd(data))
@debounce(0.1)
def updateInterval():
global interval
interval = 10 - intervalSlider.get()
if isPulsing:
sendPulse(linkColour!="unset")
if isFlashing:
sendFlash(linkColour!="unset")
def sgButton(frame,row,col,colour):
global customColour1, customColour2, customColour3, customColour4, customColour5
r, g, b = map(int, validColours[colour])
if col == 4:
match row:
case 0:
customColour1 = CTkButton(frame,text="", fg_color=settings[7][:-1], hover=False, font=CTkFont(size=bsize), width=sgwidth, corner_radius=sgradius, height=sgheight, command=lambda: sendColourCB(customColour1,7))
customColour1.grid(row=row,column=col,padx=(10,0),pady=(10,0))
case 1:
customColour2 = CTkButton(frame,text="", fg_color=settings[8][:-1], hover=False, font=CTkFont(size=bsize), width=sgwidth, corner_radius=sgradius, height=sgheight, command=lambda: sendColourCB(customColour2,8))
customColour2.grid(row=row,column=col,padx=(10,0),pady=(10,0))
case 2:
customColour3 = CTkButton(frame,text="", fg_color=settings[9][:-1], hover=False, font=CTkFont(size=bsize), width=sgwidth, corner_radius=sgradius, height=sgheight, command=lambda: sendColourCB(customColour3,9))
customColour3.grid(row=row,column=col,padx=(10,0),pady=(10,0))
case 3:
customColour4 = CTkButton(frame,text="", fg_color=settings[10][:-1], hover=False, font=CTkFont(size=bsize), width=sgwidth, corner_radius=sgradius, height=sgheight, command=lambda: sendColourCB(customColour4,10))
customColour4.grid(row=row,column=col,padx=(10,0),pady=(10,0))
case 4:
customColour5 = CTkButton(frame,text="", fg_color=settings[11][:-1], hover=False, font=CTkFont(size=bsize), width=sgwidth, corner_radius=sgradius, height=sgheight, command=lambda: sendColourCB(customColour5,11))
customColour5.grid(row=row,column=col,padx=(10,0),pady=(10,0))
else:
CTkButton(frame,text="", fg_color="#{:02x}{:02x}{:02x}".format(r, g, b), hover=False, font=CTkFont(size=bsize), width=sgwidth, corner_radius=sgradius, height=sgheight, command=lambda: sendColourWB(r,g,b)).grid(row=row,column=col,padx=(10,0),pady=(10,0))
#Settings Functions
def macInputSave():
global settings, address
address = macInputVar.get()
if os.name == 'posix' and platform.system() == 'Darwin':
settings[2] = macInputVar.get() + "\n"
writesettings()
recreate_controller()
macInputButton.configure(state="disabled", text="Saved", fg_color="green")
macInputButton.after(1000, lambda: macInputButton.configure(state="normal", text="Save", fg_color="#1f6aa5"))
elif validate_mac_address(macInputVar.get()):
settings[2] = macInputVar.get() + "\n"
writesettings()
recreate_controller()
macInputButton.configure(state="disabled", text="Saved", fg_color="green")
macInputButton.after(1000, lambda: macInputButton.configure(state="normal", text="Save", fg_color="#1f6aa5"))
else:
messagebox.showerror("Invalid MAC Address", "Please enter a valid MAC address.")
def validate_mac_address(mac_address):
# MAC address format: XX:XX:XX:XX:XX:XX
mac_regex = r'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$'
if re.match(mac_regex, mac_address):
return True
else:
return False
def uuidInputSave():
global settings, char_uuid
char_uuid = uuidInputVar.get()
if len(uuidInputVar.get()) == 4:
settings[3] = uuidInputVar.get() + "\n"
writesettings()
recreate_controller()
uuidInputButton.configure(state="disabled", text="Saved", fg_color="green")
uuidInputButton.after(1000, lambda: uuidInputButton.configure(state="normal", text="Save", fg_color="#1f6aa5"))
else:
messagebox.showerror("Invalid UUID", "Please enter a UUID with exactly 4 characters.")
def start_event_loop(controller):
asyncio.set_event_loop(controller.loop)
controller.loop.run_forever()
def recreate_controller():
global controller, loop_thread,address, char_uuid
# Stop the previous controller and thread, if they exist
if 'controller' in globals() and controller is not None:
controller.stop()
if loop_thread.is_alive():
loop_thread.join()
# Start the new controller
controller = BluetoothController(address, char_uuid)
loop_thread = threading.Thread(target=start_event_loop, args=(controller,))
loop_thread.start()
def toggleAutoCS():
global settings
settings[4] = str(autoCSVar.get()) + "\n"
writesettings()
def toggleKeyBind():
global settings
settings[5] = str(keyBindVar.get()) + "\n"
if keyBindVar.get()==0:
unbindAll()
else:
updateTab()
writesettings()
def toggleLoaded():
global settings
if loadedVar.get()==0:
settings[12] = "Save\n"
settings[6] = str(loadedVar.get()) + "\n"
writesettings()
def toggleTheme():
global settings
settings[14] = str(darkModeVar.get()) + "\n"
messagebox.showinfo("Theme Change","The theme will change after you restart LightCraft.")
writesettings()
def showMusic():
config_dir = os.path.join(os.getcwd(), "Configurations")
if not os.path.exists(config_dir):
os.makedirs(config_dir)
if os.name == 'nt':
os.startfile(config_dir)
elif os.name == 'posix':
subprocess.Popen(['open', config_dir])
else:
messagebox.showerror("Unsupported OS", "This feature is not supported on your operating system.")
def updateDefaultColour(value):
global defaultColour
defaultColour = defaultColourVar.get().lower()
settings[15] = defaultColourVar.get() + "\n"
writesettings()
if isConnected:
sendColourMusic(defaultColour)
def openManual():
webbrowser.open(r"www.github.com/akashcraft/LED-Controller/wiki")
def openSettings():
if os.path.exists("Settings.txt"):
if os.name == 'nt':
subprocess.Popen(["Settings.txt"], shell=True)
elif os.name == 'posix':
subprocess.Popen(['open', 'Settings.txt'])
else:
messagebox.showerror("Unsupported OS", "This feature is not supported on your operating system.")
else:
messagebox.showerror("Unable to Load Configuration", "The settings file seems to be missing. LightCraft will attempt to restore default settings.")
#Alert Functions
def playAlert():
global interval
if not isOn:
togglePower()
enableRepeat()
alert = alert_var.get()
pulseflash_var.set("red_pulse")
match alert:
case 0:
pygame.mixer.music.load(r"./Resources/italyAlert.mp3")
loop_thread1 = threading.Thread(target=lambda: asyncio.run(repeat(controller.client, char_uuid, '["0.3 red","0.3 pink"]', 100))) # type: ignore
loop_thread1.start()
case 1:
pygame.mixer.music.load(r"./Resources/japanAlert.mp3")
interval = 0
sendPulse()
case 2:
pygame.mixer.music.load(r"./Resources/franceAlert.mp3")
interval = 1
sendPulse()
case 3:
pygame.mixer.music.load(r"./Resources/usaAlert.mp3")
interval = 6
sendPulse()
intervalSlider.set(10-interval)
pygame.mixer.music.play()
alertButton.configure(text="Stop Alert", fg_color="#AA0000", hover_color="#880000", command=stopAlert)
def stopAlert():
pygame.mixer.music.stop()
pygame.mixer.music.unload()
disableRepeat()
sendColourMusic(defaultColour)
alertButton.configure(text="Play Alert",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"), command=playAlert)
#Music Functions
def get_vlength(video_path):
with VideoFileClip(video_path) as video:
duration = video.duration
return duration
def extract_av(video_path, audio_path):
video = VideoFileClip(video_path)
audio = video.audio
if audio is not None:
audio.write_audiofile(audio_path)
def clearload():
global repeatCmdsChild, repeatCmds, prohibited_times
repeatCmds, repeatCmdsChild, prohibited_times = [],[],[]
load_button.configure(fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
heading3.configure(text="No Media Loaded")
if (isLinked and isConnected):
link_button.configure(fg_color="green", hover_color="#005500")
elif isConnected:
link_button.configure(fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
else:
link_button.configure(state="disabled",fg_color=("#2b6b8f","#0f4d67"))
play_button.configure(state="disabled",fg_color=("#2b6b8f","#0f4d67"))
add_button.configure(state="disabled",fg_color=("#2b6b8f","#0f4d67"))
seek_button.configure(state="disabled",fg_color=("#2b6b8f","#0f4d67"))
stop_button.configure(state="disabled",fg_color=("#2b6b8f","#0f4d67"))
music_slider.set(0)
music_slider.configure(state="disabled")
total_time.configure(text="00:00.0")
actual_time.configure(text="00:00.0")
musicframechild.grid_forget()
def load(autoload=False):
global isLoaded, music_length, position, config_file_path, data, music, next_index, last_pos, isVideo
if isLoaded and isPlaying:
stop()
pygame.mixer.music.unload()
if not autoload:
music = filedialog.askopenfilename(filetypes=[("Media Files", "*.mp3 *.mp4")])
if music == "":
isLoaded = False
return
else:
clearload()
else:
music = settings[12][:-1]
for child in musicframechild.grid_slaves():
child.grid_remove()
musicframe.event_generate("<MouseWheel>", delta=1000*120)
try:
#Load Successful
config_dir = os.path.join(os.getcwd(), "Configurations")
if not os.path.exists(config_dir):
os.makedirs(config_dir)
music_name = os.path.basename(music).split(".")[0]
config_file_path = os.path.join(config_dir, f"{music_name} LightCraft.txt")
if not os.path.exists(config_file_path):
fobj = open(config_file_path, "w")
fobj.close()
fobj = open(config_file_path, "r")
data = fobj.readlines()
fobj.close()
#Config Load Successful
isLoaded = True
musicframechild.grid(row=0,column=0,padx=0,pady=0, sticky='nsew')
video = music
if music.endswith(".mp3"):
audio = MP3(music)
music_length = audio.info.length
isVideo = False
elif music.endswith(".mp4"):
music_length = get_vlength(music)
isVideo = True
try:
if not os.path.exists(os.path.join(config_dir, f"{music_name} LightCraft.mp3")):
messagebox.showinfo("Extracting Audio","LightCraft needs to extract the audio from the selected video. This may take a few seconds.")
extract_av(music, os.path.join(config_dir, f"{music_name} LightCraft.mp3"))
except:
messagebox.showerror("Unable to Extract Audio","LightCraft was unable to extract the audio from the selected video. Please make sure that the file is not corrupted and that it is a valid video file. Try a different video and if the problem persists, please contact the developer.")
clearload()
isLoaded = False
return
music = os.path.join(config_dir, f"{music_name} LightCraft.mp3")
else:
music_length = 0
loadConfig()
load_button.configure(fg_color="green", hover_color="#005500")
heading3.configure(text=music_name)
music_slider.configure(state="normal",to=int(music_length*1000))
play_button.configure(state="normal",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
add_button.configure(state="normal",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
seek_button.configure(state="normal", text=str(seekAmount).rstrip('0').rstrip('.') + "s",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
stop_button.configure(state="normal",fg_color=("#3b8ed0","#1f6aa5"),hover_color=("#36719f","#144870"))
total_time.configure(text=time.strftime("%M:%S", time.gmtime(music_length))+"."+format_ms(int(music_length*1000)))
pygame.mixer.music.load(music)
pygame.mixer.music.play()
pygame.mixer.music.pause()
last_pos = 0
position = 0
next_index = 0
if settings[6][:-1] == "1":
if isVideo:
settings[12] = video + "\n"
else:
settings[12] = music + "\n"
writesettings()
except:
#Load Failed
clearload()
isLoaded = False
messagebox.showerror("Unable to Load Media","LightCraft was unable to load the selected media. Please make sure that the file is not corrupted and that it is a valid media file. Delete any corrupted configuration file. Try a different media and if the problem persists, please contact the developer.")
command_functions = {'sendColourMusic': sendColourMusic,'sendFlashMusic': sendFlashMusic,'sendPulseMusic': sendPulseMusic,'sendHexMusic': sendHexMusic,'sendRepeatMusic':sendRepeatMusic}
def update_music_slider():
global isPlaying, position, cmds, isRepeating, next_index
if isPlaying:
position = last_pos + pygame.mixer.music.get_pos()
music_slider.set(position)
if abs(position - (music_length * 1000)) < 300:
root.after(300, stop)
music_slider.set(int(music_length * 1000))
actual_time.configure(text=time.strftime("%M:%S", time.gmtime(music_length))+"."+format_ms(int(music_length*1000)))
else:
actual_time.configure(text=time.strftime("%M:%S", time.gmtime(position // 1000)) + "." + format_ms(position % 1000))
if isLinked and next_index != -1:
try:
if abs(position-prohibited_times[next_index]) < 200:
cmd = cmds[next_index]
func_name, args_str = cmd[:-1].split('(')
args = args_str.split('.') if args_str else []
command_functions[func_name](*args)
next_index += 1
if next_index == len(prohibited_times):
next_index = -1
except:
next_index = -1
root.after(100, update_music_slider)
else:
return
def set_music_slider(offset=0):
global position, isRepeating, next_index, last_pos
isRepeating = False
if isLinked:
sendColourMusic(defaultColour)
if offset == 0:
new_pos = music_slider.get()
else:
new_pos = position + (offset * 1000)
if new_pos < 0:
new_pos = 0
elif new_pos > (music_length * 1000):
new_pos = music_length * 1000
pygame.mixer.music.play(0, new_pos//1000)
if not isPlaying:
pygame.mixer.music.pause()
music_slider.set(new_pos)
last_pos = new_pos
position = int(new_pos)
for i in range(len(prohibited_times)):
if position <= prohibited_times[i]:
next_index = i
break
else:
next_index = -1
actual_time.configure(text=time.strftime("%M:%S", time.gmtime(position/1000))+"."+format_ms(position%1000))
def format_ms(ms):
if ms < 100:
return "0"
else:
return str(ms)[:1]
def play():
global isPlaying, isRepeating, next_index, position
isRepeating = False
for i in range(len(prohibited_times)):
if position <= prohibited_times[i]:
next_index = i
break
else:
next_index = -1
if not isPlaying:
isPlaying = True
play_button.configure(image=imgtk_pause)
pygame.mixer.music.unpause()
update_music_slider()
else:
isPlaying = False
if isLinked:
sendColourMusic(defaultColour)
play_button.configure(image=imgtk_play)
pygame.mixer.music.pause()
@debounce(0.3)
def stop():
global isPlaying, position, isRepeating, last_pos, player_main
last_pos = 0
isRepeating = False
position = 0
actual_time.configure(text="00:00.0")
music_slider.set(0)
if isLinked:
sendColourMusic(defaultColour)
play_button.configure(image=imgtk_play)
pygame.mixer.music.play()
pygame.mixer.music.pause()
isPlaying = False
def loadConfig():
global cmd_frames, prohibited_times, fobj, data, cmds, repeatCmds, repeatCmdsChild
cmd_frames, prohibited_times, cmds = [],[],[]
flag = 0
for i in range(len(data)):
cmd = data[i].split(",")
index = int(cmd[0])-1
prohibited_times.append(int(cmd[1]))
newFrame = CTkFrame(musicframechild, corner_radius=5, fg_color=("#ebebeb","#515151"))
newFrame.grid_columnconfigure(6, weight=1)
newFrame.grid(row=index,column=0,padx=(0,5),pady=1, sticky='ew')
label1 = CTkLabel(newFrame, text=cmd[0], font=CTkFont(size=13), width=15, height=5)
label1.grid(row=0,column=0,padx=(10,0),pady=5, sticky='w')
label2 = CTkLabel(newFrame, text=cmd[2], font=CTkFont(size=13), height=5)
label2.grid(row=0,column=1,padx=(10,5),pady=5, sticky='w')
controlType = tk.StringVar(value=cmd[3])
if controlType.get() == "Repeat":
if i not in repeatCmds:
repeatCmds.append(i)
newFrame.configure(fg_color=("#c8c8c8","#3a3a3a"))
secondControl = tk.StringVar(value=cmd[4])
start = int(secondControl.get().split("-")[0])-1
end = int(secondControl.get().split("-")[1])-1
for j in range(start, end+1):
if j not in repeatCmdsChild:
repeatCmdsChild.append(j)
if (flag < 3):
combo1 = CTkComboBox(newFrame,variable=controlType, values=["Single","Hex","RGB","Pulse","Flash"], width=70, height=10, border_width=0, corner_radius=3, command=lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
flag = flag + 1
else:
combo1 = CTkComboBox(newFrame,variable=controlType, values=["Single","Hex","RGB","Pulse","Flash","Repeat"], width=70, height=10, border_width=0, corner_radius=3, command=lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo1.grid(row=0,column=3,padx=(5,0),pady=0, sticky='w')
combo1.bind("<FocusIn>", lambda e: root.focus_set())
combo2, combo3, save_button, del_button, copy_button = frameCreator(newFrame, index, cmd, controlType.get())
cmds.append(cmd[7])
cmd_frames.append([newFrame, combo1, combo2, combo3, save_button, del_button, copy_button, label1])
for i in repeatCmdsChild:
cmd_frames[i][1].configure(values=["Single","Hex","RGB","Pulse","Flash"])
cmd_frames[i][5].configure(state="disabled", image=imgtk_del_no)
cmd_frames[i][0].configure(fg_color=("#c8c8c8","#3a3a3a"))
def frameCreator(newFrame, index, cmd, controlType):
secondControl= tk.StringVar(value=cmd[4])
thirdControl = tk.StringVar(value=cmd[5])
save_button = CTkButton(newFrame, text="", image=imgtk_save, fg_color="transparent", width=5, height=5)
copy_button = CTkButton(newFrame, text="", image=imgtk_copy, fg_color="transparent", width=5, height=5)
if controlType == "Single":
combo2 = CTkComboBox(newFrame, variable=secondControl, values=[color.capitalize() for color in validColours.keys()], width=70, height=10, border_width=0, corner_radius=3, command= lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo2.grid(row=0,column=4,padx=(5,0),pady=0, sticky='w')
combo3 = None
elif controlType == "Flash":
combo2 = CTkComboBox(newFrame, variable=secondControl, values=['Rainbow', 'Primary', 'Red', 'Green', 'Blue', 'White', 'Purple', 'Cyan', 'Yellow'], width=70, height=10, border_width=0, corner_radius=3, command= lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo2.grid(row=0,column=4,padx=(5,0),pady=0, sticky='w')
combo3 = CTkComboBox(newFrame, variable=thirdControl, values=['0','1','2','3','4','5','6','7','8','9','10'], width=70, height=10, border_width=0, corner_radius=3, command= lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo3.grid(row=0,column=5,padx=(5,0),pady=0, sticky='w')
elif controlType == "Pulse":
combo2 = CTkComboBox(newFrame, variable=secondControl, values=['Rainbow', 'Primary', 'Red', 'Green', 'Blue', 'Green Blue', 'Red Blue', 'Red Green', 'White', 'Purple', 'Cyan', 'Yellow'], width=70, height=10, border_width=0, corner_radius=3, command= lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo2.grid(row=0,column=4,padx=(5,0),pady=0, sticky='w')
combo3 = CTkComboBox(newFrame, variable=thirdControl, values=['0','1','2','3','4','5','6','7','8','9','10'], width=70, height=10, border_width=0, corner_radius=3, command= lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo3.grid(row=0,column=5,padx=(5,0),pady=0, sticky='w')
elif controlType == "Repeat":
combo3 = CTkComboBox(newFrame, variable=thirdControl, values=['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'], width=70, height=10, border_width=0, corner_radius=3, command= lambda value, index=index, cmd=cmd: editCmd(index, cmd, value))
combo3.grid(row=0,column=5,padx=(5,0),pady=0, sticky='w')
elif controlType == "RGB":
t = secondControl.get()
r = int(t[0:2], 16)
g = int(t[2:4], 16)
b = int(t[4:6], 16)
secondControl.set(f"{r} {g} {b}")
if controlType not in ["Hex","RGB","Repeat"]:
combo2.bind("<FocusIn>", lambda e: root.focus_set())
else:
combo2 = CTkEntry(newFrame, textvariable=secondControl, width=70, height=10, border_width=0, corner_radius=3)
combo2.grid(row=0,column=4,padx=(5,0),pady=0, sticky='w')
save_button.configure(command= lambda value=combo2.get(), index=index, cmd=cmd: editCmd(index, cmd, value))
save_button.grid(row=0,column=7,padx=0,pady=0, sticky='e')
combo3 = None
combo2.bind("<FocusIn>", lambda e: unbindAll())
combo2.bind("<FocusOut>", lambda e: bindMusic())
combo2.bind("<Return>", lambda e: save_button.invoke())
if combo3!=None:
combo3.bind("<FocusIn>", lambda e: root.focus_set())
del_button = CTkButton(newFrame, text="", image=imgtk_del, fg_color="transparent", hover_color="dark red", width=5, height=5, command= lambda index=index, cmd=cmd: delCmd(index, cmd))
del_button.grid(row=0,column=9,padx=(0,5),pady=0, sticky='e')
copy_button = CTkButton(newFrame, text="", image=imgtk_copy, fg_color="transparent", hover_color="#877c00", width=5, height=5, command= lambda cmd=cmd: addCmd(True, cmd))
copy_button.grid(row=0,column=8,padx=0,pady=0, sticky='e')
return combo2, combo3, save_button, del_button, copy_button
def delCmd(index, cmd):
global data, repeatCmds, repeatCmdsChild
del data[index]
if cmd[3] == "Repeat":
repeatCmds.remove(index)
start = int(cmd[4].split("-")[0])-1
end = int(cmd[4].split("-")[1])-1
for i in range(start, end+1):
repeatCmdsChild.remove(i)
for i in range(index, len(data)):
cmd = data[i].split(",")
cmd[0] = str(i+1)
data[i] = ','.join(cmd)
refreshCmds()
def refreshCmds():
fobj = open(config_file_path, "w")
fobj.writelines(data)
fobj.close()
for child in musicframechild.grid_slaves():
child.grid_remove()
musicframe.event_generate("<MouseWheel>", delta=1000*120)
loadConfig()
def editCmd(index, cmd, value):
global data, fobj, cmds, repeatCmds, prohibited_times, repeatCmdsChild
cmd_frame = cmd_frames[index]
controlType = cmd[3]
if value in ["Single","Hex","RGB","Pulse","Flash","Repeat"]: #Major Change
if value != controlType:
cmd[3] = value
cmd_frame[2].grid_forget()
if cmd_frame[3] != None:
cmd_frame[3].grid_forget()
cmd_frame[4].grid_forget()
cmd_frame[5].grid_forget()
if value == "Single":
cmd[4] = "Red"
cmd[7] = "sendColourMusic(red)"
elif value == "Flash":
cmd[4] = "Red"
cmd[5] = "10"
cmd[7] = "sendFlashMusic(red.10)"
elif value == "Pulse":
cmd[4] = "Red"
cmd[5] = "10"
cmd[7] = "sendPulseMusic(red.10)"
elif value == "Hex":
cmd[4] = "FF0000"
cmd[7] = "sendHexMusic(#FF0000)"
elif value == "RGB":
cmd[4] = "FF0000"
cmd[7] = "sendHexMusic(#FF0000)"
elif value == "Repeat":
cmd[4] = "1-3"
cmd[5] = "1"
cmd[7] = "sendRepeatMusic(1-3)"
if index not in repeatCmds:
repeatCmds.append(index)