-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathticker.py
More file actions
1991 lines (1821 loc) · 109 KB
/
ticker.py
File metadata and controls
1991 lines (1821 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
#!/home/fpp/led-ticker/venv/bin/python
# -*- coding: utf-8 -*-
# Property of solutions reseaux chromatel
# =================================================================================================
# ================================== CONFIG (env defaults) ========================================
# =================================================================================================
import os, time, json, math
# Scroll position: round half toward -inf so the rendered pixel only ever moves left.
# round() uses banker's rounding which can snap 1px backward; floor() holds each pixel
# for a full pixel of travel making the stutter more visible. ceil(x-0.5) changes at
# the 0.5 mark (same cadence as round) but always rounds toward -inf — no backward blips.
_sp = lambda x: math.ceil(x - 0.5)
from datetime import datetime, date, time as dtime, timedelta, timezone
from multiprocessing import Process, Queue, set_start_method
from collections import deque
import queue as queue_std
import pygame
import signal
import sys
# Property of solutions reseaux chromatel
# Add pytz for proper market hours detection
try:
import pytz
PYTZ_AVAILABLE = True
except ImportError:
PYTZ_AVAILABLE = False
print("[WARN] pytz not available - market hours detection will be limited", flush=True)
# --------------------------------------------------------------------------------
# OUTPUT / DRIVER BEHAVIOR
# --------------------------------------------------------------------------------
# Import worker modules
from utils import (
is_us_market_open, get_market_event_announcement,
now_local, set_globals as set_utils_globals
)
from workers import (
market_worker, weather_worker, scoreboard_worker,
set_globals as set_worker_globals
)
# Import rendering module
from rendering import (
set_globals as set_rendering_globals, set_fonts,
BLACK, WHITE, RED, GREEN, YELLOW, GREY,
parse_color, fmt_price_compact, fmt_value_currency_compact,
format_weather_alert_text, parse_hhmm,
using_microfont,
current_dim_scale, apply_night_mode_speed,
init_pygame, write_surface_to_rgb_matrix, init_rgb_matrix,
make_font, get_row_font, get_sb_font, get_dbg_font,
get_preroll_big_font, get_maint_big_font,
row_render_text, build_time_surface, build_announcement_surface,
build_weather_alert_surface, build_message_surface, build_clock_surface,
build_preroll_bigtime_surface,
build_row_surfaces_from_cache, build_portfolio_parts, apply_dimming_inplace,
render_fullheight_scoreboard, ScoreboardFlashState,
clear_team_logo_cache
)
# --------------------------------------------------------------------------------
# RGB MATRIX HARDWARE SETTINGS
# --------------------------------------------------------------------------------
RGB_BRIGHTNESS = max(0, min(100, int(os.environ.get("RGB_BRIGHTNESS", "100") or 100))) # Brightness level 0-100
RGB_HARDWARE_MAPPING = (os.environ.get("RGB_HARDWARE_MAPPING", "adafruit-hat") or "adafruit-hat").strip() # Hardware adapter type
RGB_GPIO_SLOWDOWN = max(0, min(4, int(os.environ.get("RGB_GPIO_SLOWDOWN", "4") or 4))) # GPIO slowdown for stability (0-4)
RGB_PWM_BITS = max(1, min(11, int(os.environ.get("RGB_PWM_BITS", "11") or 11))) # PWM bits for color depth (1-11)
RGB_PWM_LSB_NANOSECONDS = max(50, min(3000, int(os.environ.get("RGB_PWM_LSB_NANOSECONDS", "130") or 130))) # PWM timing (50-3000)
# Advanced panel configuration
RGB_CHAIN_LENGTH = max(1, int(os.environ.get("RGB_CHAIN_LENGTH", "1") or 1)) # Number of panels chained horizontally
RGB_PARALLEL = max(1, int(os.environ.get("RGB_PARALLEL", "1") or 1)) # Number of parallel chains
RGB_SCAN_MODE = max(0, min(1, int(os.environ.get("RGB_SCAN_MODE", "0") or 0))) # 0=progressive, 1=interlaced
RGB_ROW_ADDRESS_TYPE = max(0, min(4, int(os.environ.get("RGB_ROW_ADDRESS_TYPE", "0") or 0))) # Row addressing: 0=direct, 1=AB, 2=direct-ABCDline, 3=ABC-shift, 4=ABC-ZigZag
RGB_MULTIPLEXING = max(0, min(18, int(os.environ.get("RGB_MULTIPLEXING", "0") or 0))) # Multiplexing type for specific panels
RGB_LED_RGB_SEQUENCE = (os.environ.get("RGB_LED_RGB_SEQUENCE", "RGB") or "RGB").strip().upper() # LED color order: RGB, RBG, GRB, GBR, BRG, BGR
RGB_PIXEL_MAPPER = (os.environ.get("RGB_PIXEL_MAPPER", "") or "").strip() # Pixel mapper config (e.g. "Rotate:90" or "U-mapper")
RGB_PANEL_TYPE = (os.environ.get("RGB_PANEL_TYPE", "") or "").strip() # Panel type hint (empty for default)
# --------------------------------------------------------------------------------
# CLOCK OVERRIDE (standalone big clock)
# --------------------------------------------------------------------------------
CLOCK_24H = os.environ.get("CLOCK_24H", "1") == "1" # True: 24-hour clock (HH:MM[/SS]). False: 12-hour (h:MM[/SS], no leading 0).
CLOCK_SHOW_SECONDS = os.environ.get("CLOCK_SHOW_SECONDS", "0") == "1" # Append :SS (more updates/more CPU; off is cleaner for LED).
CLOCK_BLINK_COLON = os.environ.get("CLOCK_BLINK_COLON", "1") == "1" # Blink colon every second (replaced with space when off).
CLOCK_COLOR = (os.environ.get("CLOCK_COLOR", "yellow") or "yellow") # Time color.
CLOCK_DATE_SHOW = os.environ.get("CLOCK_DATE_SHOW", "1") == "1" # If true, render a date line under time (centered).
CLOCK_DATE_FMT = (os.environ.get("CLOCK_DATE_FMT", "%a %b %d") or "%a %b %d") # ex: "Sat Feb 08".
CLOCK_DATE_COLOR = (os.environ.get("CLOCK_DATE_COLOR", "white") or "white") # Date color.
# --------------------------------------------------------------------------------
# DIAGNOSTICS
# --------------------------------------------------------------------------------
DEMO_MODE = os.environ.get("TICKER_DEMO", "0") == "1" # Skip network calls; render canned market values for bench testing.
DEBUG_OVERLAY= os.environ.get("DEBUG_OVERLAY", "0") == "1" # Draw small technical info at the bottom line (FPS/state/dim/etc.).
# --------------------------------------------------------------------------------
# MODEL / CANVAS / LAYOUT
# --------------------------------------------------------------------------------
MODEL_NAME = os.environ.get("FPP_MODEL_NAME", "Matrix192x16") # FPP model name; used for SHM filename and default WH resolver.
# DEPRECATED: SHM mode no longer supported - using RGB Matrix directly
W = int(os.environ.get("TICKER_W", "0") or 0) # Override panel width; 0 = auto by MODEL_NAME.
H = int(os.environ.get("TICKER_H", "0") or 0) # Override panel height; 0 = auto by MODEL_NAME.
# Layout is always dual (two 8px rows). Single-row mode removed.
# --------------------------------------------------------------------------------
# TIMEZONE
# --------------------------------------------------------------------------------
TICKER_TZ = (os.environ.get("TICKER_TZ", "America/Toronto") or "America/Toronto").strip()
# --------------------------------------------------------------------------------
# MAIN DISPLAY / FRAME RATE
# --------------------------------------------------------------------------------
try: FPS = max(1, int(os.environ.get("FPS", "60") or 60))
except: FPS = 60
try: PPS_TOP = float(os.environ.get("PPS_TOP", "40") or 40)
except: PPS_TOP = 40.0
try: PPS_BOT = float(os.environ.get("PPS_BOT", "40") or 40)
except: PPS_BOT = 40.0
try: REFRESH_SEC = max(10, int(os.environ.get("REFRESH_SEC", "120") or 120))
except: REFRESH_SEC = 120
try: FRESH_SEC = max(1, int(os.environ.get("FRESH_SEC", "180") or 180))
except: FRESH_SEC = 180
# --------------------------------------------------------------------------------
# TIME PREROLL
# --------------------------------------------------------------------------------
TIME_PREROLL_ENABLED = os.environ.get("TIME_PREROLL_ENABLED", "1") == "1"
try: TIME_PREROLL_SEC = max(0, int(os.environ.get("TIME_PREROLL_SEC", "15") or 15))
except: TIME_PREROLL_SEC = 15
PREROLL_STYLE = (os.environ.get("PREROLL_STYLE", "BIGTIME") or "BIGTIME").upper() # "BIGTIME", "MARQUEE", "MARKET_ANNOUNCE", "NONE"
PREROLL_COLOR = (os.environ.get("PREROLL_COLOR", "yellow") or "yellow").lower()
try: PREROLL_PPS = float(os.environ.get("PREROLL_PPS", "40") or 40)
except: PREROLL_PPS = 40.0
# --------------------------------------------------------------------------------
# MAINTENANCE MODE
# --------------------------------------------------------------------------------
MAINTENANCE_MODE = os.environ.get("MAINTENANCE_MODE", "0") == "1"
MAINTENANCE_TEXT = (os.environ.get("MAINTENANCE_TEXT", "SYSTEM MAINTENANCE EXPECTED BACK SOON") or "MAINTENANCE").strip()
MAINTENANCE_SCROLL = os.environ.get("MAINTENANCE_SCROLL", "1") == "1"
try: MAINTENANCE_PPS = float(os.environ.get("MAINTENANCE_PPS", "30") or 30)
except: MAINTENANCE_PPS = 30.0
# --------------------------------------------------------------------------------
# WEATHER WORKER
# --------------------------------------------------------------------------------
WEATHER_RSS_URL = os.environ.get("WEATHER_RSS_URL", "https://weather.gc.ca/rss/warning/qc-147_e.xml")
WEATHER_REFRESH_SEC = int(os.environ.get("WEATHER_REFRESH_SEC", "300")) # Poll RSS cadence (seconds).
WEATHER_ANNOUNCE_SEC= int(os.environ.get("WEATHER_ANNOUNCE_SEC", "12")) # How long to show the banner (seconds).
try: WEATHER_TIMEOUT = float(os.environ.get("WEATHER_TIMEOUT", "5.0"))
except: WEATHER_TIMEOUT = 5.0
WEATHER_INCLUDE_WATCH = os.environ.get("WEATHER_INCLUDE_WATCH", "1") == "1"
WEATHER_FORCE_ACTIVE = os.environ.get("WEATHER_FORCE_ACTIVE", "0") == "1"
WEATHER_FORCE_TEXT = (os.environ.get("WEATHER_FORCE_TEXT", "") or "").strip()
# Test harness: if >0, after N seconds, inject a synthetic "active" weather message.
try: WEATHER_TEST_DELAY = int(os.environ.get("WEATHER_TEST_DELAY", "0") or 0)
except: WEATHER_TEST_DELAY = 0
# In-render repeat logic: how often to re-announce the weather banner if it is *still* logically active.
# NOTE: We still respect WEATHER_ANNOUNCE_SEC as a minimum spacing from the worker.
try: WEATHER_REPEAT_SEC = int(os.environ.get("WEATHER_REPEAT_SEC", "600") or 600)
except: WEATHER_REPEAT_SEC = 600
# Where to draw the banner when dual: "top" or "bottom"; single layout always uses the only row.
# WEATHER_ROW and WEATHER_COLOR are deprecated - weather alerts always render full-screen
# using WEATHER_WARNING_COLOR / WEATHER_ADVISORY_COLOR for severity-based colors.
# --------------------------------------------------------------------------------
# WEATHER ALERT DISPLAY BY SEVERITY
# --------------------------------------------------------------------------------
# WARNING (red): Full 16px height, red color, show every N scrolls
try: WEATHER_WARNING_EVERY_N_SCROLLS = int(os.environ.get("WEATHER_WARNING_EVERY_N_SCROLLS", "5") or 5)
except: WEATHER_WARNING_EVERY_N_SCROLLS = 5
WEATHER_WARNING_COLOR = (os.environ.get("WEATHER_WARNING_COLOR", "red") or "red").lower()
# ADVISORY/WATCH (yellow): show every N scrolls
try: WEATHER_ADVISORY_EVERY_N_SCROLLS = int(os.environ.get("WEATHER_ADVISORY_EVERY_N_SCROLLS", "10") or 10)
except: WEATHER_ADVISORY_EVERY_N_SCROLLS = 10
WEATHER_ADVISORY_COLOR = (os.environ.get("WEATHER_ADVISORY_COLOR", "yellow") or "yellow").lower()
# STATEMENT (special weather statement): own color and scroll frequency
try: WEATHER_STATEMENT_EVERY_N_SCROLLS = int(os.environ.get("WEATHER_STATEMENT_EVERY_N_SCROLLS", "15") or 15)
except: WEATHER_STATEMENT_EVERY_N_SCROLLS = 15
WEATHER_STATEMENT_COLOR = (os.environ.get("WEATHER_STATEMENT_COLOR", "cyan") or "cyan").lower()
# TOP-OF-HOUR WEATHER PREROLL: show active alert full-screen after clock preroll
WEATHER_PREROLL_ENABLED = os.environ.get("WEATHER_PREROLL_ENABLED", "1") == "1"
try: WEATHER_PREROLL_SEC = int(os.environ.get("WEATHER_PREROLL_SEC", "8") or 8)
except: WEATHER_PREROLL_SEC = 8
# Test harness: if >0, after WEATHER_TEST_DELAY seconds, force an artificial active alert
# that remains logically "active" for this many seconds (0 = one-shot).
try: WEATHER_TEST_STICKY_TOTAL = int(os.environ.get("WEATHER_TEST_STICKY_TOTAL", "60") or 60)
except: WEATHER_TEST_STICKY_TOTAL = 60
# --------------------------------------------------------------------------------
# SCOREBOARD - PREGAME & POSTGAME TIMING
# --------------------------------------------------------------------------------
SCOREBOARD_PREGAME_WINDOW_MIN = int(os.environ.get("SCOREBOARD_PREGAME_WINDOW_MIN", "30")) # Show scoreboard N min before game starts
SCOREBOARD_POSTGAME_DELAY_MIN = int(os.environ.get("SCOREBOARD_POSTGAME_DELAY_MIN", "5")) # Keep showing scoreboard N min after FINAL
SCOREBOARD_SHOW_COUNTDOWN = os.environ.get("SCOREBOARD_SHOW_COUNTDOWN", "0") == "1" # Enable pregame countdown announces + T-N scoreboard flip
SCOREBOARD_PREGAME_ANNOUNCE_EVERY = max(1, int(os.environ.get("SCOREBOARD_PREGAME_ANNOUNCE_EVERY", "5") or 5)) # Inject every N top-row scroll completions
SCOREBOARD_PREGAME_ANNOUNCE_COLOR = (os.environ.get("SCOREBOARD_PREGAME_ANNOUNCE_COLOR", "cyan") or "cyan").lower() # Color for announce text
SCOREBOARD_LIVE_TRIGGER_MIN = max(1, int(os.environ.get("SCOREBOARD_LIVE_TRIGGER_MIN", "5") or 5)) # Minutes before start to flip into scoreboard mode
# --------------------------------------------------------------------------------
# MESSAGE INJECTOR
# --------------------------------------------------------------------------------
INJECT_MESSAGE = (os.environ.get("TICKER_MESSAGE", "*** DEV MODE ***") or "").strip() # Message to inject into scroll.
MESSAGE_EVERY = max(0, int(os.environ.get("MESSAGE_EVERY_SCROLLS", "5") or 0)) # Inject every N full scrolls (0=disabled).
MESSAGE_ROW = (os.environ.get("MESSAGE_ROW", "auto") or "auto").lower() # "top", "bottom", "single", "both", or "auto".
MESSAGE_COLOR = (os.environ.get("MESSAGE_COLOR", "magenta") or "yellow").lower() # Named color for message text.
MESSAGE_TEST_FORCE = os.environ.get("MESSAGE_TEST_FORCE", "0") == "1" # If true, message appears on **every** scroll.
# --------------------------------------------------------------------------------
# NIGHT MODE (time-based dimming + scroll speed reduction)
# --------------------------------------------------------------------------------
NIGHT_MODE_ENABLED = os.environ.get("NIGHT_MODE_ENABLED", "0") == "1"
NIGHT_MODE_START = (os.environ.get("NIGHT_MODE_START", "22:00") or "22:00").strip()
NIGHT_MODE_END = (os.environ.get("NIGHT_MODE_END", "07:00") or "07:00").strip()
try: NIGHT_MODE_DIM_PCT = int(os.environ.get("NIGHT_MODE_DIM_PCT", "30") or 30)
except: NIGHT_MODE_DIM_PCT = 30
try: NIGHT_MODE_SPEED_PCT = int(os.environ.get("NIGHT_MODE_SPEED_PCT", "50") or 50)
except: NIGHT_MODE_SPEED_PCT = 50
QUICK_DIM_PCT = 0 # Quick brightness override (1-100); 0 = disabled
# --------------------------------------------------------------------------------
# FONTS
# --------------------------------------------------------------------------------
FONT_FAMILY_BASE = (os.environ.get("FONT_FAMILY_BASE", "DejaVuSansMono") or "DejaVuSansMono")
FONT_FAMILY_SCOREBOARD = (os.environ.get("FONT_FAMILY_SCOREBOARD", FONT_FAMILY_BASE) or FONT_FAMILY_BASE)
FONT_FAMILY_DEBUG = (os.environ.get("FONT_FAMILY_DEBUG", FONT_FAMILY_BASE) or FONT_FAMILY_BASE)
PREROLL_FONT_FAMILY = (os.environ.get("PREROLL_FONT_FAMILY", FONT_FAMILY_BASE) or FONT_FAMILY_BASE)
MAINT_FONT_FAMILY = (os.environ.get("MAINT_FONT_FAMILY", FONT_FAMILY_BASE) or FONT_FAMILY_BASE)
FONT_SIZE_ROW = (os.environ.get("FONT_SIZE_ROW", "auto") or "auto")
FONT_SIZE_SB = (os.environ.get("FONT_SIZE_SB", "auto") or "auto")
FONT_SIZE_DEBUG = (os.environ.get("FONT_SIZE_DEBUG", "auto") or "auto")
try: PREROLL_FONT_PX = int(os.environ.get("PREROLL_FONT_PX", "0") or 0)
except: PREROLL_FONT_PX = 0
try: MAINT_FONT_PX = int(os.environ.get("MAINT_FONT_PX", "0") or 0)
except: MAINT_FONT_PX = 0
FONT_BOLD_BASE = os.environ.get("FONT_BOLD_BASE", "1") == "1"
FONT_BOLD_SB = os.environ.get("FONT_BOLD_SB", "1") == "1"
FONT_BOLD_DEBUG = os.environ.get("FONT_BOLD_DEBUG", "0") == "1"
PREROLL_FONT_BOLD= os.environ.get("PREROLL_FONT_BOLD", "1") == "1"
MAINT_FONT_BOLD = os.environ.get("MAINT_FONT_BOLD", "1") == "1"
# --------------------------------------------------------------------------------
# SCOREBOARD CORE
# --------------------------------------------------------------------------------
SCOREBOARD_ENABLED = os.environ.get("SCOREBOARD_ENABLED", "1") == "1"
SCOREBOARD_LEAGUES = [s.strip().upper() for s in (os.environ.get("SCOREBOARD_LEAGUES", "NHL,NFL") or "").split(",") if s.strip()]
SCOREBOARD_NHL_TEAMS= [s.strip().upper() for s in (os.environ.get("SCOREBOARD_NHL_TEAMS", "MTL") or "").split(",") if s.strip()]
SCOREBOARD_NFL_TEAMS= [s.strip().upper() for s in (os.environ.get("SCOREBOARD_NFL_TEAMS", "NE") or "").split(",") if s.strip()]
SCOREBOARD_POLL_WINDOW_MIN = int(os.environ.get("SCOREBOARD_POLL_WINDOW_MIN", "120") or 120)
SCOREBOARD_POLL_CADENCE = int(os.environ.get("SCOREBOARD_POLL_CADENCE", "60") or 60)
SCOREBOARD_LIVE_REFRESH = int(os.environ.get("SCOREBOARD_LIVE_REFRESH", "45") or 45)
SCOREBOARD_PRECEDENCE = (os.environ.get("SCOREBOARD_PRECEDENCE", "normal") or "normal").lower()
SCOREBOARD_HOME_FIRST = os.environ.get("SCOREBOARD_HOME_FIRST", "1") == "1"
SCOREBOARD_SHOW_CLOCK = os.environ.get("SCOREBOARD_SHOW_CLOCK", "1") == "1"
SCOREBOARD_SHOW_SOG = os.environ.get("SCOREBOARD_SHOW_SOG", "1") == "1"
SCOREBOARD_SHOW_POSSESSION = os.environ.get("SCOREBOARD_SHOW_POSSESSION", "1") == "1"
SCOREBOARD_INCLUDE_OTHERS = os.environ.get("SCOREBOARD_INCLUDE_OTHERS", "0") == "1"
SCOREBOARD_ONLY_MY_TEAMS = os.environ.get("SCOREBOARD_ONLY_MY_TEAMS", "1") == "1"
SCOREBOARD_MAX_GAMES = max(1, int(os.environ.get("SCOREBOARD_MAX_GAMES", "2") or 2))
# --------------------------------------------------------------------------------
# SCOREBOARD TEST HARNESS
# --------------------------------------------------------------------------------
SCOREBOARD_TEST = os.environ.get("SCOREBOARD_TEST", "0") == "1"
SCOREBOARD_TEST_LEAGUE = (os.environ.get("SCOREBOARD_TEST_LEAGUE", "NHL") or "NHL").upper()
SCOREBOARD_TEST_HOME = (os.environ.get("SCOREBOARD_TEST_HOME", "MTL") or "").upper()
SCOREBOARD_TEST_AWAY = (os.environ.get("SCOREBOARD_TEST_AWAY", "TOR") or "").upper()
SCOREBOARD_TEST_DURATION= int(os.environ.get("SCOREBOARD_TEST_DURATION", "0") or 0)
# --------------------------------------------------------------------------------
# OVERRIDES (temporary modes)
# --------------------------------------------------------------------------------
OVERRIDE_MODE = (os.environ.get("OVERRIDE_MODE", "OFF") or "OFF").upper() # "OFF","BRIGHT","SCOREBOARD","MESSAGE","MAINT","CLOCK","LOGO"
try: OVERRIDE_DURATION_MIN = int(os.environ.get("OVERRIDE_DURATION_MIN", "0") or 0)
except: OVERRIDE_DURATION_MIN = 0
OVERRIDE_MESSAGE_TEXT = (os.environ.get("OVERRIDE_MESSAGE_TEXT", "") or "").strip()
LOGO_PATH = (os.environ.get("LOGO_PATH", "logo.png") or "logo.png").strip()
LOGO_PPS = float(os.environ.get("LOGO_PPS", "30.0") or 30.0)
LOGO_SCROLL = os.environ.get("LOGO_SCROLL", "1") == "1" # True=scroll, False=centered static
OVERRIDE_MESSAGE_SCROLL = os.environ.get("OVERRIDE_MESSAGE_SCROLL", "1") == "1" # True=scroll, False=centered static
OVERRIDE_MESSAGE_COLOR = (os.environ.get("OVERRIDE_MESSAGE_COLOR", "yellow") or "yellow").strip()
# --------------------------------------------------------------------------------
# SCORE ALERTS (centered flash)
# --------------------------------------------------------------------------------
SCORE_ALERTS_ENABLED = os.environ.get("SCORE_ALERTS_ENABLED", "1") == "1"
SCORE_ALERTS_NHL = os.environ.get("SCORE_ALERTS_NHL", "1") == "1"
SCORE_ALERTS_NFL = os.environ.get("SCORE_ALERTS_NFL", "1") == "1"
SCORE_ALERTS_MY_TEAMS_ONLY= os.environ.get("SCORE_ALERTS_MY_TEAMS_ONLY", "1") == "1"
try: SCORE_ALERTS_CYCLES = int(os.environ.get("SCORE_ALERTS_CYCLES", "2") or 2)
except: SCORE_ALERTS_CYCLES = 2
try: SCORE_ALERTS_QUEUE_MAX = int(os.environ.get("SCORE_ALERTS_QUEUE_MAX", "4") or 4)
except: SCORE_ALERTS_QUEUE_MAX= 4
try: SCORE_ALERTS_FLASH_MS = int(os.environ.get("SCORE_ALERTS_FLASH_MS", "250") or 250)
except: SCORE_ALERTS_FLASH_MS = 250
SCORE_ALERTS_FLASH_COLORS = [c.strip().lower() for c in (os.environ.get("SCORE_ALERTS_FLASH_COLORS", "red,white,blue") or "red,white,blue").split(",") if c.strip()]
try: SCORE_ALERTS_NFL_TD_DELTA_MIN = int(os.environ.get("SCORE_ALERTS_NFL_TD_DELTA_MIN","6") or 6)
except: SCORE_ALERTS_NFL_TD_DELTA_MIN = 6
SCORE_ALERTS_TEST = os.environ.get("SCORE_ALERTS_TEST", "0") == "1"
SCORE_ALERTS_TEST_LEAGUE = (os.environ.get("SCORE_ALERTS_TEST_LEAGUE","NHL") or "NHL").upper()
SCORE_ALERTS_TEST_TEAM = (os.environ.get("SCORE_ALERTS_TEST_TEAM","MTL") or "MTL").upper()
try: SCORE_ALERTS_TEST_INTERVAL_SEC = int(os.environ.get("SCORE_ALERTS_TEST_INTERVAL_SEC","12") or 12)
except: SCORE_ALERTS_TEST_INTERVAL_SEC = 12
# --------------------------------------------------------------------------------
# MICROFONT
# --------------------------------------------------------------------------------
MICROFONT_ENABLED = os.environ.get("MICROFONT_ENABLED", "0") == "1" # In dual layout, use a crisp 5x7 microfont for row text.
# =================================================================================================
# ============================== Ticker lists + holdings (defaults) ===============================
# =================================================================================================
# The default symbol sets (overridable in config.json as TICKERS_TOP/BOT).
TICKERS_TOP = [
("^IXIC", "NAS"),
("^GSPC", "S&P"), # S&P 500
("^GSPTSE", "TSX"),
("CADUSD=X", "CAD/USD"),
("GC=F", "GOLD"),
]
TICKERS_BOT = [
("AAPL", ""),
("MSFT", ""),
("GOOGL", ""),
("AMZN", ""),
("NVDA", ""),
("TSLA", ""),
("META", ""),
("TSM", ""),
]
TICKERS_BOT2 = [] # Alternate bottom row (shown every other scroll); empty = no alternating
HOLDINGS_ENABLED = False
HOLDINGS = {} # {"SYM": {"shares": float}, ...}
PORTFOLIO_DISPLAY_ENABLED = False # Show portfolio total at the start of the top row
PORTFOLIO_LABEL = (os.environ.get("PORTFOLIO_LABEL", "MY") or "MY").strip().upper()
# Bottom-row portfolio group summaries: each prepends a labelled total to its alternating row.
# BOT_GROUP1 → bot_parts (TICKERS_BOT, even completed_bot)
# BOT_GROUP2 → bot_parts2 (TICKERS_BOT2, odd completed_bot)
# Membership is derived automatically: symbols from the respective display row that also exist
# in HOLDINGS. Add a ticker to the row + HOLDINGS and it's automatically counted — no third list.
BOT_GROUP1_LABEL = (os.environ.get("BOT_GROUP1_LABEL", "TFSA") or "TFSA").strip().upper()
BOT_GROUP1_ENABLED = os.environ.get("BOT_GROUP1_ENABLED", "0") == "1"
BOT_GROUP2_LABEL = (os.environ.get("BOT_GROUP2_LABEL", "RRSP") or "RRSP").strip().upper()
BOT_GROUP2_ENABLED = os.environ.get("BOT_GROUP2_ENABLED", "0") == "1"
# Default weathers have a sticky time in seconds (show for X seconds after active).
try: WEATHER_STICKY_SEC = int(os.environ.get("WEATHER_STICKY_SEC", "12") or 12)
except: WEATHER_STICKY_SEC = 12
# =================================================================================================
# ===================================== PANEL/LAYOUT SETUP ========================================
# =================================================================================================
def _resolve_tz():
"""Return a pytz timezone for TICKER_TZ if available, else None."""
if not PYTZ_AVAILABLE:
return None
try:
return pytz.timezone(TICKER_TZ)
except Exception:
print(f"[WARN] Timezone '{TICKER_TZ}' invalid; using local system time.", flush=True)
return None
def _resolve_panel_size():
"""
Auto-detect or override WxH. If both W and H are specified in env/config, use them.
Otherwise infer from MODEL_NAME. If both are 0, default to 96x16 for safety.
"""
global W, H
if W > 0 and H > 0:
return
mn = (MODEL_NAME or "").lower()
if "96x32" in mn:
W, H = 96, 32
elif "192x16" in mn:
W, H = 192, 16
elif "96x16" in mn:
W, H = 96, 16
else:
W, H = max(1, W), max(1, H) # keep env overrides if user-provided
if W <= 0 or H <= 0:
W, H = 96, 16
_resolve_panel_size()
IS_DUAL = True # Always dual (two 8px rows); single-row mode removed
IS_SINGLE = False # Single-row mode removed; kept for reference guards
ROW_H, TOP_Y, BOT_Y = H, 0, 0 # Will be recomputed in _recompute_layout_globals
TZINFO = _resolve_tz()
# --- Top-of-hour helper: compute the next local hour boundary (aligned to wall clock) ---
def _compute_next_hour_ts(now_dt=None):
# Return a unix timestamp for the next top-of-hour in local tz.
if now_dt is None:
now_dt = now_local()
hour_start = now_dt.replace(minute=0, second=0, microsecond=0)
next_hour = hour_start + timedelta(hours=1)
return next_hour.timestamp()
# Score Alerts - colors via parse_color
_SCORE_FLASH_COLORS = [parse_color(c) for c in (SCORE_ALERTS_FLASH_COLORS or ['red','white','blue'])]
class ScoreAlert:
"""Flashing static banner for GOAL/TOUCHDOWN events."""
def __init__(self, league: str, team: str, score: int, cycles: int):
self.league = league
self.team = team
self.score = score
n = max(1, len(_SCORE_FLASH_COLORS))
self.flashes_left = max(1, cycles) * n
self.flash_idx = 0
self.flash_next_ts = time.time() + (SCORE_ALERTS_FLASH_MS / 1000.0)
def current_color(self):
now = time.time()
if now >= self.flash_next_ts:
self.flash_idx = (self.flash_idx + 1) % max(1, len(_SCORE_FLASH_COLORS))
self.flash_next_ts = now + (SCORE_ALERTS_FLASH_MS / 1000.0)
self.flashes_left -= 1
return _SCORE_FLASH_COLORS[self.flash_idx]
@property
def done(self):
return self.flashes_left <= 0
# =================================================================================================
# ============================ config loader + hot reload (config.json) ============================
# =================================================================================================
CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
STATUS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ticker_status.json")
_cfg_mtime = 0.0
def _atomic_load_json(path: str) -> dict:
"""Load JSON safely ({} on error)."""
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f) or {}
except Exception:
return {}
def _recompute_layout_globals():
"""Recompute row geometry after W/H changes. Always dual layout."""
global W, H, ROW_H, TOP_Y, BOT_Y
_resolve_panel_size()
ROW_H = H // 2; TOP_Y = 0; BOT_Y = ROW_H
def _apply_config(cfg: dict) -> dict:
"""Apply config.json into globals and set 'changed' flags per category."""
g = globals()
changed = {"any": False, "layout": False, "dim": False, "markets": False, "scoreboard": False, "override": False, "weather": False, "message": False, "portfolio": False}
def set_if(key):
if key not in cfg: return
old = g.get(key, None); new = cfg[key]
# Apply transformations for specific keys
if key == "PREROLL_STYLE" and isinstance(new, str):
new = new.upper()
if key in ("OVERRIDE_MODE",) and isinstance(new, str):
new = new.upper()
if old != new:
g[key] = new; changed["any"]=True
# Treat clock tunables as "override" changes so they apply immediately
if key.startswith("CLOCK_"): changed["override"] = True
if key in ("MODEL_NAME","W","H","LAYOUT"): changed["layout"]=True
if key.startswith("NIGHT_MODE") or key == "QUICK_DIM_PCT": changed["dim"]=True
if key in ("TICKERS_TOP","TICKERS_BOT","TICKERS_BOT2","HOLDINGS","HOLDINGS_ENABLED"): changed["markets"]=True
if key in ("PORTFOLIO_DISPLAY_ENABLED","PORTFOLIO_LABEL","BOT_GROUP1_LABEL","BOT_GROUP1_ENABLED","BOT_GROUP2_LABEL","BOT_GROUP2_ENABLED"): changed["portfolio"]=True
# Display-only SCOREBOARD_ keys don't require a worker restart (worker doesn't use them)
_sb_display_only = {
"SCOREBOARD_SHOW_SOG", "SCOREBOARD_SHOW_CLOCK", "SCOREBOARD_SHOW_POSSESSION",
"SCOREBOARD_HOME_FIRST", "SCOREBOARD_PRECEDENCE", "SCOREBOARD_SHOW_COUNTDOWN",
"SCOREBOARD_PREGAME_ANNOUNCE_EVERY", "SCOREBOARD_PREGAME_ANNOUNCE_COLOR",
"SCOREBOARD_LIVE_TRIGGER_MIN",
}
if key.startswith("SCOREBOARD_") and key not in _sb_display_only: changed["scoreboard"]=True
if key.startswith("OVERRIDE_"): changed["override"]=True
if key in ("LOGO_PATH", "LOGO_PPS", "LOGO_SCROLL", "OVERRIDE_MESSAGE_SCROLL"): changed["override"]=True
if key.startswith("WEATHER_"): changed["weather"]=True
if key in ("INJECT_MESSAGE","MESSAGE_EVERY","MESSAGE_ROW","MESSAGE_COLOR","MESSAGE_TEST_FORCE"): changed["message"]=True
for k in [
"RGB_BRIGHTNESS","RGB_HARDWARE_MAPPING","RGB_GPIO_SLOWDOWN","RGB_PWM_BITS","RGB_PWM_LSB_NANOSECONDS",
"RGB_CHAIN_LENGTH","RGB_PARALLEL","RGB_SCAN_MODE","RGB_ROW_ADDRESS_TYPE","RGB_MULTIPLEXING",
"RGB_LED_RGB_SEQUENCE","RGB_PIXEL_MAPPER","RGB_PANEL_TYPE",
"MODEL_NAME","W","H","LAYOUT","TICKER_TZ",
"FPS","PPS_TOP","PPS_BOT","PPS_SINGLE","REFRESH_SEC","FRESH_SEC",
"TIME_PREROLL_ENABLED","TIME_PREROLL_SEC","PREROLL_STYLE","PREROLL_COLOR","PREROLL_PPS",
"MAINTENANCE_MODE","MAINTENANCE_TEXT","MAINTENANCE_SCROLL","MAINTENANCE_PPS",
"WEATHER_RSS_URL","WEATHER_REFRESH_SEC","WEATHER_ANNOUNCE_SEC","WEATHER_TIMEOUT",
"WEATHER_INCLUDE_WATCH","WEATHER_FORCE_ACTIVE","WEATHER_FORCE_TEXT","WEATHER_TEST_DELAY","WEATHER_WARNING_EVERY_N_SCROLLS","WEATHER_WARNING_COLOR","WEATHER_ADVISORY_EVERY_N_SCROLLS","WEATHER_ADVISORY_COLOR","WEATHER_STATEMENT_EVERY_N_SCROLLS","WEATHER_STATEMENT_COLOR","WEATHER_PREROLL_ENABLED","WEATHER_PREROLL_SEC","WEATHER_STICKY_SEC","WEATHER_TEST_STICKY_TOTAL","WEATHER_REPEAT_SEC",
"INJECT_MESSAGE","MESSAGE_EVERY","MESSAGE_ROW","MESSAGE_COLOR","MESSAGE_TEST_FORCE",
"NIGHT_MODE_ENABLED","NIGHT_MODE_START","NIGHT_MODE_END","NIGHT_MODE_DIM_PCT","NIGHT_MODE_SPEED_PCT","QUICK_DIM_PCT",
"FONT_FAMILY_BASE","FONT_FAMILY_SCOREBOARD","FONT_FAMILY_DEBUG","PREROLL_FONT_FAMILY","MAINT_FONT_FAMILY",
"FONT_SIZE_ROW","FONT_SIZE_SB","FONT_SIZE_DEBUG","PREROLL_FONT_PX","MAINT_FONT_PX",
"FONT_BOLD_BASE","FONT_BOLD_SB","FONT_BOLD_DEBUG","PREROLL_FONT_BOLD","MAINT_FONT_BOLD",
"SCOREBOARD_ENABLED","SCOREBOARD_LEAGUES","SCOREBOARD_NHL_TEAMS","SCOREBOARD_NFL_TEAMS",
"SCOREBOARD_POLL_WINDOW_MIN","SCOREBOARD_POLL_CADENCE","SCOREBOARD_LIVE_REFRESH",
"SCOREBOARD_PREGAME_WINDOW_MIN","SCOREBOARD_POSTGAME_DELAY_MIN","SCOREBOARD_SHOW_COUNTDOWN",
"SCOREBOARD_PREGAME_ANNOUNCE_EVERY","SCOREBOARD_PREGAME_ANNOUNCE_COLOR","SCOREBOARD_LIVE_TRIGGER_MIN",
"SCOREBOARD_PRECEDENCE","SCOREBOARD_HOME_FIRST",
"SCOREBOARD_SHOW_CLOCK","SCOREBOARD_SHOW_SOG","SCOREBOARD_SHOW_POSSESSION",
"SCOREBOARD_INCLUDE_OTHERS","SCOREBOARD_ONLY_MY_TEAMS","SCOREBOARD_MAX_GAMES",
"OVERRIDE_MODE","OVERRIDE_DURATION_MIN","OVERRIDE_MESSAGE_TEXT","OVERRIDE_MESSAGE_SCROLL","OVERRIDE_MESSAGE_COLOR","LOGO_PATH","LOGO_PPS","LOGO_SCROLL",
"SCORE_ALERTS_ENABLED","SCORE_ALERTS_NHL","SCORE_ALERTS_NFL","SCORE_ALERTS_MY_TEAMS_ONLY",
"SCORE_ALERTS_CYCLES","SCORE_ALERTS_QUEUE_MAX","SCORE_ALERTS_FLASH_MS","SCORE_ALERTS_FLASH_COLORS",
"SCORE_ALERTS_NFL_TD_DELTA_MIN","SCORE_ALERTS_TEST","SCORE_ALERTS_TEST_LEAGUE","SCORE_ALERTS_TEST_TEAM","SCORE_ALERTS_TEST_INTERVAL_SEC",
"TICKERS_TOP","TICKERS_BOT","TICKERS_BOT2","HOLDINGS_ENABLED","HOLDINGS","PORTFOLIO_DISPLAY_ENABLED","PORTFOLIO_LABEL",
"BOT_GROUP1_LABEL","BOT_GROUP1_ENABLED",
"BOT_GROUP2_LABEL","BOT_GROUP2_ENABLED",
"MICROFONT_ENABLED",
"SCOREBOARD_TEST","SCOREBOARD_TEST_LEAGUE","SCOREBOARD_TEST_HOME","SCOREBOARD_TEST_AWAY","SCOREBOARD_TEST_DURATION",
# CLOCK override tunables
"CLOCK_24H","CLOCK_SHOW_SECONDS","CLOCK_BLINK_COLON","CLOCK_COLOR","CLOCK_DATE_SHOW","CLOCK_DATE_FMT","CLOCK_DATE_COLOR",
# Diagnostics and test flags
"DEBUG_OVERLAY","DEMO_MODE",
]:
set_if(k)
if changed["layout"]: _recompute_layout_globals()
return changed
def _initial_config_load():
"""Load config.json once at startup (BEFORE printing the banner)."""
global _cfg_mtime, TZINFO
try:
cfg = _atomic_load_json(CONFIG_PATH)
if cfg:
changes = _apply_config(cfg)
try: _cfg_mtime = os.path.getmtime(CONFIG_PATH)
except Exception: _cfg_mtime = 0.0
TZINFO = _resolve_tz()
print(f"[START] Loaded config.json from {CONFIG_PATH} (changes: {changes})", flush=True)
else:
print(f"[START] No config.json overrides found at {CONFIG_PATH}", flush=True)
except Exception as e:
print(f"[START] config.json load error: {e}", flush=True)
def _maybe_reload_config() -> dict:
"""Hot-reload config.json when mtime changes; return change flags."""
global _cfg_mtime, TZINFO
try:
m = os.path.getmtime(CONFIG_PATH)
except Exception:
return {"reloaded": False}
if m <= _cfg_mtime:
return {"reloaded": False}
cfg = _atomic_load_json(CONFIG_PATH)
changes = _apply_config(cfg)
_cfg_mtime = m
TZINFO = _resolve_tz()
print(f"[CFG] Reloaded config.json (flags: {changes})", flush=True)
return {"reloaded": True, **changes}
# =================================================================================================
# =========================================== MAIN ================================================
# =================================================================================================
def run_maintenance_loop(screen, clock, maint_font):
"""
Minimal maintenance mode loop: just scroll MAINTENANCE_TEXT indefinitely.
Press Ctrl+C or send SIGTERM to exit.
"""
import pygame
x = float(W)
txt = (MAINTENANCE_TEXT or "MAINTENANCE").upper()
srf = maint_font.render(txt, True, WHITE)
pps = max(1.0, float(MAINTENANCE_PPS))
while True:
dt = clock.tick(FPS)/1000.0
frame = pygame.Surface((W, H)); frame.fill(BLACK)
if MAINTENANCE_SCROLL:
w = srf.get_width()
y = max(0, (H - srf.get_height())//2)
if -w < x < W: frame.blit(srf, (_sp(x), y))
x -= pps*dt
if x < -w: x = float(W)
else:
wt = srf.get_width()
xt = max(0, (W - wt)//2)
y = max(0, (H - srf.get_height())//2)
frame.blit(srf, (xt, y))
write_surface_to_rgb_matrix(frame)
try:
pygame.image.save(frame, "/tmp/ticker_preview.png")
except Exception:
pass
# Global shutdown flag
_shutdown_requested = False
def _signal_handler(signum, frame):
"""Handle SIGTERM and SIGINT gracefully."""
global _shutdown_requested
sig_name = "SIGTERM" if signum == signal.SIGTERM else "SIGINT"
print(f"\n[SIGNAL] Received {sig_name}, initiating clean shutdown...", flush=True)
_shutdown_requested = True
def _terminate_worker(proc):
"""Terminate a worker process gracefully, falling back to kill."""
if proc and proc.is_alive():
proc.terminate()
proc.join(timeout=1.0)
if proc.is_alive():
proc.kill()
proc.join(timeout=0.5)
def _push_alert(alert_queue, entry):
"""Push an alert entry onto the alert_queue, evicting oldest if full."""
if len(alert_queue) >= alert_queue.maxlen:
try:
alert_queue.popleft()
except Exception:
pass
alert_queue.append(entry)
def _extract_live_game_data(scoreboard_latest):
"""Find the first live game in scoreboard_latest and return a game_data dict, or None."""
for league_key in ("NHL", "NFL"):
payload = scoreboard_latest.get(league_key)
if payload and payload.get("games"):
for g in payload["games"]:
if g.get("state") == "LIVE":
home_code = g.get("home", {}).get("code", "???")
away_code = g.get("away", {}).get("code", "???")
home_score = g.get("home", {}).get("score", 0)
away_score = g.get("away", {}).get("score", 0)
game_clock = g.get("clock", "")
period = g.get("period_label", "")
if not period:
period_num = g.get("period", 0)
if league_key == "NHL":
period = "OT" if period_num > 3 else f"P{period_num}"
elif league_key == "NFL":
period = f"Q{period_num}"
return {
"home_code": home_code,
"away_code": away_code,
"home_score": home_score,
"away_score": away_score,
"home_sog": int((g.get("home") or {}).get("sog", 0) or 0),
"away_sog": int((g.get("away") or {}).get("sog", 0) or 0),
"clock": game_clock,
"period": period,
"league": league_key
}
return None
def _get_pregame_announce_game(scoreboard_latest, max_minutes):
"""Return (game_dict, league_key) for the first watched-team PREGAME game within
max_minutes of start, or (None, None). Only fires for teams in SCOREBOARD_NHL_TEAMS /
SCOREBOARD_NFL_TEAMS so 'others' games don't trigger announcements."""
for league_key in ("NHL", "NFL"):
payload = scoreboard_latest.get(league_key)
if not (payload and payload.get("games")):
continue
wanted = set()
if league_key == "NHL":
wanted = {t.upper() for t in (SCOREBOARD_NHL_TEAMS or [])}
elif league_key == "NFL":
wanted = {t.upper() for t in (SCOREBOARD_NFL_TEAMS or [])}
for g in payload["games"]:
if g.get("state") != "PREGAME":
continue
mins = g.get("minutes_until_start", 9999)
if mins > max_minutes:
continue
home = (g.get("home") or {}).get("code", "").upper()
away = (g.get("away") or {}).get("code", "").upper()
if not wanted or home in wanted or away in wanted:
return g, league_key
return None, None
def _extract_pregame_game_data(scoreboard_latest, trigger_min):
"""Return a game_data dict (same shape as _extract_live_game_data) for a PREGAME
game within trigger_min minutes of start, for the T-N scoreboard flip. Returns None
if no such game exists."""
for league_key in ("NHL", "NFL"):
payload = scoreboard_latest.get(league_key)
if not (payload and payload.get("games")):
continue
for g in payload["games"]:
if g.get("state") != "PREGAME":
continue
mins = g.get("minutes_until_start", 9999)
if mins <= trigger_min:
return {
"home_code": (g.get("home") or {}).get("code", "???"),
"away_code": (g.get("away") or {}).get("code", "???"),
"home_score": 0,
"away_score": 0,
"clock": "SOON" if mins <= 1 else f"{mins}m",
"period": "PRE",
"league": league_key,
}
return None
def _load_logo_surface(path: str, target_h: int):
"""Load a logo image, scale to target_h pixels tall (preserving aspect ratio).
Uses PIL for loading — reliable in headless/dummy SDL mode where pygame.image.load
can fail to decode PNG/JPG without SDL_image. PIL is already a hard dependency
(used in write_surface_to_rgb_matrix).
Relative paths are resolved against the ticker.py script directory first."""
# Resolve relative path against the script's own directory
if not os.path.isabs(path):
script_dir = os.path.dirname(os.path.abspath(__file__))
candidate = os.path.join(script_dir, path)
if os.path.isfile(candidate):
path = candidate
try:
from PIL import Image as _PILImage
pil_img = _PILImage.open(path).convert("RGBA")
orig_w, orig_h = pil_img.size
if orig_h == 0:
return None
scale = target_h / orig_h
new_w = max(1, int(orig_w * scale))
pil_scaled = pil_img.resize((new_w, target_h), _PILImage.LANCZOS)
# pygame.image.frombuffer with RGBA avoids any display-mode requirement
surf = pygame.image.frombuffer(pil_scaled.tobytes(), (new_w, target_h), "RGBA")
out = pygame.Surface((new_w, target_h), pygame.SRCALPHA)
out.blit(surf, (0, 0))
print(f"[LOGO] Loaded '{path}' → {new_w}×{target_h}px", flush=True)
return out
except Exception as e:
print(f"[LOGO] Failed to load '{path}': {e}", flush=True)
return None
def run():
global _shutdown_requested
# Register signal handlers for clean shutdown
signal.signal(signal.SIGTERM, _signal_handler)
signal.signal(signal.SIGINT, _signal_handler)
# 1) Load config first
_initial_config_load()
# No longer need SHM_PATH with RGB Matrix mode
# 2) Initialize rendering module globals
set_rendering_globals(
W=W, H=H, ROW_H=ROW_H, TOP_Y=TOP_Y, BOT_Y=BOT_Y,
MICROFONT_ENABLED=MICROFONT_ENABLED,
TZINFO=TZINFO,
NIGHT_MODE_ENABLED=NIGHT_MODE_ENABLED,
NIGHT_MODE_START=NIGHT_MODE_START,
NIGHT_MODE_END=NIGHT_MODE_END,
NIGHT_MODE_DIM_PCT=NIGHT_MODE_DIM_PCT,
NIGHT_MODE_SPEED_PCT=NIGHT_MODE_SPEED_PCT,
QUICK_DIM_PCT=QUICK_DIM_PCT,
HOLDINGS=HOLDINGS,
HOLDINGS_ENABLED=HOLDINGS_ENABLED,
FONT_FAMILY_BASE=FONT_FAMILY_BASE,
FONT_SIZE_ROW=FONT_SIZE_ROW,
FONT_BOLD_BASE=FONT_BOLD_BASE,
FONT_FAMILY_SCOREBOARD=FONT_FAMILY_SCOREBOARD,
FONT_SIZE_SB=FONT_SIZE_SB,
FONT_BOLD_SB=FONT_BOLD_SB,
FONT_FAMILY_DEBUG=FONT_FAMILY_DEBUG,
FONT_SIZE_DEBUG=FONT_SIZE_DEBUG,
FONT_BOLD_DEBUG=FONT_BOLD_DEBUG,
PREROLL_FONT_FAMILY=PREROLL_FONT_FAMILY,
PREROLL_FONT_PX=PREROLL_FONT_PX,
PREROLL_FONT_BOLD=PREROLL_FONT_BOLD,
PREROLL_COLOR=PREROLL_COLOR,
MAINT_FONT_FAMILY=MAINT_FONT_FAMILY,
MAINT_FONT_PX=MAINT_FONT_PX,
MAINT_FONT_BOLD=MAINT_FONT_BOLD,
CLOCK_24H=CLOCK_24H,
CLOCK_SHOW_SECONDS=CLOCK_SHOW_SECONDS,
CLOCK_BLINK_COLON=CLOCK_BLINK_COLON,
CLOCK_COLOR=CLOCK_COLOR,
CLOCK_DATE_SHOW=CLOCK_DATE_SHOW,
CLOCK_DATE_FMT=CLOCK_DATE_FMT,
CLOCK_DATE_COLOR=CLOCK_DATE_COLOR
)
# 3) Show banner
start_ts = time.time()
print("="*80, flush=True)
print(f"[START] LED Ticker {W}x{H} (layout={LAYOUT}, fps={FPS})", flush=True)
print(f"[START] Timezone: {TICKER_TZ} (TZINFO={TZINFO})", flush=True)
print(f"[START] Config file: {CONFIG_PATH}", flush=True)
if DEMO_MODE: print("[START] DEMO MODE: no network calls", flush=True)
if DEBUG_OVERLAY: print("[START] DEBUG overlay ON (bottom line)", flush=True)
if MICROFONT_ENABLED: print("[START] Microfont enabled for dual layout row text", flush=True)
if TIME_PREROLL_ENABLED:
print(f"[START] Time preroll: ENABLED {TIME_PREROLL_SEC}s style={PREROLL_STYLE} color={PREROLL_COLOR} pps={PREROLL_PPS}", flush=True)
else:
print(f"[START] Time preroll: DISABLED", flush=True)
print(f"[START] Weather worker: RSS={bool(WEATHER_RSS_URL)} force_active={int(WEATHER_FORCE_ACTIVE)} test_delay={WEATHER_TEST_DELAY} announce={WEATHER_ANNOUNCE_SEC}s repeat={WEATHER_REPEAT_SEC}s", flush=True)
if NIGHT_MODE_ENABLED:
print(f"[START] Night Mode: {NIGHT_MODE_START}-{NIGHT_MODE_END} dim={NIGHT_MODE_DIM_PCT}% speed={NIGHT_MODE_SPEED_PCT}%", flush=True)
if INJECT_MESSAGE and MESSAGE_EVERY>0: print(f"[START] Message injector: every {MESSAGE_EVERY} scrolls row={MESSAGE_ROW} color={MESSAGE_COLOR}", flush=True)
if MESSAGE_TEST_FORCE: print("[START] Message TEST: force every scroll", flush=True)
if MAINTENANCE_MODE: print(f"[START] Maintenance: scroll={int(MAINTENANCE_SCROLL)} pps={MAINTENANCE_PPS}", flush=True)
if SCOREBOARD_ENABLED:
print(f"[START] Scoreboard: leagues={SCOREBOARD_LEAGUES} NHL={SCOREBOARD_NHL_TEAMS} NFL={SCOREBOARD_NFL_TEAMS} test={int(SCOREBOARD_TEST)} precedence={SCOREBOARD_PRECEDENCE} my_only={int(SCOREBOARD_ONLY_MY_TEAMS)}", flush=True)
if SCORE_ALERTS_ENABLED:
print(f"[START] Score Alerts: NHL={int(SCORE_ALERTS_NHL)} NFL={int(SCORE_ALERTS_NFL)} my_only={int(SCORE_ALERTS_MY_TEAMS_ONLY)} cycles={SCORE_ALERTS_CYCLES} queue={SCORE_ALERTS_QUEUE_MAX} flash_ms={SCORE_ALERTS_FLASH_MS} test={int(SCORE_ALERTS_TEST)}", flush=True)
# Compute override AFTER config load (and keep variables mutable for reload)
override_mode = OVERRIDE_MODE if OVERRIDE_MODE in ("BRIGHT","SCOREBOARD","MESSAGE","MAINT","CLOCK","LOGO") else "OFF"
override_active = (override_mode != "OFF")
override_end_ts = (time.time() + OVERRIDE_DURATION_MIN*60) if (override_active and OVERRIDE_DURATION_MIN>0) else None
if override_active:
dur_str = f"{OVERRIDE_DURATION_MIN} min" if OVERRIDE_DURATION_MIN>0 else "until cleared"
print(f"[START] OVERRIDE: {override_mode} for {dur_str}", flush=True)
ALL_TICKERS = sorted({s for s,_ in (TICKERS_TOP+TICKERS_BOT+(TICKERS_BOT2 or []))})
# Queues with maxsize to prevent unbounded memory growth
mq=Queue(maxsize=10); wq=Queue(maxsize=5); sbq=Queue(maxsize=20)
# Start workers with current config - we'll track them for restart
workers = {"market": None, "weather": None, "scoreboard": None}
if not DEMO_MODE:
workers["market"] = Process(target=market_worker, args=(ALL_TICKERS, REFRESH_SEC, mq, STATUS_PATH, TZINFO), daemon=True)
workers["weather"] = Process(target=weather_worker, args=(WEATHER_RSS_URL, WEATHER_INCLUDE_WATCH, WEATHER_REFRESH_SEC, WEATHER_TIMEOUT, WEATHER_FORCE_ACTIVE, WEATHER_FORCE_TEXT, wq, STATUS_PATH, TZINFO), daemon=True)
workers["market"].start(); workers["weather"].start()
print("[WORKERS] Market and Weather workers started", flush=True)
if SCOREBOARD_ENABLED:
test_cfg = {
"enabled":SCOREBOARD_TEST, "league":SCOREBOARD_TEST_LEAGUE,
"home":SCOREBOARD_TEST_HOME, "away":SCOREBOARD_TEST_AWAY,
"duration":SCOREBOARD_TEST_DURATION
}
workers["scoreboard"] = Process(target=scoreboard_worker,
args=(SCOREBOARD_LEAGUES, SCOREBOARD_NHL_TEAMS, SCOREBOARD_NFL_TEAMS,
SCOREBOARD_POLL_WINDOW_MIN, SCOREBOARD_POLL_CADENCE, SCOREBOARD_LIVE_REFRESH,
SCOREBOARD_INCLUDE_OTHERS, SCOREBOARD_ONLY_MY_TEAMS, SCOREBOARD_MAX_GAMES,
test_cfg, sbq, STATUS_PATH, TZINFO, SCOREBOARD_PREGAME_WINDOW_MIN, SCOREBOARD_POSTGAME_DELAY_MIN),
daemon=True)
workers["scoreboard"].start()
print("[SB] worker spawned", flush=True)
screen, clock = init_pygame()
print("[RGB Matrix] Initializing RGB Matrix...", flush=True)
rgb_init_success = init_rgb_matrix(
width=W,
height=H,
brightness=RGB_BRIGHTNESS,
hardware_mapping=RGB_HARDWARE_MAPPING,
gpio_slowdown=RGB_GPIO_SLOWDOWN,
pwm_bits=RGB_PWM_BITS,
pwm_lsb_nanoseconds=RGB_PWM_LSB_NANOSECONDS,
chain_length=RGB_CHAIN_LENGTH,
parallel=RGB_PARALLEL,
scan_mode=RGB_SCAN_MODE,
row_address_type=RGB_ROW_ADDRESS_TYPE,
multiplexing=RGB_MULTIPLEXING,
led_rgb_sequence=RGB_LED_RGB_SEQUENCE,
pixel_mapper=RGB_PIXEL_MAPPER,
panel_type=RGB_PANEL_TYPE
)
if not rgb_init_success:
print("[RGB Matrix] FATAL: Failed to initialize RGB Matrix", flush=True)
print("[RGB Matrix] Check that you're running as root and rpi-rgb-led-matrix is installed", flush=True)
sys.exit(1)
global font_row, font_dbg, font_sb
font_row = get_row_font()
font_dbg = get_dbg_font()
font_sb = get_sb_font()
set_fonts(font_row, font_dbg, font_sb) # Set fonts in rendering module
maint_big_font = get_maint_big_font()
preroll_big_font= get_preroll_big_font()
if override_mode == "LOGO":
logo_surf = _load_logo_surface(LOGO_PATH, H)
if MAINTENANCE_MODE and not override_active:
print("[MAINT] Maintenance active; entering maintenance loop.", flush=True)
return run_maintenance_loop(screen, clock, font_row)
# Create message surface after fonts are initialized
injector_active = bool(INJECT_MESSAGE and MESSAGE_EVERY>0)
msg_surface = None
if injector_active:
col = parse_color(MESSAGE_COLOR)
msg_surface = build_message_surface(INJECT_MESSAGE, col, font_row)
market_cache={}; market_state="UNKNOWN"; last_success_ts=0.0; last_result_ok=False
weather_active=False; weather_message=""
scoreboard_latest = {} # league -> payload
scoreboard_game_today = False # True if any watched team has a game today (all-day flag)
logo_surf = None; x_logo = float(W) # LOGO override mode state
# Full-height scoreboard state
scoreboard_flash = ScoreboardFlashState()
last_scores_fullheight = {}
last_scores = {}
alert_queue = deque(maxlen=max(1, SCORE_ALERTS_QUEUE_MAX))
alert_obj = None
alert_test_last_ts = 0.0
# Initialize ticker parts NOW (after market_cache exists but with empty cache)
# This prevents black screen on startup
single_parts, top_parts, bot_parts, bot_parts2 = [], [], [], []
try:
single_parts,_ = build_row_surfaces_from_cache(TICKERS_TOP+TICKERS_BOT, market_cache, font_row, HOLDINGS_ENABLED)
top_parts,_ = build_row_surfaces_from_cache(TICKERS_TOP, market_cache, font_row, HOLDINGS_ENABLED)
bot_parts,_ = build_row_surfaces_from_cache(TICKERS_BOT, market_cache, font_row, HOLDINGS_ENABLED)
bot_parts2,_ = build_row_surfaces_from_cache(TICKERS_BOT2, market_cache, font_row, HOLDINGS_ENABLED) if TICKERS_BOT2 else ([], False)
if PORTFOLIO_DISPLAY_ENABLED:
_port = build_portfolio_parts(market_cache, HOLDINGS, PORTFOLIO_LABEL)
if _port:
top_parts = _port + top_parts
single_parts = _port + single_parts
if BOT_GROUP1_ENABLED and HOLDINGS:
_h1 = {p[0]: HOLDINGS[p[0]] for p in TICKERS_BOT if p and p[0] in HOLDINGS}
if _h1:
_g1 = build_portfolio_parts(market_cache, _h1, BOT_GROUP1_LABEL)
if _g1: bot_parts = _g1 + bot_parts
if TICKERS_BOT2 and BOT_GROUP2_ENABLED and HOLDINGS:
_h2 = {p[0]: HOLDINGS[p[0]] for p in TICKERS_BOT2 if p and p[0] in HOLDINGS}
if _h2:
_g2 = build_portfolio_parts(market_cache, _h2, BOT_GROUP2_LABEL)
if _g2: bot_parts2 = _g2 + bot_parts2
print(f"[INIT] Built initial ticker parts: {len(single_parts)} single, {len(top_parts)} top, {len(bot_parts)} bot, {len(bot_parts2)} bot2", flush=True)
except Exception as e:
print(f"[INIT] Failed to build initial ticker parts: {e}", flush=True)
# RGB Matrix error tracking (suppress repeated errors)
shm_last_error = None
shm_error_count = 0
shm_last_error_print = 0.0
shm_write_success = False # Track first successful write
# --- Weather banner state machine (sticky / re-announce) ---
weather_banner = {
"active": False, # last-known active flag from worker or test
"message": "", # last headline
"severity": "", # severity level (warning, advisory, watch)
"next_repeat_at": 0.0, # earliest time allowed to re-pin while still active
"test_forced_until": 0.0 # when in test harness, how long we pretend it's still active
}
def poll_queues_nonblock():
"""Non-blocking drain of worker queues into local caches."""
nonlocal market_cache, market_state, last_success_ts, last_result_ok
nonlocal weather_active, weather_message
nonlocal scoreboard_latest, scoreboard_game_today, weather_banner
if not DEMO_MODE:
try:
while True:
msg = mq.get_nowait()
if msg.get("type")=="market":
payload = msg["payload"]
market_cache = payload.get("data",{}) or {}
market_state = (payload.get("market_state") or "UNKNOWN").upper()
if payload.get("ok_any", False):
last_success_ts = payload.get("ts", time.time()); last_result_ok=True
else:
last_result_ok=False
except queue_std.Empty: pass
try:
while True:
msg = wq.get_nowait()
if msg.get("type")=="weather":
payload = msg["payload"]
weather_active = bool(payload.get("active",False))
weather_message = payload.get("message","") or ""
weather_severity = payload.get("severity","") or ""
# Sticky pin logic driven by worker cadence
now = time.time()
new_msg = (weather_message or "").strip()
if weather_active:
if (not weather_banner["active"]) or (new_msg and new_msg != weather_banner["message"]):
weather_banner["active"] = True
weather_banner["message"] = new_msg or "Weather alert"
weather_banner["severity"] = weather_severity
else:
weather_banner["active"] = False
except queue_std.Empty: pass
if SCOREBOARD_ENABLED:
try:
while True:
msg = sbq.get_nowait()
if msg.get("type")=="scoreboard":
payload = msg["payload"]; league=(payload.get("league") or "").upper()
if league: