-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhud.py
More file actions
2655 lines (2516 loc) · 109 KB
/
hud.py
File metadata and controls
2655 lines (2516 loc) · 109 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
#!/usr/bin/env python3
import time, requests, json, evdev, spotipy, colorsys, datetime, os, subprocess, toml, random, sys, copy, math, queue, threading, signal, hashlib, functools, concurrent.futures, numpy as np
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance, ImageStat, ImageColor
from threading import Thread, Event, RLock
from spotipy.oauth2 import SpotifyOAuth
from functools import lru_cache
sys.stdout.reconfigure(line_buffering=True)
# ============== CONSTANTS ==============
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 320
UPDATE_INTERVAL_WEATHER = 3600
GEO_UPDATE_INTERVAL = 3600
SCOPE = "user-read-currently-playing user-modify-playback-state user-read-playback-state playlist-modify-private playlist-modify-public playlist-read-private playlist-read-collaborative user-read-private user-library-read user-library-modify"
USE_GPSD = True
USE_GOOGLE_GEO = True
SCREEN_AREA = SCREEN_WIDTH * SCREEN_HEIGHT
BG_DIR = "./bg"
CLOCK_TYPE = "analog"
CLOCK_BACKGROUND = "color"
CLOCK_COLOR = "black"
INTERNET_CHECK_INTERVAL = 120
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
FONT_PATH = os.path.join(SCRIPT_DIR, "static", "font", "mx_univga.ttf")
FONT_PATH_BOLD = os.path.join(SCRIPT_DIR, "static", "font", "mx_univga.ttf")
LARGE_FONT = ImageFont.truetype(FONT_PATH_BOLD, 32)
MEDIUM_FONT = ImageFont.truetype(FONT_PATH, 20)
SMALL_FONT = ImageFont.truetype(FONT_PATH, 10)
SPOT_LARGE_FONT = ImageFont.truetype(FONT_PATH_BOLD, 20)
SPOT_MEDIUM_FONT = ImageFont.truetype(FONT_PATH, 12)
SPOT_SMALL_FONT = ImageFont.truetype(FONT_PATH, 8)
WAVESHARE_FONT_SMALL = ImageFont.truetype(FONT_PATH_BOLD, 16)
WAVESHARE_FONT_MEDIUM = ImageFont.truetype(FONT_PATH_BOLD, 18)
WAVESHARE_FONT_LARGE = ImageFont.truetype(FONT_PATH_BOLD, 16)
WAVESHARE_FONT_TIME = ImageFont.truetype(FONT_PATH_BOLD, 32)
WAVESHARE_FONT_DATE = ImageFont.truetype(FONT_PATH_BOLD, 18)
WAVESHARE_FONT_WEATHER = ImageFont.truetype(FONT_PATH_BOLD, 16)
WAVESHARE_FONT_WEATHER_SMALL = ImageFont.truetype(FONT_PATH_BOLD, 16)
process_executor = None
frame_hash_cache = {}
frame_hash_cache_size = 50
DEFAULT_CONFIG = {
"display": {
"type": "dummy",
"framebuffer": "/dev/fb1",
"rotation": 0,
"st7789": {
"spi_port": 0,
"spi_cs": 1,
"dc_pin": 9,
"backlight_pin": 13,
"rotation": 0,
"spi_speed": 60000000
}
},
"api_keys": {
"openweather": "",
"google_geo": "",
"client_id": "",
"client_secret": "",
"lastfm": "",
"redirect_uri": "http://127.0.0.1:5000"
},
"settings": {
"framebuffer": "/dev/fb1",
"start_screen": "weather",
"fallback_city": "",
"use_gpsd": True,
"use_google_geo": True,
"time_display": True,
"sleep_timeout": 300,
"progressbar_display": True,
"enable_current_track_display": True
},
"wifi": {
"ap_ssid": "Neonwifi-Manager",
"ap_ip": "192.168.42.1",
},
"auto_start": {
"auto_start_hud": True,
"auto_start_neonwifi": True,
"check_internet": True
},
"clock": {
"type": "analog",
"background": "color",
"color": "black"
},
"buttons": {
"button_a": 5,
"button_b": 6,
"button_x": 16,
"button_y": 24
},
"ui": {
"theme": "dark"
}
}
# ============== GLOBAL VARIABLES ==============
weather_cache = {}
album_bg_cache = {}
exit_event = Event()
art_lock = RLock()
artist_image_lock = RLock()
scroll_lock = RLock()
st7789_display = None
waveshare_epd = None
waveshare_base_image = None
partial_refresh_count = 0
epd2in13_V3 = None
epdconfig = None
bg_generation_queue = queue.Queue(maxsize=5)
spotify_bg_cache = None
spotify_bg_cache_lock = threading.Lock()
current_album_art_hash = None
current_clock_artwork = None
clock_bg_image = None
clock_bg_lock = threading.Lock()
button_last_press = {5: 0, 6: 0, 16: 0, 24: 0}
_gamma_r = np.array([int(((i / 255.0) ** (1 / 1.5)) * 31 + 0.5) for i in range(256)], dtype=np.uint8)
_gamma_g = np.array([int(((i / 255.0) ** (1 / 1.5)) * 63 + 0.5) for i in range(256)], dtype=np.uint8)
_gamma_b = np.array([int(((i / 255.0) ** (1 / 1.5)) * 31 + 0.5) for i in range(256)], dtype=np.uint8)
weather_info = None
spotify_track = None
sp = None
album_art_image = None
artist_image = None
scroll_state = {"title": {"offset": 0, "max_offset": 0, "active": False}, "artists": {"offset": 0, "max_offset": 0, "active": False}, "album": {"offset": 0, "max_offset": 0, "active": False}}
bg_map = {"Clear": "bg_clear.png", "Clouds": "bg_clouds.png", "Rain": "bg_rain.png", "Drizzle": "bg_drizzle.png", "Thunderstorm": "bg_storm.png", "Snow": "bg_snow.png", "Mist": "bg_mist.png", "Fog": "bg_fog.png", "Haze": "bg_haze.png", "Smoke": "bg_smoke.png", "Dust": "bg_dust.png", "Sand": "bg_sand.png", "Ash": "bg_ash.png", "Squall": "bg_squall.png", "Tornado": "bg_tornado.png"}
art_pos = [float(SCREEN_WIDTH - 155), float(SCREEN_HEIGHT - 155)]
artist_pos = [5, float(SCREEN_HEIGHT - 105)]
artist_velocity = [0.7, 0.7]
art_velocity = [1, 1]
artist_on_top = False
spotify_layout_cache = None
scrolling_text_cache = {}
last_display_time = 0
waveshare_lock = RLock()
file_write_lock = threading.Lock()
last_activity_time = time.time()
st7789_lock = threading.Lock()
display_sleeping = False
last_saved_album_art_hash = None
internet_available = True
last_internet_check = 0
last_frame_hash = None
# ============== ANIMATION FUNCTIONS ==============
def animate_images():
global START_SCREEN
last_animation_time = time.time()
while not exit_event.is_set():
if display_sleeping:
time.sleep(0.5)
continue
current_time = time.time()
frame_time = current_time - last_animation_time
last_animation_time = current_time
needs_update = False
album_moved = update_album_art_position(frame_time)
artist_moved, toggled = update_artist_position(frame_time)
needs_update = album_moved or artist_moved
if toggled:
needs_update = True
if needs_update and START_SCREEN == "spotify":
update_display()
time.sleep(ANIMATION_FRAME_TIME)
def animate_text_scroll():
while not exit_event.is_set():
if display_sleeping:
time.sleep(0.5)
continue
with scroll_lock:
for key in scroll_state:
state = scroll_state[key]
if state["active"] and state["max_offset"] > 0:
state["offset"] += 2
if state["offset"] >= state["max_offset"]:
state["offset"] = 0
time.sleep(TEXT_SCROLL_FRAME_TIME)
# ============== BACKGROUND GENERATION FUNCTIONS ==============
def background_generation_worker():
global spotify_bg_cache, current_album_art_hash, clock_bg_image
while not exit_event.is_set():
try:
album_img, size, bg_type = bg_generation_queue.get(timeout=5)
if bg_type == "spotify":
generated_bg = get_cached_background(size, album_img)
with spotify_bg_cache_lock:
spotify_bg_cache = generated_bg.copy() if generated_bg else None
current_album_art_hash = id(album_img) if album_img else None
elif bg_type == "clock":
clock_bg_result = get_cached_background(size, album_img)
with clock_bg_lock:
clock_bg_image = clock_bg_result.copy() if clock_bg_result else None
bg_generation_queue.task_done()
except queue.Empty:
continue
except Exception as e:
print(f"Background generation worker error: {e}")
bg_generation_queue.task_done()
def create_fade_mask(art_size, fade_width):
x_coords = np.arange(art_size)
left_fade_mask = np.where(x_coords < fade_width,
255 * ((x_coords / fade_width) ** 0.7),
255).astype(np.uint8)
right_fade_mask = np.where(x_coords > art_size - fade_width,
255 * (((art_size - x_coords) / fade_width) ** 0.7),
255).astype(np.uint8)
combined_alpha = np.minimum(left_fade_mask, right_fade_mask)
mask_array = np.tile(combined_alpha, (art_size, 1))
return Image.fromarray(mask_array, mode='L')
def get_background_path(weather_info):
if not weather_info:
candidate = "bg_default.png"
else:
main = weather_info.get('main', '').capitalize()
candidate = bg_map.get(main, "bg_default.png")
full_path = os.path.join(BG_DIR, candidate) if candidate else None
if full_path and os.path.exists(full_path):
return candidate
fallback_path = os.path.join(BG_DIR, "bg_default.png")
if os.path.exists(fallback_path):
return "bg_default.png"
return None
def get_cached_background(size, album_art_img):
global album_bg_cache
if album_art_img is None:
return Image.new("RGB", size, "black")
img_hash = id(album_art_img)
if img_hash in album_bg_cache:
bg = album_bg_cache[img_hash]
if bg.size == size:
return bg.copy()
bg = make_background_from_art(size, album_art_img)
if len(album_bg_cache) >= 3:
oldest_key = next(iter(album_bg_cache))
del album_bg_cache[oldest_key]
album_bg_cache[img_hash] = bg.copy()
return bg
def make_background_from_art(size, album_art_img):
return prepare_album_background(size, album_art_img)
def prepare_album_background(size, album_art_img):
width, height = size
if album_art_img is None:
return create_gradient_background(size)
if album_art_img.mode != "RGB":
album_art_img = album_art_img.convert("RGB")
small_for_color = album_art_img.resize((50, 50), Image.BILINEAR)
pixels = list(small_for_color.getdata())
r, g, b = calculate_avg_colors(pixels)
avg_color = (int(r * 0.7), int(g * 0.7), int(b * 0.7))
bg = Image.new("RGB", size, avg_color)
art_size = height
scaled_art = album_art_img.resize((art_size, art_size), Image.BILINEAR)
blurred_art = scaled_art.filter(ImageFilter.GaussianBlur(2))
enhancer = ImageEnhance.Brightness(blurred_art)
blurred_art = enhancer.enhance(0.6)
fade_width = min(80, art_size // 4)
mask = create_fade_mask(art_size, fade_width)
art_x = (width - art_size) // 2
bg.paste(blurred_art, (art_x, 0), mask)
return bg
def request_background_generation(album_img):
global current_clock_artwork
if album_img is not None:
with clock_bg_lock:
if current_clock_artwork is None or id(album_img) != id(current_clock_artwork):
current_clock_artwork = album_img.copy()
current_hash = id(album_img)
if hasattr(request_background_generation, 'last_queued_hash'):
if request_background_generation.last_queued_hash == current_hash:
return
request_background_generation.last_queued_hash = current_hash
try:
bg_generation_queue.put((album_img, (SCREEN_WIDTH, SCREEN_HEIGHT), "spotify"), block=False)
except queue.Full:
pass
if CLOCK_BACKGROUND == "album":
try:
bg_generation_queue.put((album_img, (SCREEN_WIDTH, SCREEN_HEIGHT), "clock"), block=False)
except queue.Full:
pass
else:
with clock_bg_lock:
current_clock_artwork = None
# ============== BUTTON AND TOUCH FUNCTIONS ==============
def find_touchscreen():
for path in evdev.list_devices():
dev = evdev.InputDevice(path)
if "ADS7846" in dev.name or "Touchscreen" in dev.name or "touch" in dev.name.lower():
return dev
print("Touchscreen not found - touch controls disabled")
return None
def handle_buttons():
global START_SCREEN, display_sleeping
display_type = config.get("display", {}).get("type", "framebuffer")
if display_type == "waveshare_epd":
print("Button controls disabled for Waveshare e-paper display")
while not exit_event.is_set():
time.sleep(1)
return
if not HAS_GPIO:
print("GPIO not available - button controls disabled")
while not exit_event.is_set():
time.sleep(1)
return
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
buttons = [BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y]
for button in buttons:
try:
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
except Exception as e:
if "busy" in str(e).lower():
print(f"GPIO {button} already in use, skipping button setup.")
return
else:
raise
print("Button handler started:")
print("A: Switch to Clock, B: Switch to Weather, X: Switch to Spotify, Y: Toggle Display On/Off")
while not exit_event.is_set():
for button in buttons:
try:
if GPIO.input(button) == GPIO.LOW:
current_time = time.time()
if current_time - button_last_press[button] > DEBOUNCE_TIME:
button_last_press[button] = current_time
update_activity()
if button == BUTTON_A:
if START_SCREEN != "time":
START_SCREEN = "time"
update_display()
elif button == BUTTON_B:
if START_SCREEN != "weather":
START_SCREEN = "weather"
update_display()
elif button == BUTTON_X:
if START_SCREEN != "spotify":
START_SCREEN = "spotify"
update_display()
elif button == BUTTON_Y:
if display_sleeping:
wake_up_display()
else:
go_to_sleep()
except Exception:
pass
time.sleep(0.1)
GPIO.cleanup()
def handle_touch():
global START_SCREEN
display_type = config.get("display", {}).get("type", "framebuffer")
if display_type == "waveshare_epd":
print("Touch controls disabled for Waveshare e-paper display")
while not exit_event.is_set():
time.sleep(1)
return
device = find_touchscreen()
if device is None:
while not exit_event.is_set():
time.sleep(1)
return
screen_order = ["weather", "spotify", "time"]
for event in device.read_loop():
if exit_event.is_set():
break
if event.type == evdev.ecodes.EV_KEY and event.code == evdev.ecodes.BTN_TOUCH and event.value == 1:
current_index = screen_order.index(START_SCREEN)
START_SCREEN = screen_order[(current_index + 1) % len(screen_order)]
update_activity()
update_display()
# ============== CACHE FUNCTIONS ==============
text_bbox_cache_local = {}
@lru_cache(maxsize=50)
def get_cached_bg(bg_path, size):
return Image.open(bg_path).resize(size, Image.BILINEAR)
@lru_cache(maxsize=100)
def get_cached_text_bbox(text, font_path, font_size):
font = ImageFont.truetype(font_path, font_size)
return font.getbbox(text)
def get_cached_text_bbox_font(text, font):
key = (text, getattr(font, "path", None), getattr(font, "size", None))
if key not in text_bbox_cache_local:
text_bbox_cache_local[key] = font.getbbox(text)
return text_bbox_cache_local[key]
def cache_weather(lat, lon, data):
weather_cache[f"{lat:.2f}_{lon:.2f}"] = (data, time.time())
def cleanup_caches():
get_cached_bg.cache_clear()
get_cached_text_bbox.cache_clear()
if len(text_bbox_cache_local) > 50:
text_bbox_cache_local.clear()
if len(album_bg_cache) > 3:
keys = list(album_bg_cache.keys())[-3:]
keep = {k: album_bg_cache[k] for k in keys}
album_bg_cache.clear()
album_bg_cache.update(keep)
if len(scrolling_text_cache) > 3:
scrolling_text_cache.clear()
def get_cached_weather(lat, lon):
cache_key = f"{lat:.2f}_{lon:.2f}"
if cache_key in weather_cache:
cached_data, timestamp = weather_cache[cache_key]
if time.time() - timestamp < 300:
return cached_data
return None
# ============== CLOCK FUNCTIONS ==============
def draw_analog_clock(img, palette):
face_color, notch_color, hour_color, minute_color, second_color = palette
draw = ImageDraw.Draw(img)
now = datetime.datetime.now()
center_x = SCREEN_WIDTH // 2
center_y = SCREEN_HEIGHT // 2
radius = min(SCREEN_WIDTH, SCREEN_HEIGHT) // 2 - 20
draw.ellipse((center_x - radius, center_y - radius, center_x + radius, center_y + radius),
outline=face_color, width=4)
for i in range(12):
angle = math.radians(i * 30)
x_outer = center_x + radius * math.sin(angle)
y_outer = center_y - radius * math.cos(angle)
x_inner = center_x + (radius - 15) * math.sin(angle)
y_inner = center_y - (radius - 15) * math.cos(angle)
draw.line((x_inner, y_inner, x_outer, y_outer), fill=notch_color, width=2)
hour = now.hour % 12 + now.minute / 60.0
minute = now.minute + now.second / 60.0
second = now.second
hour_angle = math.radians((hour / 12.0) * 360)
minute_angle = math.radians((minute / 60.0) * 360)
second_angle = math.radians((second / 60.0) * 360)
draw.line((center_x, center_y,
center_x + radius * 0.5 * math.sin(hour_angle),
center_y - radius * 0.5 * math.cos(hour_angle)),
fill=hour_color, width=10)
draw.line((center_x, center_y,
center_x + radius * 0.7 * math.sin(minute_angle),
center_y - radius * 0.7 * math.cos(minute_angle)),
fill=minute_color, width=6)
draw.line((center_x, center_y,
center_x + radius * 0.85 * math.sin(second_angle),
center_y - radius * 0.85 * math.cos(second_angle)),
fill=second_color, width=4)
draw.ellipse((center_x - 5, center_y - 5, center_x + 5, center_y + 5), fill="white")
def draw_clock_image():
img, avg_color = get_clock_background()
palette = generate_clock_palette(avg_color)
if CLOCK_TYPE == "analog":
draw_analog_clock(img, palette)
else:
draw_digital_clock(img, palette)
return img
def draw_digital_clock(img, palette):
face_color, notch_color, hour_color, minute_color, second_color = palette
draw = ImageDraw.Draw(img)
now = datetime.datetime.now()
time_str = now.strftime("%H:%M:%S")
date_str = now.strftime("%A, %B %d, %Y")
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
time_bbox = get_cached_text_bbox_font(time_str, LARGE_FONT)
time_width = time_bbox[2] - time_bbox[0]
time_height = time_bbox[3] - time_bbox[1]
time_x = (SCREEN_WIDTH - time_width) // 2
time_y = (SCREEN_HEIGHT - time_height) // 2 - 30
date_bbox = get_cached_text_bbox_font(date_str, MEDIUM_FONT)
date_width = date_bbox[2] - date_bbox[0]
date_x = (SCREEN_WIDTH - date_width) // 2
date_y = time_y + time_height + 20
img = Image.alpha_composite(img.convert("RGBA"), overlay).convert("RGB")
draw = ImageDraw.Draw(img)
draw_text_aliased(draw, img, (time_x, time_y), time_str, LARGE_FONT, face_color)
draw_text_aliased(draw, img, (date_x, date_y), date_str, MEDIUM_FONT, notch_color)
def generate_clock_palette(avg_color):
r, g, b = [x / 255.0 for x in avg_color]
h, s, v = colorsys.rgb_to_hsv(r, g, b)
base_hue = (h + 0.5) % 1.0
contrast_saturation = 0.8 + (0.4 * (1.0 - s))
contrast_brightness = 0.85 if v < 0.5 else 0.25
palette = []
for i in range(5):
hh = (base_hue + i * 0.18) % 1.0
rr, gg, bb = colorsys.hsv_to_rgb(hh, contrast_saturation, contrast_brightness)
rr, gg, bb = int(rr * 255), int(gg * 255), int(bb * 255)
rr = min(max(rr + (128 - avg_color[0]) // 2, 0), 255)
gg = min(max(gg + (128 - avg_color[1]) // 2, 0), 255)
bb = min(max(bb + (128 - avg_color[2]) // 2, 0), 255)
palette.append((rr, gg, bb))
return palette
def get_clock_background():
global weather_info, clock_bg_image
img = Image.new("RGB", (SCREEN_WIDTH, SCREEN_HEIGHT), "black")
avg_color = (128, 128, 128)
bg_applied = False
if CLOCK_BACKGROUND == "album":
with clock_bg_lock:
bg_to_use = clock_bg_image
if bg_to_use is not None:
img.paste(bg_to_use, (0, 0))
stat = ImageStat.Stat(bg_to_use)
avg_color = tuple(int(v) for v in stat.mean[:3])
bg_applied = True
else:
try:
if CLOCK_COLOR:
bg_color = ImageColor.getrgb(CLOCK_COLOR)
else:
bg_color = (0, 0, 0)
img.paste(Image.new("RGB", (SCREEN_WIDTH, SCREEN_HEIGHT), bg_color))
avg_color = bg_color
bg_applied = True
except Exception:
img.paste(Image.new("RGB", (SCREEN_WIDTH, SCREEN_HEIGHT), "black"))
avg_color = (0, 0, 0)
bg_applied = True
elif CLOCK_BACKGROUND == "weather":
bg_filename = get_background_path(weather_info)
if bg_filename:
bg_path = os.path.join(BG_DIR, bg_filename)
if os.path.exists(bg_path):
bg_img = get_cached_bg(bg_path, (SCREEN_WIDTH, SCREEN_HEIGHT))
img.paste(bg_img, (0, 0))
stat = ImageStat.Stat(bg_img)
avg_color = tuple(int(v) for v in stat.mean[:3])
bg_applied = True
if not bg_applied:
try:
if CLOCK_COLOR:
bg_color = ImageColor.getrgb(CLOCK_COLOR)
else:
hue_shift = (datetime.datetime.now().second / 60.0) % 1.0
rr, gg, bb = colorsys.hsv_to_rgb(hue_shift, 0.5, 0.2)
bg_color = (int(rr * 255), int(gg * 255), int(bb * 255))
img.paste(Image.new("RGB", (SCREEN_WIDTH, SCREEN_HEIGHT), bg_color))
avg_color = bg_color
except Exception:
img.paste(Image.new("RGB", (SCREEN_WIDTH, SCREEN_HEIGHT), "black"))
avg_color = (0, 0, 0)
return img, avg_color
# ============== COLOR FUNCTIONS ==============
def calculate_avg_colors(pixels):
avg_r = sum(p[0] for p in pixels) // len(pixels)
avg_g = sum(p[1] for p in pixels) // len(pixels)
avg_b = sum(p[2] for p in pixels) // len(pixels)
return avg_r, avg_g, avg_b
def generate_color_palette(avg_h, avg_s, avg_v, n=2):
opposite_h = (avg_h + 0.5) % 1.0
colors = []
data_saturation = min(0.9, avg_s + 0.3)
label_saturation = max(0.6, data_saturation - 0.2)
base_brightness = 0.9 if avg_v < 0.3 else (0.8 if avg_v > 0.7 else 0.85)
r1, g1, b1 = colorsys.hsv_to_rgb(opposite_h, data_saturation, base_brightness)
colors.append((int(r1*255), int(g1*255), int(b1*255)))
if n > 1:
secondary_h = (opposite_h + 0.12) % 1.0
label_brightness = base_brightness - 0.05 if base_brightness > 0.7 else base_brightness
r2, g2, b2 = colorsys.hsv_to_rgb(secondary_h, label_saturation, label_brightness)
colors.append((int(r2*255), int(g2*255), int(b2*255)))
return colors[:n]
def get_contrasting_colors(img, n=2):
if img.mode != "RGB": img = img.convert("RGB")
small_img = img.resize((50, 50), Image.BILINEAR)
pixels = list(small_img.getdata())
avg_r, avg_g, avg_b = calculate_avg_colors(pixels)
avg_h, avg_s, avg_v = colorsys.rgb_to_hsv(avg_r/255, avg_g/255, avg_b/255)
return generate_color_palette(avg_h, avg_s, avg_v, n)
# ============== CONFIGURATION FUNCTIONS ==============
def init_process_executor():
global process_executor
process_executor = concurrent.futures.ProcessPoolExecutor(max_workers=2)
def load_config(path="config.toml"):
if not os.path.exists(path):
with open(path, 'w') as f:
toml.dump(DEFAULT_CONFIG, f)
return load_config_defaults()
try:
with open(path, 'r') as f:
loaded_config = toml.load(f)
merged_config = merge_configs(DEFAULT_CONFIG, loaded_config)
with open(path, 'w') as f:
toml.dump(merged_config, f)
return merged_config
except Exception as e:
print(f"Error loading config: {e}, using defaults")
with open(path, 'w') as f:
toml.dump(DEFAULT_CONFIG, f)
return load_config_defaults()
def load_config_defaults():
return DEFAULT_CONFIG.copy()
def merge_configs(default_config, loaded_config):
merged_config = copy.deepcopy(default_config)
for category in loaded_config:
if category in merged_config:
if isinstance(merged_config[category], dict) and isinstance(loaded_config[category], dict):
for key in loaded_config[category]:
merged_config[category][key] = loaded_config[category][key]
else:
merged_config[category] = loaded_config[category]
else:
merged_config[category] = loaded_config[category]
return merged_config
# ============== DISPLAY FUNCTIONS ==============
def clear_waveshare_display():
global waveshare_epd
if not HAS_WAVESHARE_EPD or waveshare_epd is None:
return
try:
waveshare_epd.init()
white_img = Image.new('1', (250, 122), 255)
waveshare_epd.display(waveshare_epd.getbuffer(white_img))
waveshare_epd.sleep()
except Exception as e:
print(f"Failed to clear waveshare display: {e}")
try:
waveshare_epd.init()
waveshare_epd.Clear(0xFF)
waveshare_epd.sleep()
except Exception as e2:
print(f"Failed to reset waveshare display: {e2}")
def clear_framebuffer():
global HAS_ST7789
display_type = config.get("display", {}).get("type", "framebuffer")
if display_type == "dummy":
return
elif display_type == "waveshare_epd" and HAS_WAVESHARE_EPD:
clear_waveshare_display()
return
elif display_type == "st7789" and HAS_ST7789 and st7789_display:
black_img = Image.new("RGB", (320, 240), "black")
st7789_display.display(black_img)
else:
try:
black_image = Image.new("RGB", (SCREEN_WIDTH, SCREEN_HEIGHT), "black")
display_image_on_original_fb(black_image)
try:
with open(FRAMEBUFFER, "wb") as f:
black_pixel = b'\x00\x00'
f.write(black_pixel * SCREEN_WIDTH * SCREEN_HEIGHT)
f.flush()
os.fsync(f.fileno())
except Exception as e:
print(f"Direct framebuffer write failed: {e}")
except Exception as e:
print(f"Error clearing framebuffer: {e}")
if HAS_ST7789:
try:
black_img = Image.new("RGB", (320, 240), "black")
display_image_on_st7789(black_img)
except:
pass
def compute_frame_hash(image):
if image.mode != "RGB":
image = image.convert("RGB")
small = image.resize((16, 16), Image.BILINEAR)
data = np.array(small).tobytes()
return hashlib.md5(data).hexdigest()
def convert_to_1bit_dithered(album_art_img, size=(40, 40)):
if album_art_img is None:
return None
small_img = album_art_img.resize(size, Image.BILINEAR)
gray_img = small_img.convert('L')
bw_img = gray_img.convert('1')
return bw_img
def convert_to_rgb565(image):
arr = np.array(image, dtype=np.uint8)
r = _gamma_r[arr[:, :, 0]].astype(np.uint16)
g = _gamma_g[arr[:, :, 1]].astype(np.uint16)
b = _gamma_b[arr[:, :, 2]].astype(np.uint16)
rgb565 = (r << 11) | (g << 5) | b
output = np.empty((SCREEN_HEIGHT, SCREEN_WIDTH, 2), dtype=np.uint8)
output[:, :, 0] = rgb565 & 0xFF
output[:, :, 1] = (rgb565 >> 8) & 0xFF
return output
def display_image_on_dummy():
pass
def display_image_on_waveshare(image):
global waveshare_epd, waveshare_base_image, partial_refresh_count
with waveshare_lock:
if waveshare_epd is None:
if not init_waveshare_display():
return
try:
display_width = 250
display_height = 122
if image.size != (display_width, display_height):
image = image.resize((display_width, display_height), Image.BILINEAR)
if image.mode != '1':
image = image.convert('1')
content_changed = getattr(image, 'content_changed', True)
if content_changed:
waveshare_epd.init()
waveshare_epd.Clear(0xFF)
waveshare_epd.display(waveshare_epd.getbuffer(image))
waveshare_base_image = image.copy()
partial_refresh_count = 0
else:
waveshare_epd.displayPartial(waveshare_epd.getbuffer(image))
partial_refresh_count += 1
except Exception as e:
print(f"Waveshare display error: {e}")
try:
waveshare_epd.init()
waveshare_epd.display(waveshare_epd.getbuffer(image))
waveshare_base_image = image.copy()
partial_refresh_count = 0
except Exception as e2:
print(f"Failed to reset waveshare display: {e2}")
def display_image_on_framebuffer(image):
global last_display_time
now = time.time()
if now - last_display_time < MIN_DISPLAY_INTERVAL:
return
last_display_time = now
frame_hash = compute_frame_hash(image)
if not should_display_frame(frame_hash):
return
display_type = config.get("display", {}).get("type", "framebuffer")
if display_type == "dummy":
display_image_on_dummy()
elif display_type == "st7789" and HAS_ST7789:
display_image_on_st7789(image)
elif display_type == "waveshare_epd" and HAS_WAVESHARE_EPD:
display_image_on_waveshare(image)
else:
display_image_on_original_fb(image)
def display_image_on_original_fb(image):
try:
rotated_image = prepare_framebuffer_image(image)
output = convert_to_rgb565(rotated_image)
with open(FRAMEBUFFER, "wb") as fb:
fb.write(output.tobytes())
except PermissionError:
print(f"Permission denied for {FRAMEBUFFER} - falling back to ST7789")
if HAS_ST7789:
display_image_on_st7789(image)
else:
print("No display available")
except Exception as e:
print(f"Framebuffer error: {e}")
def display_image_on_st7789(image):
global st7789_display
try:
if st7789_display is None:
st7789_display = init_st7789_display()
if st7789_display is None:
return
scaled_image = image.resize((320, 240), Image.BILINEAR)
if scaled_image.mode != "RGB":
scaled_image = scaled_image.convert("RGB")
with st7789_lock:
st7789_display.display(scaled_image)
except Exception as e:
print(f"ST7789 display error: {e}")
try:
st7789_display = init_st7789_display()
except:
st7789_display = None
def draw_waveshare(weather_info, spotify_track):
global waveshare_base_image, partial_refresh_count
display_width = 250
display_height = 122
img = Image.new('1', (display_width, display_height), 255)
draw = ImageDraw.Draw(img)
draw.rectangle([0, 0, display_width-1, display_height-1], outline=0, width=2)
font_small = WAVESHARE_FONT_SMALL
font_medium = WAVESHARE_FONT_MEDIUM
font_large = WAVESHARE_FONT_LARGE
content_changed = False
current_track_id = ""
if spotify_track:
current_track_id = f"{spotify_track.get('title', '')}_{spotify_track.get('artists', '')}"
current_weather_id = ""
if weather_info:
current_weather_id = f"{weather_info.get('city', '')}_{weather_info.get('temp', '')}_{weather_info.get('description', '')}"
if not hasattr(draw_waveshare, 'last_track_id'):
draw_waveshare.last_track_id = ""
draw_waveshare.last_weather_id = ""
content_changed = True
if current_track_id != draw_waveshare.last_track_id:
content_changed = True
draw_waveshare.last_track_id = current_track_id
if hasattr(draw_waveshare, 'title_scroll_offset'):
draw_waveshare.title_scroll_offset = 0
draw_waveshare.artist_scroll_offset = 0
current_weather_id = None
if weather_info:
current_weather_id = f"{weather_info.get('city', '')}_{weather_info.get('temp', '')}_{weather_info.get('description', '')}"
if not hasattr(draw_waveshare, 'last_track_id'):
draw_waveshare.last_track_id = None
draw_waveshare.last_weather_id = None
content_changed = True
if current_track_id != draw_waveshare.last_track_id:
content_changed = True
draw_waveshare.last_track_id = current_track_id
if hasattr(draw_waveshare, 'title_scroll_offset'):
draw_waveshare.title_scroll_offset = 0
draw_waveshare.artist_scroll_offset = 0
if current_weather_id != draw_waveshare.last_weather_id:
content_changed = True
draw_waveshare.last_weather_id = current_weather_id
album_art_size = 80
album_art_x = display_width - album_art_size - 3
album_art_y = display_height - album_art_size - 3
if spotify_track:
artist = spotify_track.get('artists', 'Unknown Artist')
title = spotify_track.get('title', 'No Track')
with scroll_lock:
if not hasattr(draw_waveshare, 'title_scroll_offset'):
draw_waveshare.title_scroll_offset = 0
draw_waveshare.artist_scroll_offset = 0
title_bbox = draw.textbbox((0, 0), title, font=font_medium)
title_width = title_bbox[2] - title_bbox[0]
scroll_speed = 8
if title_width > display_width - 20:
total_scroll_distance = title_width + 15
draw_waveshare.title_scroll_offset = (draw_waveshare.title_scroll_offset + scroll_speed) % total_scroll_distance
title_x = -draw_waveshare.title_scroll_offset
draw.text((title_x, 8), title, font=font_medium, fill=0)
draw.text((title_x + total_scroll_distance, 8), title, font=font_medium, fill=0)
else:
title_x = (display_width - title_width) // 2
draw.text((title_x, 8), title, font=font_medium, fill=0)
artist_bbox = draw.textbbox((0, 0), artist, font=font_medium)
artist_width = artist_bbox[2] - artist_bbox[0]
if artist_width > display_width - 20:
total_scroll_distance = artist_width + 20
draw_waveshare.artist_scroll_offset = (draw_waveshare.artist_scroll_offset + scroll_speed) % total_scroll_distance
artist_x = -draw_waveshare.artist_scroll_offset
draw.text((artist_x, 25), artist, font=font_medium, fill=0)
draw.text((artist_x + total_scroll_distance, 25), artist, font=font_medium, fill=0)
else:
artist_x = (display_width - artist_width) // 2
draw.text((artist_x, 25), artist, font=font_medium, fill=0)
with art_lock:
album_img = album_art_image
if album_img is not None:
bw_album_art = convert_to_1bit_dithered(album_img, (album_art_size, album_art_size))
img.paste(bw_album_art, (album_art_x, album_art_y))
else:
if hasattr(draw_waveshare, 'title_scroll_offset'):
draw_waveshare.title_scroll_offset = 0
draw_waveshare.artist_scroll_offset = 0
draw.text((5, 8), "No music playing", font=font_medium, fill=0)
if weather_info:
weather_icon_x = 8
weather_icon_y = display_height - 55
if weather_info and "cached_icon" in weather_info and weather_info["cached_icon"] is not None:
try:
img.paste(weather_info["cached_icon"], (weather_icon_x, weather_icon_y))
except Exception as e:
print(f"Error pasting cached weather icon: {e}")
temp_text = f"Temp : {weather_info['temp']}°C"
draw.text((45, display_height - 55), temp_text, font=font_large, fill=0)
feels_like_text = f"Feels: {weather_info['feels_like']}°C"
draw.text((45, display_height - 35), feels_like_text, font=font_small, fill=0)
desc_text = weather_info['description'][:15]
draw.text((45, display_height - 20), desc_text, font=font_small, fill=0)
now = datetime.datetime.now().strftime("%H:%M")
time_bbox = draw.textbbox((0, 0), now, font=font_medium)
time_width = time_bbox[2] - time_bbox[0]
time_height = time_bbox[3] - time_bbox[1]
clock_x = 8
clock_y = display_height - 75
draw.text((clock_x, clock_y), now, font=font_medium, fill=0)
rotation = config.get("display", {}).get("rotation", 0)
if rotation == 180:
img = img.rotate(180, expand=False)
img.content_changed = content_changed
return img
def draw_waveshare_sleep_screen():
display_width = 250
display_height = 122
img = Image.new('1', (display_width, display_height), 255)
draw = ImageDraw.Draw(img)
draw.rectangle([0, 0, display_width-1, display_height-1], outline=0, width=2)
font_time = ImageFont.truetype(FONT_PATH_BOLD, 32)
font_date = ImageFont.truetype(FONT_PATH_BOLD, 18)
font_weather = ImageFont.truetype(FONT_PATH_BOLD, 18)
font_weather_small = ImageFont.truetype(FONT_PATH_BOLD, 16)
now = datetime.datetime.now()
time_str = now.strftime("%H:%M")
time_bbox = draw.textbbox((0, 0), time_str, font=font_time)
time_width = time_bbox[2] - time_bbox[0]
time_height = time_bbox[3] - time_bbox[1]
time_x = (display_width - time_width) // 2
time_y = (display_height - time_height) // 2 - 10
draw.text((time_x, time_y), time_str, font=font_time, fill=0)
date_str = now.strftime("%a, %b %d")
date_bbox = draw.textbbox((0, 0), date_str, font=font_date)
date_width = date_bbox[2] - date_bbox[0]
date_x = (display_width - date_width) // 2
date_y = time_y + time_height + 5
draw.text((date_x, date_y), date_str, font=font_date, fill=0)
if weather_info and OPENWEATHER_API_KEY:
weather_x = 5
temp_text = f"{weather_info['temp']}°C"
temp_bbox = draw.textbbox((0, 0), temp_text, font=font_weather)
temp_height = temp_bbox[3] - temp_bbox[1]
temp_y = display_height - temp_height - 5
draw.text((weather_x, temp_y), temp_text, font=font_weather, fill=0)
desc_text = weather_info['description']
desc_bbox = draw.textbbox((0, 0), desc_text, font=font_weather_small)
desc_height = desc_bbox[3] - desc_bbox[1]
desc_y = temp_y - desc_height - 2
draw.text((weather_x, desc_y), desc_text, font=font_weather_small, fill=0)
if "cached_icon" in weather_info and weather_info["cached_icon"] is not None:
try:
icon_y = desc_y - 35
img.paste(weather_info["cached_icon"], (weather_x, icon_y))
except Exception as e:
print(f"Error pasting weather icon: {e}")
rotation = config.get("display", {}).get("rotation", 0)
if rotation == 180:
img = img.rotate(180, expand=False)
img.content_changed = False
return img
def draw_text_aliased(draw, image, position, text, font, fill):
mask = Image.new("L", image.size, 0)
mask_draw = ImageDraw.Draw(mask)
mask_draw.text(position, text, fill=255, font=font)
color_layer = Image.new("RGB", image.size, fill)
image.paste(color_layer, (0, 0), mask)
def draw_text_with_background(img, text_elements):
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
overlay_draw = ImageDraw.Draw(overlay)
for text, position, font, color in text_elements:
bbox = get_cached_text_bbox_font(text, font)
actual_bbox = (position[0] + bbox[0], position[1] + bbox[1], position[0] + bbox[2], position[1] + bbox[3])
overlay_draw.rectangle([actual_bbox[0]-5, actual_bbox[1]-5, actual_bbox[2]+5, actual_bbox[3]+5], fill=(0, 0, 0, 200))
img = Image.alpha_composite(img.convert("RGBA"), overlay).convert("RGB")
draw = ImageDraw.Draw(img)
for text, position, font, color in text_elements:
draw_text_aliased(draw, img, position, text, font, color)
return img, draw
def init_st7789_display():
global st7789_display
if not HAS_ST7789: return None
try:
st7789_config = config["display"].get("st7789", {})
config_rotation = config["display"].get("rotation", 0)
st7789_display = st7789.ST7789(
port=st7789_config.get("spi_port", 0),