forked from onlaj/Piano-LED-Visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualizer.py
2142 lines (1853 loc) · 98.2 KB
/
visualizer.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
from subprocess import call
from xml.dom import minidom
import xml.etree.ElementTree as ET
import ast
import LCD_1in44
import LCD_Config
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL import ImageColor
import RPi.GPIO as GPIO
import time
import random
import webcolors as wc
import sys
import os
import datetime
import psutil
import fcntl
os.chdir(sys.path[0])
import mido
from mido import MidiFile, Message, tempo2bpm, MidiTrack,MetaMessage
from neopixel import *
import argparse
import threading
# Ensure there is only one instance of the script running.
fh=0
def singleton():
global fh
fh=open(os.path.realpath(__file__),'r')
try:
fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK_NB)
except:
restart_script()
def restart_script():
python = sys.executable
os.execl(python, python, *sys.argv)
singleton()
class UserSettings:
def __init__(self):
self.pending_changes = False
try:
self.tree = ET.parse("settings.xml")
self.root = self.tree.getroot()
except:
print("Can't load settings file, restoring defaults")
self.reset_to_default()
self.pending_reset = False
def get_setting_value(self, name):
value = self.root.find(name).text
return value
def change_setting_value(self, name, value):
self.root.find(str(name)).text = str(value)
self.pending_changes = True
def save_changes(self):
if(self.pending_changes == True):
self.pending_changes = False
self.tree.write("settings.xml")
self.tree = ET.parse("settings.xml")
self.root = self.tree.getroot()
def reset_to_default(self):
self.tree = ET.parse("default_settings.xml")
self.tree.write("settings.xml")
self.root = self.tree.getroot()
self.pending_reset = True
class LedStrip:
def __init__(self):
self.brightness_percent = int(usersettings.get_setting_value("brightness_percent"))
self.led_number = int(usersettings.get_setting_value("led_count"))
self.shift = int(usersettings.get_setting_value("shift"))
self.brightness = 255 * self.brightness_percent / 100
self.keylist = [0] * self.led_number
self.keylist_status = [0] * self.led_number
self.keylist_color = [0] * self.led_number
# LED strip configuration:
self.LED_COUNT = int(self.led_number) # Number of LED pixels.
self.LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
#LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
self.LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
self.LED_DMA = 10 # DMA channel to use for generating signal (try 10)
self.LED_BRIGHTNESS = int(self.brightness) # Set to 0 for darkest and 255 for brightest
self.LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
self.LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
args = parser.parse_args()
# Create NeoPixel object with appropriate configuration.
self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, self.LED_BRIGHTNESS, self.LED_CHANNEL)
# Intialize the library (must be called once before other functions).
self.strip.begin()
def change_brightness(self, value):
self.brightness_percent += value
if(self.brightness_percent <= 0):
self.brightness_percent = 1
elif(self.brightness_percent > 100):
self.brightness_percent = 100
self.brightness = 255 * self.brightness_percent / 100
usersettings.change_setting_value("brightness_percent", self.brightness_percent)
if(menu.screensaver_is_running == True):
menu.screensaver_is_running = False
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
args = parser.parse_args()
self.strip = Adafruit_NeoPixel(self.LED_COUNT, self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, int(self.brightness), self.LED_CHANNEL)
# Intialize the library (must be called once before other functions).
self.strip.begin()
fastColorWipe(ledstrip.strip, True)
def change_led_count(self, value):
self.led_number += value
if(self.led_number <= 0):
self.led_number = 1
usersettings.change_setting_value("led_count", self.led_number)
self.keylist = [0] * self.led_number
self.keylist_status = [0] * self.led_number
self.keylist_color = [0] * self.led_number
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
args = parser.parse_args()
self.strip = Adafruit_NeoPixel(int(self.led_number), self.LED_PIN, self.LED_FREQ_HZ, self.LED_DMA, self.LED_INVERT, int(self.brightness), self.LED_CHANNEL)
# Intialize the library (must be called once before other functions).
self.strip.begin()
fastColorWipe(ledstrip.strip, True)
def change_shift(self, value):
self.shift += value
usersettings.change_setting_value("shift", self.shift)
fastColorWipe(ledstrip.strip, True)
def set_adjacent_colors(self, note, color):
if(ledsettings.adjacent_mode == "RGB" and color != 0):
color = Color(int(ledsettings.adjacent_green), int(ledsettings.adjacent_red), int(ledsettings.adjacent_blue))
if(ledsettings.adjacent_mode != "Off"):
self.strip.setPixelColor(int(note)+1, color)
self.strip.setPixelColor(int(note)-1, color)
KEYRIGHT = 26
KEYLEFT = 5
KEYUP = 6
KEYDOWN = 19
KEY1 = 21
KEY2 = 20
KEY3 = 16
JPRESS = 13
BACKLIGHT = 24
# pin numbers are interpreted as BCM pin numbers.
GPIO.setmode(GPIO.BCM)
# Sets the pin as input and sets Pull-up mode for the pin.
GPIO.setup(KEYRIGHT,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(KEYLEFT,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(KEYUP,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(KEYDOWN,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(KEY1,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(KEY2,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(KEY3,GPIO.IN,GPIO.PUD_UP)
GPIO.setup(JPRESS,GPIO.IN,GPIO.PUD_UP)
#LED animations
def fastColorWipe(strip, update):
red = int(ledsettings.get_backlight_color("Red"))* (ledsettings.backlight_brightness_percent) / 100
green = int(ledsettings.get_backlight_color("Green")) * (ledsettings.backlight_brightness_percent) / 100
blue = int(ledsettings.get_backlight_color("Blue")) * float(ledsettings.backlight_brightness_percent) / 100
color = Color(int(green),int(red),int(blue))
for i in range(strip.numPixels()):
strip.setPixelColor(i, color)
if(update == True):
strip.show()
def theaterChase(strip, color, wait_ms=50):
"""Movie theater light style chaser animation."""
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
j = 0
menu.screensaver_is_running = True
while (menu.screensaver_is_running == True):
red = int(ledsettings.get_color("Red"))
green = int(ledsettings.get_color("Green"))
blue = int(ledsettings.get_color("Blue"))
for q in range(5):
for i in range(0, strip.numPixels(), 5):
strip.setPixelColor(i+q, Color(green, red, blue))
strip.show()
time.sleep(wait_ms/1000.0)
for i in range(0, strip.numPixels(), 5):
strip.setPixelColor(i+q, 0)
j += 1
if(j > 256):
j = 0
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def wheel(pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3)
def rainbow(strip, wait_ms=20):
"""Draw rainbow that fades across all pixels at once."""
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
j = 0
menu.screensaver_is_running = True
while (menu.screensaver_is_running == True):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((j) & 255))
j += 1
if(j >= 256):
j = 0
strip.show()
time.sleep(wait_ms/1000.0)
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def rainbowCycle(strip, wait_ms=20):
"""Draw rainbow that uniformly distributes itself across all pixels."""
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
j = 0
menu.screensaver_is_running = True
while (menu.screensaver_is_running == True):
for i in range(strip.numPixels()):
strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
j += 1
if(j >= 256):
j = 0
strip.show()
time.sleep(wait_ms/1000.0)
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def theaterChaseRainbow(strip, wait_ms=10):
"""Rainbow movie theater light style chaser animation."""
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
j = 0
menu.screensaver_is_running = True
while (menu.screensaver_is_running == True):
for q in range(5):
for i in range(0, strip.numPixels(), 5):
strip.setPixelColor(i+q, wheel((i+j) % 255))
strip.show()
time.sleep(wait_ms/1000.0)
for i in range(0, strip.numPixels(), 5):
strip.setPixelColor(i+q, 0)
j += 1
if(j > 256):
j = 0
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def breathing(strip, wait_ms=2):
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
menu.screensaver_is_running = True
multiplier = 24
direction = 2
while (menu.screensaver_is_running == True):
if(multiplier >= 98 or multiplier < 24):
direction *= -1
multiplier += direction
divide = multiplier / float(100)
red = int(round(float(ledsettings.get_color("Red")) * float(divide)))
green = int(round(float(ledsettings.get_color("Green")) * float(divide)))
blue = int(round(float(ledsettings.get_color("Blue")) * float(divide)))
for i in range(strip.numPixels()):
strip.setPixelColor(i, Color(green, red, blue))
strip.show()
if(wait_ms > 0):
time.sleep(wait_ms/1000.0)
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def sound_of_da_police(strip, wait_ms=5):
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
menu.screensaver_is_running = True
middle = strip.numPixels() / 2
r_start = 0
l_start = 196
while (menu.screensaver_is_running == True):
r_start += 14
l_start -= 14
for i in range(strip.numPixels()):
if((i > middle) and i > (r_start) and i < (r_start + 40)):
strip.setPixelColor(i, Color(0, 255, 0))
elif((i < middle) and i < (l_start) and i > (l_start - 40)):
strip.setPixelColor(i, Color(0, 0, 255))
else:
strip.setPixelColor(i, Color(0, 0, 0))
if(r_start > 150):
r_start = 0
l_start = 175
strip.show()
time.sleep(wait_ms/1000.0)
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def scanner(strip, wait_ms=1):
if (menu.screensaver_is_running == True):
menu.screensaver_is_running = False
time.sleep(1)
fastColorWipe(ledstrip.strip, True)
menu.t = threading.currentThread()
menu.screensaver_is_running = True
position = 0
direction = 3
scanner_length = 20
red_fixed = ledsettings.get_color("Red")
green_fixed = ledsettings.get_color("Green")
blue_fixed = ledsettings.get_color("Blue")
while (menu.screensaver_is_running == True):
position += direction
for i in range(strip.numPixels()):
if(i > (position - (scanner_length)) and i < (position + (scanner_length))):
distance_from_position = position - i
if(distance_from_position < 0):
distance_from_position *= -1
divide = ((scanner_length / 2) - distance_from_position) / float(scanner_length / 2)
red = int(float(red_fixed) * float(divide))
green = int(float(green_fixed) * float(divide))
blue = int(float(blue_fixed) * float(divide))
if(divide > 0):
strip.setPixelColor(i, Color(green, red, blue))
else:
strip.setPixelColor(i, Color(0, 0, 0))
if(position >= strip.numPixels() or position <= 1):
direction *= -1
strip.show()
time.sleep(wait_ms/1000.0)
menu.screensaver_is_running = False
fastColorWipe(ledstrip.strip, True)
def get_rainbow_colors(pos, color):
pos = int(pos)
if pos < 85:
if(color == "green"):
return pos * 3
elif(color == "red"):
return 255 - pos * 3
elif(color == "blue"):
return 0
elif pos < 170:
pos -= 85
if(color == "green"):
return 255 - pos * 3
elif(color == "red"):
return 0
elif(color == "blue"):
return pos * 3
else:
pos -= 170
if(color == "green"):
return 0
elif(color == "red"):
return pos * 3
elif(color == "blue"):
return 255 - pos * 3
class MenuLCD:
def __init__(self, xml_file_name):
self.LCD = LCD_1in44.LCD()
self.Lcd_ScanDir = LCD_1in44.SCAN_DIR_DFT
self.LCD.LCD_Init(self.Lcd_ScanDir)
self.image = Image.new("RGB", (self.LCD.width, self.LCD.height), "GREEN")
self.draw = ImageDraw.Draw(self.image)
self.LCD.LCD_ShowImage(self.image,0,0)
self.xml_file_name = xml_file_name
self.DOMTree = minidom.parse(xml_file_name)
self.currentlocation = "menu";
self.scroll_hold = 0
self.cut_count = 0
self.pointer_position = 0
self.background_color = usersettings.get_setting_value("background_color")
self.text_color = usersettings.get_setting_value("text_color")
self.update_songs()
self.update_ports()
self.speed_multiplier = 1
self.screensaver_settings = dict()
self.screensaver_settings['time'] = usersettings.get_setting_value("time")
self.screensaver_settings['date'] = usersettings.get_setting_value("date")
self.screensaver_settings['cpu_chart'] = usersettings.get_setting_value("cpu_chart")
self.screensaver_settings['cpu'] = usersettings.get_setting_value("cpu")
self.screensaver_settings['ram'] = usersettings.get_setting_value("ram")
self.screensaver_settings['temp'] = usersettings.get_setting_value("temp")
self.screensaver_settings['network_usage'] = usersettings.get_setting_value("network_usage")
self.screensaver_settings['sd_card_space'] = usersettings.get_setting_value("sd_card_space")
self.screensaver_delay = usersettings.get_setting_value("screensaver_delay")
self.screen_off_delay = usersettings.get_setting_value("screen_off_delay")
self.led_animation_delay = usersettings.get_setting_value("led_animation_delay")
self.led_animation = usersettings.get_setting_value("led_animation")
self.screen_status = 1
self.screensaver_is_running = False
def toggle_screensaver_settings(self, setting):
setting = setting.lower()
setting = setting.replace(" ", "_")
if(str(self.screensaver_settings[setting]) == "1"):
usersettings.change_setting_value(setting, "0")
self.screensaver_settings[setting] = "0"
else:
usersettings.change_setting_value(setting, "1")
self.screensaver_settings[setting] = "1"
def update_songs(self):
songs_list = os.listdir("Songs")
self.DOMTree = minidom.parse(self.xml_file_name)
for song in songs_list:
element = self.DOMTree.createElement("Choose_song")
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , song)
mc = self.DOMTree.getElementsByTagName("Play_MIDI")[0]
mc.appendChild(element)
def update_sequence_list(self):
try:
sequences_tree = minidom.parse("sequences.xml")
self.update_songs()
i = 0
while(True):
try:
i += 1
sequence_name = sequences_tree.getElementsByTagName("sequence_"+str(i))[0].getElementsByTagName("sequence_name")[0].firstChild.nodeValue
element = self.DOMTree.createElement("Sequences")
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , str(sequence_name))
mc = self.DOMTree.getElementsByTagName("LED_Strip_Settings")[0]
mc.appendChild(element)
except:
break
except:
self.render_message("Something went wrong", "Check your sequences file", 1500)
def update_ports(self):
ports = mido.get_input_names()
self.update_sequence_list()
for port in ports:
element = self.DOMTree.createElement("Input")
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , port)
mc = self.DOMTree.getElementsByTagName("Ports_Settings")[0]
mc.appendChild(element)
element = self.DOMTree.createElement("Playback")
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , port)
mc = self.DOMTree.getElementsByTagName("Ports_Settings")[2]
mc.appendChild(element)
def update_multicolor(self, colors_list):
i = 0
self.update_ports()
rgb_names = []
rgb_names = ["Red", "Green", "Blue"]
for color in colors_list:
i = i + 1
element = self.DOMTree.createElement("Multicolor")
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , "Color"+str(i))
mc = self.DOMTree.getElementsByTagName("LED_Color")[0]
mc.appendChild(element)
element = self.DOMTree.createElement("Color"+str(i))
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , "RGB Color"+str(i))
mc = self.DOMTree.getElementsByTagName("Multicolor")[0]
mc.appendChild(element)
#adding key range to menu
element = self.DOMTree.createElement("Color"+str(i))
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , "Key range"+str(i))
mc = self.DOMTree.getElementsByTagName("Multicolor")[0]
mc.appendChild(element)
element = self.DOMTree.createElement("Key_range"+str(i))
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , "Start")
mc = self.DOMTree.getElementsByTagName("Color"+str(i))[0]
mc.appendChild(element)
element = self.DOMTree.createElement("Key_range"+str(i))
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , "End")
mc = self.DOMTree.getElementsByTagName("Color"+str(i))[0]
mc.appendChild(element)
#adding delete
element = self.DOMTree.createElement("Color"+str(i))
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , "Delete")
mc = self.DOMTree.getElementsByTagName("Multicolor")[0]
mc.appendChild(element)
for rgb_name in rgb_names:
element = self.DOMTree.createElement("RGB_Color"+str(i))
element.appendChild(self.DOMTree.createTextNode(""))
element.setAttribute("text" , rgb_name)
mc = self.DOMTree.getElementsByTagName("Color"+str(i))[0]
mc.appendChild(element)
def show(self, position = "default", back_pointer_location = False):
if(position == "default" and self.currentlocation):
position = self.currentlocation
refresh = 1
elif(position == "default" and not self.currentlocation):
position = "menu"
refresh = 1
else:
position = position.replace(" ", "_")
self.currentlocation = position
refresh = 0
self.image = Image.new("RGB", (self.LCD.width, self.LCD.height), self.background_color)
self.draw = ImageDraw.Draw(self.image)
self.draw.text((2, 5), position.replace("_", " "), fill = self.text_color)
#getting list of items in current menu
staffs = self.DOMTree.getElementsByTagName(position)
text_margin_top = 15
i = 0
list_count = len(staffs)
list_count -= 1
if(self.pointer_position > 9):
self.menu_offset = self.pointer_position - 9
else:
self.menu_offset = -1;
#looping through menu list
for staff in staffs:
if(self.pointer_position > list_count):
self.pointer_position = list_count
elif(self.pointer_position < 0):
self.pointer_position = 0
#drawing little arrow to show there are more items above
if(self.pointer_position > 9 and i < self.menu_offset):
self.draw.line([(119,20),(125,20)], fill = self.text_color,width = 2)
self.draw.line([(119,20),(122,17)], fill = self.text_color,width = 2)
self.draw.line([(119,20),(122, 17)], fill = self.text_color,width = 2)
i += 1
continue
sid = staff.getAttribute("text")
if(not back_pointer_location):
if(i == self.pointer_position):
try:
self.parent_menu = staff.parentNode.tagName
except:
self.parent_menu = "end"
self.draw.rectangle([(0,text_margin_top),(128,text_margin_top + 11)],fill = "Crimson")
self.draw.text((3, text_margin_top), ">", fill = self.text_color)
self.current_choice = sid
else:
if(sid == back_pointer_location):
try:
self.parent_menu = staff.parentNode.tagName
except:
self.parent_menu = "data"
self.draw.rectangle([(0,text_margin_top),(128,text_margin_top + 11)],fill = "Crimson")
self.draw.text((3, text_margin_top), ">", fill = self.text_color)
self.current_choice = sid
self.pointer_position = i
#drawing little arrow to show there are more items below
if(i == 10 and self.pointer_position < list_count and list_count > 10):
self.draw.line([(119,120),(125,120)], fill = self.text_color,width = 2)
self.draw.line([(119,120),(122,123)], fill = self.text_color,width = 2)
self.draw.line([(122,123),(125,120)], fill = self.text_color,width = 2)
#scrolling text if too long
if(self.pointer_position == i and len(sid) > 18):
tobecontinued = ".."
if(refresh == 1):
try:
self.cut_count += 1
except:
self.cut_count = -6
else:
cut = 0
self.cut_count = -6
if(self.cut_count > (len(sid) - 16)):
#hold scrolling on end
if(self.scroll_hold < 8):
self.cut_count -= 1
self.scroll_hold += 1
tobecontinued = ""
else:
self.cut_count = -6
self.scroll_hold = 0
cut = self.cut_count
if(self.cut_count >= 0):
cut = self.cut_count
else:
cut = 0
else:
cut = 0
tobecontinued = ""
i += 1
#diplaying screensaver status
if(self.currentlocation == "Content"):
sid_temp = sid.lower()
sid_temp = sid_temp.replace(" ", "_")
if(str(menu.screensaver_settings[sid_temp]) == "1"):
sid_temp = " +"
else:
sid_temp = " -"
sid = sid+sid_temp
self.draw.text((10, text_margin_top), sid[cut:(18 + cut)]+tobecontinued, fill = self.text_color)
text_margin_top += 10
#displaying color example
if(self.currentlocation == "RGB"):
self.draw.text((10, 70), str(ledsettings.get_colors()), fill = self.text_color)
self.draw.rectangle([(0,80),(128,128)],fill = "rgb("+str(ledsettings.get_colors())+")")
if("RGB_Color" in self.currentlocation):
self.draw.text((10, 70), str(ledsettings.get_multicolors(self.currentlocation.replace('RGB_Color',''))), fill = self.text_color)
self.draw.rectangle([(0,80),(128,128)],fill = "rgb("+str(ledsettings.get_multicolors(self.currentlocation.replace('RGB_Color','')))+")")
if("Backlight_Color" in self.currentlocation):
self.draw.text((10, 70), str(ledsettings.get_backlight_colors()), fill = self.text_color)
self.draw.rectangle([(0,80),(128,128)],fill = "rgb("+str(ledsettings.get_backlight_colors())+")")
if("Custom_RGB" in self.currentlocation):
self.draw.text((10, 70), str(ledsettings.get_adjacent_colors()), fill = self.text_color)
self.draw.rectangle([(0,80),(128,128)],fill = "rgb("+str(ledsettings.get_adjacent_colors())+")")
if("Multicolor" in self.currentlocation):
try:
self.draw.rectangle([(115,50),(128,80)],fill = "rgb("+str(ledsettings.get_multicolors(self.current_choice.replace('Color','')))+")")
except:
pass
if("Color_for_slow_speed" in self.currentlocation):
red = ledsettings.speed_slowest["red"]
green = ledsettings.speed_slowest["green"]
blue = ledsettings.speed_slowest["blue"]
self.draw.text((10, 70), str(red)+", "+str(green)+", "+str(blue), fill = self.text_color)
self.draw.rectangle([(0,80),(128,128)],fill = "rgb("+str(red)+", "+str(green)+", "+str(blue)+")")
if("Color_for_fast_speed" in self.currentlocation):
red = ledsettings.speed_fastest["red"]
green = ledsettings.speed_fastest["green"]
blue = ledsettings.speed_fastest["blue"]
self.draw.text((10, 70), str(red)+", "+str(green)+", "+str(blue), fill = self.text_color)
self.draw.rectangle([(0,80),(128,128)],fill = "rgb("+str(red)+", "+str(green)+", "+str(blue)+")")
#displaying rainbow offset value
if(self.current_choice == "Offset"):
self.draw.text((10, 70), str(ledsettings.rainbow_offset), fill = self.text_color)
if(self.current_choice == "Scale"):
self.draw.text((10, 70), str(ledsettings.rainbow_scale)+"%", fill = self.text_color)
if(self.current_choice == "Timeshift"):
self.draw.text((10, 70), str(ledsettings.rainbow_timeshift), fill = self.text_color)
#displaying brightness value
if(self.currentlocation == "Brightness"):
self.draw.text((10, 35), str(ledstrip.brightness_percent)+"%", fill = self.text_color)
miliamps = int(ledstrip.LED_COUNT) * (60 / (100 / float(ledstrip.brightness_percent)))
amps = round(float(miliamps) / float(1000),2)
self.draw.text((10, 50), "Amps needed to "+"\n"+"power "+str(ledstrip.LED_COUNT)+" LEDS with "+"\n"+"white color: "+str(amps), fill = self.text_color)
if(self.currentlocation == "Backlight_Brightness"):
self.draw.text((10, 35), str(ledsettings.backlight_brightness_percent)+"%", fill = self.text_color)
#displaying led count
if(self.currentlocation == "Led_count"):
self.draw.text((10, 35), str(ledstrip.led_number), fill = self.text_color)
#displaying shift
if(self.currentlocation == "Shift"):
self.draw.text((10, 35), str(ledstrip.shift), fill = self.text_color)
if("Key_range" in self.currentlocation):
if(self.current_choice == "Start"):
try:
self.draw.text((10, 50), str(ledsettings.multicolor_range[int(self.currentlocation.replace('Key_range',''))-1][0]), fill = self.text_color)
except:
pass
else:
self.draw.text((10, 50), str(ledsettings.multicolor_range[int(self.currentlocation.replace('Key_range',''))-1][1]), fill = self.text_color)
#displaying screensaver settings
if(self.currentlocation == "Start_delay"):
self.draw.text((10, 70), str(self.screensaver_delay), fill = self.text_color)
if(self.currentlocation == "Turn_off_screen_delay"):
self.draw.text((10, 70), str(self.screen_off_delay), fill = self.text_color)
if(self.currentlocation == "Led_animation_delay"):
self.draw.text((10, 70), str(self.led_animation_delay), fill = self.text_color)
#displaying speed values
if(self.currentlocation == "Period"):
self.draw.text((10, 70), str(ledsettings.speed_period_in_seconds), fill = self.text_color)
if(self.currentlocation == "Max_notes_in_period"):
self.draw.text((10, 70), str(ledsettings.speed_max_notes), fill = self.text_color)
self.LCD.LCD_ShowImage(self.image,0,0)
def change_pointer(self, direction):
if(direction == 0):
self.pointer_position -= 1
elif(direction == 1):
self.pointer_position += 1
menu.cut_count = -6
menu.show()
def enter_menu(self):
position = self.current_choice.replace(" ", "_")
if(not self.DOMTree.getElementsByTagName(position)):
menu.change_settings(self.current_choice, self.currentlocation)
else:
self.currentlocation = self.current_choice
self.pointer_position = 0
menu.cut_count = -6
menu.show(self.current_choice)
def go_back(self):
if(self.parent_menu != "data"):
location_readable = self.currentlocation.replace("_", " ")
menu.cut_count = -6
menu.show(self.parent_menu, location_readable)
def render_message(self, title, message, delay = 500):
self.image = Image.new("RGB", (self.LCD.width, self.LCD.height), self.background_color)
self.draw = ImageDraw.Draw(self.image)
self.draw.text((3, 55), title, fill = self.text_color)
self.draw.text((3, 65), message, fill = self.text_color)
self.LCD.LCD_ShowImage(self.image,0,0)
LCD_Config.Driver_Delay_ms(delay)
def render_screensaver(self, hour, date, cpu, cpu_average, ram, temp, cpu_history = [], upload = 0, download = 0, card_space = 0):
self.image = Image.new("RGB", (self.LCD.width, self.LCD.height), self.background_color)
self.draw = ImageDraw.Draw(self.image)
total_height = 1
info_count = 0
for key, value in menu.screensaver_settings.items():
if(str(key) == "time" and str(value) == "1"):
total_height += 31
elif(str(key) == "date" and str(value) == "1"):
total_height += 13
elif(str(key) == "cpu_chart" and str(value) == "1"):
total_height += 35
else:
if(str(value) == "1"):
info_count += 1
height_left = 128 - total_height
if(info_count > 0):
info_height_font = height_left / info_count
top_offset = 2
if(menu.screensaver_settings["time"] == "1"):
fonthour = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 31)
self.draw.text((4, top_offset), hour, fill = self.text_color, font=fonthour)
top_offset += 31
if(menu.screensaver_settings["date"] == "1"):
font_date = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', 13)
self.draw.text((34, top_offset), date, fill = self.text_color, font=font_date)
top_offset += 13
if(menu.screensaver_settings["cpu_chart"] == "1"):
previous_height = 0
c = -5
for cpu_chart in cpu_history:
height = ((100 - cpu_chart) * 35) / float(100)
self.draw.line([(c,top_offset+previous_height),(c+5,top_offset+height)], fill = "Red",width = 1)
previous_height = height
c += 5
top_offset += 35
if(info_height_font > 12):
info_height_font = 12
font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', info_height_font)
if(menu.screensaver_settings["cpu"] == "1"):
self.draw.text((1, top_offset), "CPU: "+str(cpu)+"% ("+str(cpu_average)+"%)", fill = self.text_color, font=font)
top_offset += info_height_font
if(menu.screensaver_settings["ram"] == "1"):
self.draw.text((1, top_offset), "RAM usage: "+str(ram)+"%", fill = self.text_color, font=font)
top_offset += info_height_font
if(menu.screensaver_settings["temp"] == "1"):
self.draw.text((1, top_offset), "Temp: "+str(temp)+" C", fill = self.text_color, font=font)
top_offset += info_height_font
if(menu.screensaver_settings["network_usage"] == "1"):
if(info_height_font > 11):
info_height_font_network = 11
else:
info_height_font_network = info_height_font
font_network = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSansBold.ttf', info_height_font_network)
self.draw.text((1, top_offset), "D:"+str("{:.2f}".format(download))+"Mb/s U:"+str("{:.2f}".format(upload))+"Mb/s", fill = self.text_color, font=font_network)
top_offset += info_height_font_network
if(menu.screensaver_settings["sd_card_space"] == "1"):
self.draw.text((1, top_offset), "SD: "+str(round(card_space.used/(1024.0 ** 3), 1))+"/"+str(round(card_space.total/(1024.0 ** 3), 1))+"("+str(card_space.percent)+"%)", fill = self.text_color, font=font)
top_offset += info_height_font
self.LCD.LCD_ShowImage(self.image,0,0)
def change_settings(self, choice, location):
if(location == "Text_Color"):
self.text_color = choice
usersettings.change_setting_value("text_color", self.text_color)
if(location == "Background_Color"):
self.background_color = choice
usersettings.change_setting_value("background_color", self.background_color)
if(self.text_color == self.background_color):
self.text_color = "Red"
usersettings.change_setting_value("text_color", self.text_color)
if(location == "Choose_song"):
saving.t = threading.Thread(target=play_midi, args=(choice,))
saving.t.start()
if(location == "Play_MIDI"):
if(choice == "Save MIDI"):
now = datetime.datetime.now()
current_date = now.strftime("%Y-%m-%d %H:%M")
menu.render_message("Recording stopped", "Saved as "+current_date, 2000)
saving.save(current_date)
menu.update_songs()
if(choice =="Start recording"):
menu.render_message("Recording started", "", 2000)
saving.start_recording()
if(choice == "Cancel recording"):
menu.render_message("Recording canceled", "", 2000)
saving.cancel_recording()
if(choice == "Stop playing"):
saving.is_playing_midi.clear()
menu.render_message("Playing stopped", "", 2000)
fastColorWipe(ledstrip.strip, True)
if(location == "Solid"):
ledsettings.change_color_name(wc.name_to_rgb(choice))
ledsettings.color_mode = "Single"
usersettings.change_setting_value("color_mode", ledsettings.color_mode)
if(location == "Fading"):
ledsettings.mode = "Fading"
usersettings.change_setting_value("mode", ledsettings.mode)
if (choice == "Very fast"):
ledsettings.fadingspeed = 50
elif(choice == "Fast"):
ledsettings.fadingspeed = 40
elif(choice == "Medium"):
ledsettings.fadingspeed = 20
elif(choice == "Slow"):
ledsettings.fadingspeed = 10
elif(choice == "Very slow"):
ledsettings.fadingspeed = 2
usersettings.change_setting_value("fadingspeed", ledsettings.fadingspeed)
if(location == "Velocity"):
ledsettings.mode = "Velocity"
usersettings.change_setting_value("mode", ledsettings.mode)
if(choice == "Fast"):
ledsettings.fadingspeed = 10
elif(choice == "Medium"):
ledsettings.fadingspeed = 8
elif(choice == "Slow"):
ledsettings.fadingspeed = 6
elif(choice == "Very slow"):
ledsettings.fadingspeed = 3
usersettings.change_setting_value("fadingspeed", ledsettings.fadingspeed)
if(location == "Light_mode"):
ledsettings.mode = "Normal"
usersettings.change_setting_value("mode", ledsettings.mode)
fastColorWipe(ledstrip.strip, True)
if(location == "Input"):
midiports.change_port("inport", choice)
if(location == "Playback"):
midiports.change_port("playport", choice)
if(location == "Ports_Settings"):
if(choice == "Refresh ports" or choice == "Input" or choice == "Playback"):
menu.update_ports()
if(choice == "Reset Bluetooth service"):
menu.render_message("Reseting BL service", "", 1000)
os.system("sudo systemctl restart btmidi.service")
if(location == "LED_animations"):
if(choice == "Theater Chase"):
self.t = threading.Thread(target=theaterChase, args=(ledstrip.strip, Color(127, 127, 127)))
self.t.start()
if(choice == "Theater Chase Rainbow"):
self.t = threading.Thread(target=theaterChaseRainbow, args=(ledstrip.strip, 5))
self.t.start()
if(choice == "Sound of da police"):
self.t = threading.Thread(target=sound_of_da_police, args=(ledstrip.strip, 1))
self.t.start()
if(choice == "Scanner"):
self.t = threading.Thread(target=scanner, args=(ledstrip.strip, 1))
self.t.start()
if(choice == "Clear"):
fastColorWipe(ledstrip.strip, True)
if(location == "Breathing"):
if(choice == "Fast"):
self.t = threading.Thread(target=breathing, args=(ledstrip.strip,5))
self.t.start()
if(choice == "Medium"):
self.t = threading.Thread(target=breathing, args=(ledstrip.strip,10))
self.t.start()
if(choice == "Slow"):
self.t = threading.Thread(target=breathing, args=(ledstrip.strip,25))
self.t.start()
if(location == "Rainbow"):
if(choice == "Fast"):
self.t = threading.Thread(target=rainbow, args=(ledstrip.strip,2))
self.t.start()
if(choice == "Medium"):
self.t = threading.Thread(target=rainbow, args=(ledstrip.strip,20))
self.t.start()
if(choice == "Slow"):