-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_ui.py
More file actions
1580 lines (1494 loc) · 80.5 KB
/
Copy pathflask_ui.py
File metadata and controls
1580 lines (1494 loc) · 80.5 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
# -*- coding: utf-8 -*-
# Property of solutions reseaux chromatel
"""
LED Ticker - Control Panel (with Live Preview)
==============================================
This Flask UI edits `config.json`, provides temporary overrides, and exposes
a Live Preview of the current display when the ticker is running.
Notes
-----
- Preview works by reading preview frames from /tmp/ticker_preview.png
- Ticker saves preview snapshots every 10th frame (~3 FPS at 30 FPS render rate)
- If Pillow (PIL) is not installed, the preview endpoint will explain how to
install it in your venv: `pip install pillow`.
Environment (optional)
----------------------
TICKER_RESTART_CMD - Full shell command to restart the ticker (wins over systemd)
TICKER_SERVICE - systemd service name (default: led-ticker.service)
TICKER_USE_SUDO - "1" to use sudo for systemctl if not running as root (default 1)
FLASK_SECRET - Secret key; set this in production
FLASK_PORT - Listening port (default 5080)
"""
import os
import io
import json
import time
import tempfile
import html
import shutil
import subprocess
from threading import Lock
from flask import (
Flask, request, redirect, url_for, render_template_string,
jsonify, flash, Response, send_from_directory
)
# Optional Pillow for PNG encoding of SHM frames
try:
from PIL import Image
_PIL_OK = True
except Exception:
Image = None
_PIL_OK = False
APP_TITLE = "LED Ticker - Control Panel"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.environ.get("TICKER_CONFIG", os.path.join(BASE_DIR, "config.json"))
# Restart configuration (optional environment variables)
RESTART_CMD_ENV = os.environ.get("TICKER_RESTART_CMD", "").strip()
SYSTEMD_SERVICE = os.environ.get("TICKER_SERVICE", "led-ticker.service").strip()
USE_SUDO_DEFAULT = os.environ.get("TICKER_USE_SUDO", "1") == "1"
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.secret_key = os.environ.get("FLASK_SECRET", "dev-secret") # change in prod
_write_lock = Lock()
@app.after_request
def add_header(response):
if 'Content-Type' in response.headers:
if 'charset' not in response.headers['Content-Type']:
if 'text/html' in response.headers['Content-Type']:
response.headers['Content-Type'] = 'text/html; charset=utf-8'
elif 'application/json' in response.headers['Content-Type']:
response.headers['Content-Type'] = 'application/json; charset=utf-8'
return response
# ---------------------------- helpers ---------------------------------
def load_cfg():
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def atomic_save_cfg(cfg: dict):
"""Atomic write of config.json with a lock."""
with _write_lock:
dname = os.path.dirname(CONFIG_PATH) or "."
fd, tmp = tempfile.mkstemp(prefix=".cfg.", dir=dname)
os.close(fd)
try:
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
json.dump(cfg, f, indent=2, ensure_ascii=False)
os.replace(tmp, CONFIG_PATH)
finally:
try:
os.remove(tmp)
except Exception:
pass
def _parse_lines_pairs(txt: str):
"""
Parse textarea content formatted as pairs:
SYMBOL on one line, LABEL on the next line, repeated.
Returns [["SYM", "LABEL"], ...]
"""
out = []
lines = (txt or "").splitlines()
i = 0
while i < len(lines):
sym = (lines[i] or "").strip()
lab = (lines[i + 1] if i + 1 < len(lines) else "").strip()
if sym and lab:
out.append([sym, lab])
i += 2
return out
def _pairs_to_text(pairs):
return "\n".join([f"{s[0]}\n{s[1]}" for s in (pairs or [])])
def _parse_holdings(txt: str):
"""
Parse "SYMBOL=SHARES" per-line to {"SYM":{"shares":float}}
"""
out = {}
for line in (txt or "").splitlines():
line = line.strip()
if not line or "=" not in line:
continue
sym, sh = line.split("=", 1)
sym = sym.strip()
try:
shares = float(sh.strip())
if shares >= 0:
out[sym] = {"shares": shares}
except Exception:
pass
return out
def _holdings_to_text(hold):
lines = []
for k, v in (hold or {}).items():
try:
lines.append(f"{k}={v.get('shares',0)}")
except Exception:
pass
return "\n".join(lines)
def _get_bool(form, name, default=False):
v = form.get(name, None)
if v in ("1", "true", "on", "True", "YES", "yes", "y"):
return True
if v in ("0", "false", "off", "False", "", None, "no", "NO", "n"):
return False
return bool(default)
def _get_num(form, name, default=0, cast=float):
try:
raw = form.get(name, None)
if raw is None or raw == "":
return default
return cast(raw)
except Exception:
return default
def _get_csv_upper(form, name, default_list=None):
raw = (form.get(name, "") or "").strip()
if not raw and default_list is not None:
return default_list
return [s.strip().upper() for s in raw.split(",") if s.strip()]
# ---------------------------- restart helper ---------------------------
def _run_restart_command():
"""
Try to restart the ticker:
1) Use TICKER_RESTART_CMD if provided
2) Else try systemctl restart <SERVICE> (optionally with sudo)
Returns (ok, message)
"""
if RESTART_CMD_ENV:
try:
proc = subprocess.run(
RESTART_CMD_ENV,
shell=True,
capture_output=True,
text=True,
timeout=30,
)
if proc.returncode == 0:
return True, "Restarted via custom command."
return False, f"Custom restart failed (rc={proc.returncode}): {proc.stderr.strip() or proc.stdout.strip()}"
except Exception as e:
return False, f"Custom restart error: {e}"
if not shutil.which("systemctl"):
return False, "systemctl not found and no TICKER_RESTART_CMD provided."
use_sudo = USE_SUDO_DEFAULT and (os.geteuid() != 0)
cmd = ["systemctl", "restart", SYSTEMD_SERVICE]
if use_sudo:
if not shutil.which("sudo"):
return False, "sudo not found; set TICKER_RESTART_CMD or run UI as root."
cmd = ["sudo"] + cmd
try:
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if proc.returncode == 0:
return True, f"systemd restart ok: {SYSTEMD_SERVICE}"
err = proc.stderr.strip() or proc.stdout.strip()
return False, f"systemd restart failed (rc={proc.returncode}): {err}"
except Exception as e:
return False, f"systemd restart error: {e}"
# ---------------------------- preview helpers --------------------------
def _resolve_panel_size_from_model(model_name: str):
mn = (model_name or "").lower()
if "96x32" in mn:
return 96, 32
if "192x16" in mn:
return 192, 16
if "96x16" in mn:
return 96, 16
return 96, 16
def _derive_panel_WH(cfg: dict):
try:
w = int(cfg.get("W", 0) or 0)
h = int(cfg.get("H", 0) or 0)
except Exception:
w = h = 0
if w > 0 and h > 0:
return w, h
m = cfg.get("MODEL_NAME", "Matrix96x16")
return _resolve_panel_size_from_model(m)
def _read_preview_png_bytes(cfg: dict, scale: int = 6) -> tuple:
"""
Return (ok, bytes_or_message, mime):
- On success: (True, PNG_bytes, 'image/png')
- On error: (False, error_message, 'text/plain')
Reads from /tmp/ticker_preview.png (written by ticker in RGBMATRIX mode).
"""
if not _PIL_OK:
return False, (
"Pillow (PIL) is not installed. Install it in your venv to enable preview:\n"
" pip install pillow\n"
), "text/plain"
preview_path = "/tmp/ticker_preview.png"
if not os.path.exists(preview_path):
return False, f"Preview file not found: {preview_path}\nEnsure the ticker is running.", "text/plain"
try:
img = Image.open(preview_path)
if scale > 1:
new_size = (img.width * scale, img.height * scale)
img = img.resize(new_size, Image.NEAREST)
buf = io.BytesIO()
img.save(buf, format="PNG")
return True, buf.getvalue(), "image/png"
except Exception as e:
return False, f"Error reading preview: {e}", "text/plain"
# ---------------------------- templates --------------------------------
BASE_CSS = """
<style>
:root{
--bg:#0b0f16; --panel:#0f1724; --line:#1c2434; --text:#e6e6e6; --muted:#a7b1c2;
--blue:#2563eb; --btn:#2563eb; --btn2:#334155; --link:#93c5fd; --ok:#16a34a; --bad:#dc2626;
}
*{box-sizing:border-box}
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Arial,sans-serif;margin:0;background:var(--bg);color:var(--text)}
header{padding:12px 16px;background:var(--panel);border-bottom:1px solid var(--line);display:flex;gap:8px;align-items:center}
h1{font-size:18px;margin:0}
main{padding:16px;max-width:1200px;margin:0 auto}
section{margin:18px 0;padding:12px;border:1px solid var(--line);border-radius:8px;background:var(--panel)}
label{display:block;margin:8px 0 4px;color:var(--muted)}
input,select,textarea{width:100%;padding:8px;background:var(--bg);border:1px solid #273046;color:var(--text);border-radius:6px}
.row{display:flex;gap:12px;flex-wrap:wrap}
.col{flex:1;min-width:260px}
.grid2{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
.grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
.grid4{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}
button{background:var(--btn);color:white;border:none;padding:8px 12px;border-radius:6px;cursor:pointer}
button.secondary{background:var(--btn2)}
.btn{display:inline-block;background:var(--btn);color:white;padding:8px 12px;border-radius:6px;text-decoration:none}
.btn.secondary{background:var(--btn2)}
.pill{display:inline-block;padding:2px 8px;border-radius:999px;background:#1e293b;border:1px solid #334155;font-size:12px}
.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}
a{color:var(--link);text-decoration:none}
.toolbar{display:flex;gap:8px;align-items:center;margin-left:auto}
.muted{color:var(--muted)}
details{border:1px dashed var(--line);padding:8px;border-radius:8px}
summary{cursor:pointer;color:#cbd5e1}
.ok{color:var(--ok)} .bad{color:var(--bad)}
.preview-wrap{display:flex;gap:16px;align-items:flex-start;flex-wrap:wrap}
.preview-card{background:#0b1322;border:1px solid #233047;border-radius:10px;padding:8px}
.preview-meta{font-size:12px;color:#9fb0c7;margin-top:6px}
.hint{font-size:13px;color:#9fb0c7}
</style>
"""
HOME_HTML = """
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{title}}</title>
""" + BASE_CSS + """
</head><body>
<header>
<h1>{{title}}</h1>
<span class="pill mono">config.json</span>
<span class="pill mono">hot-reload</span>
<div class="toolbar">
<a class="btn" href="{{ url_for('preview_page') }}">Live Preview</a>
<a class="btn secondary" href="{{ url_for('override_page') }}">Overrides</a>
<a class="btn secondary" href="{{ url_for('documentation') }}">Documentation</a>
<a class="btn secondary" href="{{ url_for('raw_editor') }}">Raw JSON Editor</a>
<button class="secondary" type="button" onclick="fetch('/restart',{method:'POST'}).then(()=>location.reload())" title="Restart the ticker process/service">Restart Ticker</button>
</div>
</header>
<main>
{% with msgs = get_flashed_messages() %}
{% if msgs %}
<section>
{% for m in msgs %}
<div>{{m}}</div>
{% endfor %}
</section>
{% endif %}
{% endwith %}
<section>
<h2>Quick Preview</h2>
<div class="preview-wrap">
<div class="preview-card">
<img id="qprev" src="{{ url_for('preview_png') }}?scale={{scale}}&t={{nowts}}" alt="preview" style="image-rendering:pixelated;max-width:100%;height:auto">
<div class="preview-meta mono">{{wh}} scale={{scale}} {{preview_status}}</div>
</div>
<div class="hint">If the image doesn't move: ensure the ticker is running and Pillow is installed in the UI's venv.<br>
For a larger view and controls, open <a href="{{ url_for('preview_page') }}">Live Preview</a>.</div>
</div>
</section>
<form method="post" action="{{ url_for('save') }}">
<!-- Status & Quick Actions -->
<div style="background:#1a1f2e;padding:16px;margin-bottom:20px;border-radius:8px;border:1px solid #2c3650;">
<div style="display:flex;gap:24px;align-items:flex-start;flex-wrap:wrap;">
<div>
<div style="font-size:11px;color:#7d8ba8;margin-bottom:4px;">SERVICE STATUS</div>
<div id="service-status" style="font-weight:600;"><span style="color:#888;">Checking...</span></div>
</div>
<div style="flex:1;">
<div style="font-size:11px;color:#7d8ba8;margin-bottom:4px;">QUICK ACTIONS</div>
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px;">
<button type="submit" class="btn" style="padding:6px 12px;font-size:13px;">Save Config</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/restart',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),2000);})"> Restart</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/stop-service',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> Stop</button>
</div>
<div style="font-size:11px;color:#7d8ba8;margin-bottom:4px;margin-top:12px;">OVERRIDES</div>
<div style="display:flex;gap:8px;flex-wrap:wrap;">
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/show-clock',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> Clock 5m</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/bright-mode',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> Full Bright 30m</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/bright-30',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> 30% Bright</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/bright-60',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> 60% Bright</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/bright-100',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> 100% Bright</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/scoreboard-mode',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> Force Scoreboard</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/maint-mode',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> Maintenance</button>
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="fetch('/action/clear-override',{method:'POST'}).then(()=>{setTimeout(()=>location.reload(),1000);})"> Clear Override</button>
</div>
<div style="margin-top:8px;display:flex;gap:8px;align-items:center;">
<input type="text" id="msg-input" placeholder="Custom message..." style="flex:1;padding:6px 10px;font-size:13px;max-width:300px;">
<button type="button" class="btn secondary" style="padding:6px 12px;font-size:13px;" onclick="var msg=document.getElementById('msg-input').value.trim();if(msg){var fd=new FormData();fd.append('message',msg);fetch('/action/show-message',{method:'POST',body:fd}).then(()=>{document.getElementById('msg-input').value='';setTimeout(()=>location.reload(),1000);});}else{alert('Enter a message first');}"> Show Message 5m</button>
</div>
</div>
</div>
</div>
<!-- Worker Status Monitoring -->
<div style="background:#1a1f2e;padding:16px;margin-bottom:20px;border-radius:8px;border:1px solid #2c3650;">
<div style="font-size:11px;color:#7d8ba8;margin-bottom:8px;">WORKER STATUS</div>
<div id="worker-status" style="font-size:13px;">
<span style="color:#888;">Loading...</span>
</div>
</div>
<script>
function updateStatus(){
fetch('/api/status').then(r=>r.json()).then(d=>{
document.getElementById('service-status').innerHTML = d.service_running ?
'<span style="color:#16a34a;">OK Running</span>' : '<span style="color:#dc2626;">WARN Stopped</span>';
}).catch(()=>{});
}
function updateWorkers(){
fetch('/api/workers').then(r=>r.json()).then(d=>{
const workers = d.workers || {};
if (!d.file_exists) {
document.getElementById('worker-status').innerHTML = `
<div style="background:#0f1419;padding:16px;border-radius:6px;border:1px solid #fbbf24;">
<div style="color:#fbbf24;font-weight:600;margin-bottom:8px;">WARN Worker Status Not Available</div>
<div style="font-size:13px;color:#9ca3af;line-height:1.6;">
<p style="margin:0 0 8px 0;">The worker status file <code style="color:#e5e7eb;background:#1a1f2e;padding:2px 6px;border-radius:3px;">ticker_status.json</code> doesn't exist yet.</p>
<p style="margin:0;"><strong style="color:#e5e7eb;">To enable monitoring:</strong></p>
<ol style="margin:8px 0 0 20px;padding:0;">
<li>Deploy the updated <code style="color:#e5e7eb;background:#1a1f2e;padding:2px 6px;border-radius:3px;">ticker.py</code> file</li>
<li>Restart the LED ticker service</li>
<li>Wait 30-60 seconds for workers to run</li>
<li>This page will auto-refresh and show live data</li>
</ol>
</div>
</div>`;
return;
}
if (Object.keys(workers).length === 0) {
document.getElementById('worker-status').innerHTML = '<span style="color:#888;">No worker data available</span>';
return;
}
let html = '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px;">';
// Market Worker
if (workers.market) {
const m = workers.market;
const isStale = (m.seconds_ago||0) > 600;
const hasError = (m.status === 'error' || m.status === 'partial');
const statusColor = hasError ? '#dc2626' : (m.status === 'ok' ? (isStale ? '#fbbf24' : '#16a34a') : '#fbbf24');
let statusText = (m.status ? m.status.toUpperCase() : 'UNKNOWN');
if (m.symbols_failed && m.symbols_failed > 0) { statusText += ` (${m.symbols_failed} failed)`; }
let errorHtml = '';
if (m.error_message) { errorHtml = `<div style="color:#dc2626;margin-top:4px;">WARN ${m.error_message}</div>`; }
html += `<div style="background:#0f1419;padding:12px;border-radius:6px;border:1px solid #2c3650;">
<div style="font-weight:600;margin-bottom:6px;color:${statusColor};">Market Worker</div>
<div style="font-size:12px;color:#9ca3af;">
<div>Status: <span style="color:${statusColor};">${statusText}</span></div>
<div>Market State: <span style="color:#e5e7eb;">${m.market_state||'UNKNOWN'}</span></div>
<div>Symbols: <span style="color:#e5e7eb;">${m.symbols_count||0}</span></div>
<div>Last Update: <span style="color:#e5e7eb;">${m.last_update||'Never'}</span></div>
<div>Fetch Time: <span style="color:#e5e7eb;">${m.fetch_duration_sec||0}s</span></div>
<div style="color:${isStale ? '#fbbf24' : '#9ca3af'};">Updated ${m.seconds_ago||0}s ago</div>
${errorHtml}
</div>
</div>`;
}
// Scoreboard Worker
if (workers.scoreboard) {
const s = workers.scoreboard;
const isStale = (s.seconds_ago||0) > 600;
const hasError = (s.status === 'error');
const statusColor = hasError ? '#dc2626' : (s.status === 'live' ? '#16a34a' : (s.status === 'ok' ? '#3b82f6' : '#9ca3af'));
let leagueInfo = '';
if (s.leagues_with_games && s.leagues_with_games.length > 0) {
const leagues = s.leagues_with_games.map(l => {
const parts = String(l).split(':');
return `${parts[0]} (${parts[1]||0})`;
}).join(', ');
leagueInfo = `<div>Today: <span style="color:#e5e7eb;">${leagues}</span></div>`;
} else {
const gameTodayColor = s.game_today ? '#3b82f6' : '#9ca3af';
leagueInfo = `<div>Today: <span style="color:${gameTodayColor};">${s.game_today ? 'Game scheduled (outside window)' : 'No games'}</span></div>`;
}
let errorHtml = '';
if (s.error_message) { errorHtml = `<div style="color:#dc2626;margin-top:4px;">WARN ${s.error_message}</div>`; }
html += `<div style="background:#0f1419;padding:12px;border-radius:6px;border:1px solid #2c3650;">
<div style="font-weight:600;margin-bottom:6px;color:${statusColor};">Scoreboard Worker</div>
<div style="font-size:12px;color:#9ca3af;">
<div>Status: <span style="color:${statusColor};">${(s.status||'UNKNOWN').toUpperCase()}</span></div>
${leagueInfo}
<div>Total Games: <span style="color:#e5e7eb;">${s.total_games||0}</span></div>
<div>Live: <span style=\"color:#16a34a;\">${s.live_games||0}</span> Scheduled: <span style=\"color:#3b82f6;\">${s.pregame_games||0}</span></div>
<div>Test Mode: <span style="color:#e5e7eb;">${s.test_mode ? 'Yes' : 'No'}</span></div>
<div>Last Update: <span style="color:#e5e7eb;">${s.last_update||'Never'}</span></div>
<div style="color:${isStale ? '#fbbf24' : '#9ca3af'};">Updated ${s.seconds_ago||0}s ago</div>
${errorHtml}
</div>
</div>`;
}
// Weather Worker
if (workers.weather) {
const w = workers.weather;
const isStale = (w.seconds_ago||0) > 600;
const hasError = (w.status === 'error');
const statusColor = hasError ? '#dc2626' : (w.status === 'active' ? '#dc2626' : '#16a34a');
let errorHtml = '';
if (w.error_message) { errorHtml = `<div style="color:#dc2626;margin-top:4px;">WARN ${w.error_message}</div>`; }
html += `<div style="background:#0f1419;padding:12px;border-radius:6px;border:1px solid #2c3650;">
<div style="font-weight:600;margin-bottom:6px;color:${statusColor};">Weather Worker</div>
<div style="font-size:12px;color:#9ca3af;">
<div>Status: <span style="color:${statusColor};">${(w.status||'UNKNOWN').toUpperCase()}</span></div>
<div>Severity: <span style="color:#e5e7eb;">${w.severity||'none'}</span></div>
<div>Last Update: <span style="color:#e5e7eb;">${w.last_update||'Never'}</span></div>
<div>Fetch Time: <span style="color:#e5e7eb;">${w.fetch_duration_sec||0}s</span></div>
<div style="color:${isStale ? '#fbbf24' : '#9ca3af'};">Updated ${w.seconds_ago||0}s ago</div>
${errorHtml}
</div>
</div>`;
}
html += '</div>';
document.getElementById('worker-status').innerHTML = html;
}).catch(()=>{
document.getElementById('worker-status').innerHTML = '<span style="color:#dc2626;">Error loading worker status</span>';
});
}
updateStatus();
updateWorkers();
setInterval(updateStatus,5000);
setInterval(updateWorkers,3000);
</script>
<section>
<h2>Display & Layout</h2>
<div class="grid3">
<div><label>Layout</label>
<select name="LAYOUT">
{% for opt in ["","single","dual"] %}
<option value="{{opt}}" {% if cfg.LAYOUT==opt %}selected{% endif %}>{{opt if opt else "auto"}}</option>
{% endfor %}
</select>
</div>
<div><label>Timezone (IANA)</label><input name="TICKER_TZ" value="{{cfg.TICKER_TZ or ''}}"></div>
<div><label>Microfont (dual-row only)</label>
<select name="MICROFONT_ENABLED">
<option value="1" {% if cfg.MICROFONT_ENABLED %}selected{% endif %}>on</option>
<option value="0" {% if not cfg.MICROFONT_ENABLED %}selected{% endif %}>off</option>
</select>
</div>
</div>
<div class="grid4" style="margin-top:8px">
<div><label>FPS</label><input name="FPS" type="number" min="1" max="120" value="{{cfg.FPS or 30}}"></div>
<div><label>Top PPS</label><input name="PPS_TOP" type="number" step="0.5" value="{{cfg.PPS_TOP or 16.0}}"></div>
<div><label>Bottom PPS</label><input name="PPS_BOT" type="number" step="0.5" value="{{cfg.PPS_BOT or 20.0}}"></div>
<div><label>Single PPS</label><input name="PPS_SINGLE" type="number" step="0.5" value="{{cfg.PPS_SINGLE or 20.0}}"></div>
</div>
<div class="grid2" style="margin-top:8px">
<div><label>Width (W)</label><input name="W" type="number" value="{{cfg.W or 0}}"></div>
<div><label>Height (H)</label><input name="H" type="number" value="{{cfg.H or 0}}"></div>
</div>
<h3 style="margin-top:16px;font-size:15px;color:#94a3b8;">RGB Matrix Hardware (RGBMATRIX mode only)</h3>
<p class="muted">These settings configure the rpi-rgb-led-matrix library for direct HUB75 LED panel control.</p>
<div class="grid4" style="margin-top:8px">
<div>
<label>Hardware Mapping</label>
<select name="RGB_HARDWARE_MAPPING" title="GPIO pin layout for your HAT/adapter">
<option value="adafruit-hat" {% if (cfg.RGB_HARDWARE_MAPPING or 'adafruit-hat') == 'adafruit-hat' %}selected{% endif %}>adafruit-hat</option>
<option value="adafruit-hat-pwm" {% if (cfg.RGB_HARDWARE_MAPPING or 'adafruit-hat') == 'adafruit-hat-pwm' %}selected{% endif %}>adafruit-hat-pwm</option>
<option value="regular" {% if (cfg.RGB_HARDWARE_MAPPING or 'adafruit-hat') == 'regular' %}selected{% endif %}>regular</option>
<option value="regular-pi1" {% if (cfg.RGB_HARDWARE_MAPPING or 'adafruit-hat') == 'regular-pi1' %}selected{% endif %}>regular-pi1</option>
<option value="classic" {% if (cfg.RGB_HARDWARE_MAPPING or 'adafruit-hat') == 'classic' %}selected{% endif %}>classic</option>
<option value="classic-pi1" {% if (cfg.RGB_HARDWARE_MAPPING or 'adafruit-hat') == 'classic-pi1' %}selected{% endif %}>classic-pi1</option>
</select>
</div>
<div>
<label>Brightness (0-100)</label>
<input name="RGB_BRIGHTNESS" type="number" min="0" max="100" value="{{cfg.RGB_BRIGHTNESS or 100}}" title="LED brightness percentage">
</div>
<div>
<label>GPIO Slowdown (0-4)</label>
<input name="RGB_GPIO_SLOWDOWN" type="number" min="0" max="4" value="{{cfg.RGB_GPIO_SLOWDOWN or 4}}" title="Stability setting, higher for faster Pi models">
</div>
<div>
<label>PWM Bits (1-11)</label>
<input name="RGB_PWM_BITS" type="number" min="1" max="11" value="{{cfg.RGB_PWM_BITS or 11}}" title="Color depth, higher = more colors but slower refresh">
</div>
</div>
<div class="grid4" style="margin-top:8px">
<div>
<label>PWM LSB Nanoseconds (50-3000)</label>
<input name="RGB_PWM_LSB_NANOSECONDS" type="number" min="50" max="3000" step="10" value="{{cfg.RGB_PWM_LSB_NANOSECONDS or 130}}" title="PWM timing, affects brightness/flicker tradeoff">
</div>
</div>
<h3 style="margin-top:16px;font-size:15px;color:#94a3b8;">Advanced Panel Configuration</h3>
<p class="muted">For chained panels, special panel types, and advanced configurations. Leave at defaults for single standard panels.</p>
<div class="grid4" style="margin-top:8px">
<div>
<label>Chain Length</label>
<input name="RGB_CHAIN_LENGTH" type="number" min="1" max="32" value="{{cfg.RGB_CHAIN_LENGTH or 1}}" title="Number of panels chained horizontally">
</div>
<div>
<label>Parallel Chains</label>
<input name="RGB_PARALLEL" type="number" min="1" max="8" value="{{cfg.RGB_PARALLEL or 1}}" title="Number of parallel chains (increases height)">
</div>
<div>
<label>Scan Mode</label>
<select name="RGB_SCAN_MODE" title="Scan pattern for the panel">
<option value="0" {% if (cfg.RGB_SCAN_MODE or 0) == 0 %}selected{% endif %}>0 - Progressive</option>
<option value="1" {% if (cfg.RGB_SCAN_MODE or 0) == 1 %}selected{% endif %}>1 - Interlaced</option>
</select>
</div>
<div>
<label>Row Address Type (0-4)</label>
<input name="RGB_ROW_ADDRESS_TYPE" type="number" min="0" max="4" value="{{cfg.RGB_ROW_ADDRESS_TYPE or 0}}" title="0=direct, 1=AB, 2=direct-ABCDline, 3=ABC-shift, 4=ABC-ZigZag">
</div>
</div>
<div class="grid4" style="margin-top:8px">
<div>
<label>Multiplexing (0-18)</label>
<input name="RGB_MULTIPLEXING" type="number" min="0" max="18" value="{{cfg.RGB_MULTIPLEXING or 0}}" title="Panel-specific multiplexing type, usually 0">
</div>
<div>
<label>LED RGB Sequence</label>
<select name="RGB_LED_RGB_SEQUENCE" title="Physical LED color order">
{% for seq in ['RGB','RBG','GRB','GBR','BRG','BGR'] %}
<option value="{{seq}}" {% if (cfg.RGB_LED_RGB_SEQUENCE or 'RGB') == seq %}selected{% endif %}>{{seq}}</option>
{% endfor %}
</select>
</div>
<div>
<label>Pixel Mapper</label>
<input name="RGB_PIXEL_MAPPER" value="{{cfg.RGB_PIXEL_MAPPER or ''}}" placeholder="e.g. Rotate:90" title="Optional: Rotate:90, U-mapper, etc.">
</div>
<div>
<label>Panel Type</label>
<input name="RGB_PANEL_TYPE" value="{{cfg.RGB_PANEL_TYPE or ''}}" placeholder="Usually empty" title="Panel type hint for special panels">
</div>
</div>
</section>
<section>
<h2>Time Preroll (Top of Hour)</h2>
<p class="muted">Show a time display at the top of each hour for a configurable duration.</p>
<div class="grid4" style="margin-top:8px">
<label style="grid-column: span 4;"><input type="checkbox" name="TIME_PREROLL_ENABLED" value="1" {% if cfg.TIME_PREROLL_ENABLED %}checked{% endif %}> Enable Time Preroll</label>
</div>
<div class="grid4" style="margin-top:8px">
<div>
<label>Duration (seconds)</label>
<input name="TIME_PREROLL_SEC" type="number" min="1" max="120" value="{{cfg.TIME_PREROLL_SEC or 15}}" title="How long to show the preroll (1-120 seconds)">
</div>
<div>
<label>Style</label>
<select name="PREROLL_STYLE" title="Display style for preroll">
<option value="bigtime" {% if (cfg.PREROLL_STYLE or 'bigtime').lower() == 'bigtime' %}selected{% endif %}>Big Time (Static)</option>
<option value="marquee" {% if (cfg.PREROLL_STYLE or 'bigtime').lower() == 'marquee' %}selected{% endif %}>Marquee (Scrolling)</option>
<option value="market_announce" {% if (cfg.PREROLL_STYLE or 'bigtime').lower() == 'market_announce' %}selected{% endif %}>Market Announcement</option>
</select>
</div>
<div>
<label>Color</label>
<select name="PREROLL_COLOR" title="Color for time display">
<option value="white" {% if (cfg.PREROLL_COLOR or 'yellow') == 'white' %}selected{% endif %}>White</option>
<option value="yellow" {% if (cfg.PREROLL_COLOR or 'yellow') == 'yellow' %}selected{% endif %}>Yellow</option>
<option value="green" {% if (cfg.PREROLL_COLOR or 'yellow') == 'green' %}selected{% endif %}>Green</option>
<option value="red" {% if (cfg.PREROLL_COLOR or 'yellow') == 'red' %}selected{% endif %}>Red</option>
<option value="blue" {% if (cfg.PREROLL_COLOR or 'yellow') == 'blue' %}selected{% endif %}>Blue</option>
<option value="magenta" {% if (cfg.PREROLL_COLOR or 'yellow') == 'magenta' %}selected{% endif %}>Magenta</option>
<option value="cyan" {% if (cfg.PREROLL_COLOR or 'yellow') == 'cyan' %}selected{% endif %}>Cyan</option>
</select>
</div>
<div>
<label>Scroll Speed (PPS)</label>
<input name="PREROLL_PPS" type="number" step="0.5" min="10" max="100" value="{{cfg.PREROLL_PPS or 40.0}}" title="Pixels per second for marquee style">
</div>
</div>
</section>
<section>
<h2>Tickers (Top / Bottom / Alt Bottom)</h2>
<p class="muted">Format: <span class="mono">SYMBOL\nLABEL</span> one per line. Alt Bottom alternates with Bottom every other scroll.</p>
<div class="row">
<div class="col">
<label>Top Row</label>
<textarea name="TICKERS_TOP" rows="7">{{top_pairs}}</textarea>
</div>
<div class="col">
<label>Bottom Row</label>
<textarea name="TICKERS_BOT" rows="7">{{bot_pairs}}</textarea>
</div>
<div class="col">
<label>Alt Bottom Row (every other scroll)</label>
<textarea name="TICKERS_BOT2" rows="7">{{bot_pairs2}}</textarea>
</div>
</div>
<div class="grid3" style="margin-top:8px">
<div><label>Market Refresh (sec)</label><input name="REFRESH_SEC" type="number" value="{{cfg.REFRESH_SEC or 240}}"></div>
<div><label>Freshness Threshold (sec)</label><input name="FRESH_SEC" type="number" value="{{cfg.FRESH_SEC or 300}}"></div>
</div>
</section>
<section>
<h2>Holdings</h2>
<p class="muted">Format: <span class="mono">SYMBOL=SHARES</span> one per line (fractions OK).</p>
<label><input type="checkbox" name="HOLDINGS_ENABLED" value="1" {% if cfg.HOLDINGS_ENABLED %}checked{% endif %}> Enable holdings view (show value per ticker)</label>
<textarea name="HOLDINGS" rows="8">{{holdings_text}}</textarea>
<hr style="border:none;border-top:1px solid #1c2434;margin:12px 0">
<p class="muted">Row summaries — each prepends a labelled total to its scroll row. All totals use symbols from the row that have entries in Holdings above.</p>
<div class="grid3" style="margin-top:8px">
<div>
<label><input type="checkbox" name="PORTFOLIO_DISPLAY_ENABLED" value="1" {% if cfg.PORTFOLIO_DISPLAY_ENABLED %}checked{% endif %}> Show total on top row (TICKERS_TOP + all Holdings)</label>
<input name="PORTFOLIO_LABEL" maxlength="8" value="{{cfg.PORTFOLIO_LABEL or 'MY'}}" style="margin-top:4px;width:120px" placeholder="Label (max 8)">
</div>
<div>
<label><input type="checkbox" name="BOT_GROUP1_ENABLED" value="1" {% if cfg.BOT_GROUP1_ENABLED %}checked{% endif %}> Show group 1 total (bottom row 1 / TICKERS_BOT)</label>
<input name="BOT_GROUP1_LABEL" maxlength="8" value="{{cfg.BOT_GROUP1_LABEL or 'TFSA'}}" style="margin-top:4px;width:120px" placeholder="Label (max 8)">
</div>
<div>
<label><input type="checkbox" name="BOT_GROUP2_ENABLED" value="1" {% if cfg.BOT_GROUP2_ENABLED %}checked{% endif %}> Show group 2 total (bottom row 2 / TICKERS_BOT2)</label>
<input name="BOT_GROUP2_LABEL" maxlength="8" value="{{cfg.BOT_GROUP2_LABEL or 'RRSP'}}" style="margin-top:4px;width:120px" placeholder="Label (max 8)">
</div>
</div>
</section>
<section>
<h2>Message & Weather</h2>
<div class="grid3">
<div><label>Inject Message</label><input name="INJECT_MESSAGE" value="{{cfg.INJECT_MESSAGE or ''}}"></div>
<div><label>Message Every N Scrolls (0=off)</label><input name="MESSAGE_EVERY" type="number" min="0" value="{{cfg.MESSAGE_EVERY or 0}}"></div>
<div><label>Message Row</label>
<select name="MESSAGE_ROW">
{% for opt in ["auto","single","top","bottom","both","off"] %}
<option value="{{opt}}" {% if cfg.MESSAGE_ROW==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="grid3" style="margin-top:8px">
<div><label>Message Color</label>
<select name="MESSAGE_COLOR">
{% for opt in ["yellow","white","red","green","cyan","blue","magenta","orange","grey","black"] %}
<option value="{{opt}}" {% if cfg.MESSAGE_COLOR==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
<label><input type="checkbox" name="MESSAGE_TEST_FORCE" value="1" {% if cfg.MESSAGE_TEST_FORCE %}checked{% endif %}> Force message every scroll (test)</label>
</div>
<hr style="border:none;border-top:1px solid #1c2434;margin:14px 0">
<div class="grid2" style="margin-top:8px">
<div><label>Weather RSS URL</label><input name="WEATHER_RSS_URL" value="{{cfg.WEATHER_RSS_URL or ''}}"></div>
<div><label>Weather Refresh (sec)</label><input name="WEATHER_REFRESH_SEC" type="number" value="{{cfg.WEATHER_REFRESH_SEC or 300}}"></div>
</div>
<div class="grid3" style="margin-top:8px">
<label><input type="checkbox" name="WEATHER_INCLUDE_WATCH" value="1" {% if cfg.WEATHER_INCLUDE_WATCH %}checked{% endif %}> Include "Watch"</label>
<label><input type="checkbox" name="WEATHER_FORCE_ACTIVE" value="1" {% if cfg.WEATHER_FORCE_ACTIVE %}checked{% endif %}> Force Active</label>
<div><label>Force Text</label><input name="WEATHER_FORCE_TEXT" value="{{cfg.WEATHER_FORCE_TEXT or ''}}"></div>
</div>
<div class="grid3" style="margin-top:8px">
<div><label>Weather Timeout (s)</label><input name="WEATHER_TIMEOUT" type="number" step="0.5" value="{{cfg.WEATHER_TIMEOUT or 5.0}}"></div>
<div><label>Weather Test Delay (s) (0=off)</label><input name="WEATHER_TEST_DELAY" type="number" value="{{cfg.WEATHER_TEST_DELAY or 0}}"></div>
<div><label>Weather Sticky Duration (s)</label><input name="WEATHER_STICKY_SEC" type="number" value="{{cfg.WEATHER_STICKY_SEC or 20}}" title="How long banner stays visible"></div>
</div>
<hr style="border:none;border-top:1px solid #1c2434;margin:14px 0">
<h3 style="margin-top:16px;font-size:15px;color:#94a3b8;"> Weather Alert Display by Severity</h3>
<p class="muted">Control how weather alerts appear based on severity level.</p>
<div class="grid4" style="margin-top:8px">
<div>
<label>Warnings — Every N Scrolls</label>
<input name="WEATHER_WARNING_EVERY_N_SCROLLS" type="number" min="1" value="{{cfg.WEATHER_WARNING_EVERY_N_SCROLLS or 5}}">
</div>
<div>
<label>Warning Color</label>
<select name="WEATHER_WARNING_COLOR">
{% for color in ["red","white","yellow","cyan","magenta","orange"] %}
<option value="{{color}}" {% if cfg.WEATHER_WARNING_COLOR==color %}selected{% endif %}>{{color}}</option>
{% endfor %}
</select>
</div>
<div>
<label>Advisories/Watches — Every N Scrolls</label>
<input name="WEATHER_ADVISORY_EVERY_N_SCROLLS" type="number" min="1" value="{{cfg.WEATHER_ADVISORY_EVERY_N_SCROLLS or 10}}">
</div>
<div>
<label>Advisory Color</label>
<select name="WEATHER_ADVISORY_COLOR">
{% for color in ["yellow","cyan","white","magenta","orange"] %}
<option value="{{color}}" {% if cfg.WEATHER_ADVISORY_COLOR==color %}selected{% endif %}>{{color}}</option>
{% endfor %}
</select>
</div>
<div>
<label>Statements — Every N Scrolls</label>
<input name="WEATHER_STATEMENT_EVERY_N_SCROLLS" type="number" min="1" value="{{cfg.WEATHER_STATEMENT_EVERY_N_SCROLLS or 15}}">
</div>
<div>
<label>Statement Color</label>
<select name="WEATHER_STATEMENT_COLOR">
{% for color in ["cyan","yellow","white","magenta","orange"] %}
<option value="{{color}}" {% if cfg.WEATHER_STATEMENT_COLOR==color %}selected{% endif %}>{{color}}</option>
{% endfor %}
</select>
</div>
<div>
<label>Weather Preroll After Clock</label>
<label><input type="checkbox" name="WEATHER_PREROLL_ENABLED" value="1" {% if cfg.WEATHER_PREROLL_ENABLED != false %}checked{% endif %}> Show alert full-screen after top-of-hour</label>
</div>
<div>
<label>Weather Preroll Duration (s)</label>
<input name="WEATHER_PREROLL_SEC" type="number" min="1" value="{{cfg.WEATHER_PREROLL_SEC or 8}}">
</div>
</div>
<p class="muted" style="margin-top:8px;">
<strong>Warnings</strong>: highest severity, most frequent<br>
<strong>Advisories/Watches</strong>: moderate severity<br>
<strong>Statements</strong> (Special Weather Statement): informational, least frequent
</p>
</section>
<section>
<h2>Night Mode (Auto-Dim + Slow Scroll)</h2>
<p class="muted">Automatically dim display and slow scroll speed during night hours. Overrides other dimming settings when active.</p>
<div class="grid4">
<label><input type="checkbox" name="NIGHT_MODE_ENABLED" value="1" {% if cfg.NIGHT_MODE_ENABLED %}checked{% endif %}> Enable Night Mode</label>
<div><label>Night Start (HH:MM)</label><input name="NIGHT_MODE_START" value="{{cfg.NIGHT_MODE_START or '22:00'}}" placeholder="22:00"></div>
<div><label>Night End (HH:MM)</label><input name="NIGHT_MODE_END" value="{{cfg.NIGHT_MODE_END or '07:00'}}" placeholder="07:00"></div>
</div>
<div class="grid4" style="margin-top:8px">
<div><label>Night Brightness %</label><input name="NIGHT_MODE_DIM_PCT" type="number" min="1" max="100" value="{{cfg.NIGHT_MODE_DIM_PCT or 30}}"></div>
<div><label>Night Scroll Speed %</label><input name="NIGHT_MODE_SPEED_PCT" type="number" min="1" max="100" value="{{cfg.NIGHT_MODE_SPEED_PCT or 50}}"></div>
</div>
<p class="muted" style="margin-top:8px;">
Example: 22:00-07:00 at 30% brightness and 50% scroll speed (half speed = slower, easier to read)
</p>
</section>
<section>
<h2>Scoreboard</h2>
<div class="grid4">
<label><input type="checkbox" name="SCOREBOARD_ENABLED" value="1" {% if cfg.SCOREBOARD_ENABLED %}checked{% endif %}> Enable</label>
<div><label>Leagues (comma)</label><input name="SCOREBOARD_LEAGUES" value="{{ (cfg.SCOREBOARD_LEAGUES or [])|join(',') }}"></div>
<div><label>NHL Teams (comma)</label><input name="SCOREBOARD_NHL_TEAMS" value="{{ (cfg.SCOREBOARD_NHL_TEAMS or [])|join(',') }}"></div>
<div><label>NFL Teams (comma)</label><input name="SCOREBOARD_NFL_TEAMS" value="{{ (cfg.SCOREBOARD_NFL_TEAMS or [])|join(',') }}"></div>
</div>
<div class="grid4" style="margin-top:8px">
<div><label>Poll window min before game</label><input name="SCOREBOARD_POLL_WINDOW_MIN" type="number" value="{{cfg.SCOREBOARD_POLL_WINDOW_MIN or 120}}"></div>
<div><label>Poll cadence (sec)</label><input name="SCOREBOARD_POLL_CADENCE" type="number" value="{{cfg.SCOREBOARD_POLL_CADENCE or 60}}"></div>
<div><label>Live refresh (sec)</label><input name="SCOREBOARD_LIVE_REFRESH" type="number" value="{{cfg.SCOREBOARD_LIVE_REFRESH or 45}}"></div>
<div><label>Max games</label><input name="SCOREBOARD_MAX_GAMES" type="number" min="1" value="{{cfg.SCOREBOARD_MAX_GAMES or 2}}"></div>
</div>
<div class="grid3" style="margin-top:8px">
<div><label>Pregame Window (min)</label><input name="SCOREBOARD_PREGAME_WINDOW_MIN" type="number" value="{{cfg.SCOREBOARD_PREGAME_WINDOW_MIN or 30}}" title="Start announcing and tracking pregame data this many minutes before game start"></div>
<div><label>Postgame Delay (min)</label><input name="SCOREBOARD_POSTGAME_DELAY_MIN" type="number" value="{{cfg.SCOREBOARD_POSTGAME_DELAY_MIN or 5}}" title="Keep showing scoreboard N minutes after FINAL"></div>
<label><input type="checkbox" name="SCOREBOARD_SHOW_COUNTDOWN" value="1" {% if cfg.SCOREBOARD_SHOW_COUNTDOWN %}checked{% endif %} title="Inject pregame announcement on top row and flip to scoreboard at T-minus trigger"> Pregame Announce</label>
</div>
<div class="grid3" style="margin-top:8px">
<div><label>Announce every N scrolls</label><input name="SCOREBOARD_PREGAME_ANNOUNCE_EVERY" type="number" min="1" value="{{cfg.SCOREBOARD_PREGAME_ANNOUNCE_EVERY or 5}}" title="When Pregame Announce is on, inject every N top-row scroll completions"></div>
<div><label>Announce color</label><input name="SCOREBOARD_PREGAME_ANNOUNCE_COLOR" value="{{cfg.SCOREBOARD_PREGAME_ANNOUNCE_COLOR or 'cyan'}}" title="Color of the pregame announcement text (e.g. cyan, yellow, white)"></div>
<div><label>Scoreboard trigger (min before)</label><input name="SCOREBOARD_LIVE_TRIGGER_MIN" type="number" min="1" value="{{cfg.SCOREBOARD_LIVE_TRIGGER_MIN or 5}}" title="Flip into full scoreboard mode this many minutes before game start (shows 0-0 PRE until live)"></div>
</div>
<div class="grid4" style="margin-top:8px">
<div><label>Precedence</label>
<select name="SCOREBOARD_PRECEDENCE">
{% for opt in ["normal","force"] %}
<option value="{{opt}}" {% if cfg.SCOREBOARD_PRECEDENCE==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
<label><input type="checkbox" name="SCOREBOARD_HOME_FIRST" value="1" {% if cfg.SCOREBOARD_HOME_FIRST %}checked{% endif %}> Home first</label>
</div>
<div class="grid4" style="margin-top:8px">
<label><input type="checkbox" name="SCOREBOARD_SHOW_CLOCK" value="1" {% if cfg.SCOREBOARD_SHOW_CLOCK %}checked{% endif %}> Show clock</label>
<label><input type="checkbox" name="SCOREBOARD_SHOW_SOG" value="1" {% if cfg.SCOREBOARD_SHOW_SOG %}checked{% endif %}> Show SOG (NHL)</label>
<label><input type="checkbox" name="SCOREBOARD_SHOW_POSSESSION" value="1" {% if cfg.SCOREBOARD_SHOW_POSSESSION %}checked{% endif %}> Show possession (NFL)</label>
<label><input type="checkbox" name="SCOREBOARD_INCLUDE_OTHERS" value="1" {% if cfg.SCOREBOARD_INCLUDE_OTHERS %}checked{% endif %}> Include others</label>
</div>
<div class="grid2" style="margin-top:8px">
<label><input type="checkbox" name="SCOREBOARD_ONLY_MY_TEAMS" value="1" {% if cfg.SCOREBOARD_ONLY_MY_TEAMS %}checked{% endif %}> Only my teams</label>
</div>
<details style="margin-top:12px">
<summary>Scoreboard Test Harness</summary>
<div class="grid4" style="margin-top:8px">
<label><input type="checkbox" name="SCOREBOARD_TEST" value="1" {% if cfg.SCOREBOARD_TEST %}checked{% endif %}> Enable</label>
<div>
<label>League</label>
<select name="SCOREBOARD_TEST_LEAGUE">
{% for opt in ["NHL","NFL"] %}
<option value="{{opt}}" {% if (cfg.SCOREBOARD_TEST_LEAGUE or 'NHL')==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
<div><label>Home Team (abbrev)</label><input name="SCOREBOARD_TEST_HOME" value="{{cfg.SCOREBOARD_TEST_HOME or ''}}"></div>
<div><label>Away Team (abbrev)</label><input name="SCOREBOARD_TEST_AWAY" value="{{cfg.SCOREBOARD_TEST_AWAY or ''}}"></div>
</div>
<div style="margin-top:8px">
<label>Test Duration (sec, 0=infinite)</label>
<input name="SCOREBOARD_TEST_DURATION" type="number" min="0" value="{{cfg.SCOREBOARD_TEST_DURATION or 0}}">
</div>
</details>
</section>
<section>
<h2>Score Alerts</h2>
<div class="grid4">
<label><input type="checkbox" name="SCORE_ALERTS_ENABLED" value="1" {% if cfg.SCORE_ALERTS_ENABLED %}checked{% endif %}> Enable</label>
<label><input type="checkbox" name="SCORE_ALERTS_NHL" value="1" {% if cfg.SCORE_ALERTS_NHL %}checked{% endif %}> NHL alerts</label>
<label><input type="checkbox" name="SCORE_ALERTS_NFL" value="1" {% if cfg.SCORE_ALERTS_NFL %}checked{% endif %}> NFL alerts</label>
<label><input type="checkbox" name="SCORE_ALERTS_MY_TEAMS_ONLY" value="1" {% if cfg.SCORE_ALERTS_MY_TEAMS_ONLY %}checked{% endif %}> My teams only</label>
</div>
<div class="grid4" style="margin-top:8px">
<div><label>Cycles per alert</label><input name="SCORE_ALERTS_CYCLES" type="number" min="1" value="{{cfg.SCORE_ALERTS_CYCLES or 2}}"></div>
<div><label>Queue max</label><input name="SCORE_ALERTS_QUEUE_MAX" type="number" min="1" value="{{cfg.SCORE_ALERTS_QUEUE_MAX or 4}}"></div>
<div><label>Flash ms</label><input name="SCORE_ALERTS_FLASH_MS" type="number" min="50" value="{{cfg.SCORE_ALERTS_FLASH_MS or 250}}"></div>
<div><label>NFL TD delta (min points)</label><input name="SCORE_ALERTS_NFL_TD_DELTA_MIN" type="number" min="1" value="{{cfg.SCORE_ALERTS_NFL_TD_DELTA_MIN or 6}}"></div>
</div>
<div style="margin-top:8px">
<label>Flash colors (comma, names)</label>
<input name="SCORE_ALERTS_FLASH_COLORS" value="{{ (cfg.SCORE_ALERTS_FLASH_COLORS or ['red','white','blue'])|join(',') }}">
</div>
<details style="margin-top:8px">
<summary>Test generator</summary>
<div class="grid4" style="margin-top:8px">
<label><input type="checkbox" name="SCORE_ALERTS_TEST" value="1" {% if cfg.SCORE_ALERTS_TEST %}checked{% endif %}> Enable test</label>
<div><label>League</label>
<select name="SCORE_ALERTS_TEST_LEAGUE">
{% for opt in ["NHL","NFL"] %}
<option value="{{opt}}" {% if (cfg.SCORE_ALERTS_TEST_LEAGUE or 'NHL')==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
<div><label>Team</label><input name="SCORE_ALERTS_TEST_TEAM" value="{{cfg.SCORE_ALERTS_TEST_TEAM or 'MTL'}}"></div>
<div><label>Interval (sec)</label><input name="SCORE_ALERTS_TEST_INTERVAL_SEC" type="number" min="1" value="{{cfg.SCORE_ALERTS_TEST_INTERVAL_SEC or 12}}"></div>
</div>
</details>
</section>
<section>
<h2>Clock (Standalone Override)</h2>
<p class="muted">These apply when <span class="mono">OVERRIDE_MODE=CLOCK</span> is active.</p>
<div class="grid4">
<label><input type="checkbox" name="CLOCK_24H" value="1" {% if cfg.CLOCK_24H %}checked{% endif %}> 24-hour clock</label>
<label><input type="checkbox" name="CLOCK_SHOW_SECONDS" value="1" {% if cfg.CLOCK_SHOW_SECONDS %}checked{% endif %}> Show seconds</label>
<label><input type="checkbox" name="CLOCK_BLINK_COLON" value="1" {% if cfg.CLOCK_BLINK_COLON %}checked{% endif %}> Blink colon</label>
<div><label>Time color</label>
<select name="CLOCK_COLOR">
{% for opt in ["yellow","white","red","green","cyan","blue","magenta","orange","grey","black"] %}
<option value="{{opt}}" {% if cfg.CLOCK_COLOR==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="grid4" style="margin-top:8px">
<label><input type="checkbox" name="CLOCK_DATE_SHOW" value="1" {% if cfg.CLOCK_DATE_SHOW %}checked{% endif %}> Show date</label>
<div><label>Date format (strftime)</label><input name="CLOCK_DATE_FMT" value="{{cfg.CLOCK_DATE_FMT or '%a %b %d'}}"></div>
<div><label>Date color</label>
<select name="CLOCK_DATE_COLOR">
{% for opt in ["white","yellow","red","green","cyan","blue","magenta","orange","grey","black"] %}
<option value="{{opt}}" {% if cfg.CLOCK_DATE_COLOR==opt %}selected{% endif %}>{{opt}}</option>
{% endfor %}
</select>
</div>
</div>
</section>
<section>
<h2>Maintenance Banner</h2>
<div class="grid3">
<label><input type="checkbox" name="MAINTENANCE_MODE" value="1" {% if cfg.MAINTENANCE_MODE %}checked{% endif %}> Enable Maintenance Mode</label>
<label><input type="checkbox" name="MAINTENANCE_SCROLL" value="1" {% if cfg.MAINTENANCE_SCROLL %}checked{% endif %}> Scroll banner</label>
<div><label>Scroll PPS</label><input name="MAINTENANCE_PPS" type="number" step="0.5" value="{{cfg.MAINTENANCE_PPS or 24.0}}"></div>
</div>
<div style="margin-top:8px"><label>Text</label><input name="MAINTENANCE_TEXT" value="{{cfg.MAINTENANCE_TEXT or ''}}"></div>
</section>
<section>
<h2>Diagnostics / Test Flags</h2>
<div class="grid4">
<label><input type="checkbox" name="DEMO_MODE" value="1" {% if cfg.DEMO_MODE %}checked{% endif %}> Demo Mode (no workers)</label>
<label><input type="checkbox" name="DEBUG_OVERLAY" value="1" {% if cfg.DEBUG_OVERLAY %}checked{% endif %}> Debug Overlay</label>
</div>
</section>
<div class="row">
<div class="col"><button type="submit">Save</button></div>
</div>
</form>
</main></body></html>
"""
RAW_HTML = """
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Raw JSON Editor</title>
""" + BASE_CSS + """
</head><body>
<header>
<h1>Raw JSON Editor</h1>
<div class="toolbar"><a class="btn secondary" href="{{ url_for('home') }}">Back</a></div>
</header>
<main>
<section>
<form method="post" action="{{ url_for('raw_editor_post') }}">
<label>config.json</label>
<textarea name="json" rows="28" class="mono">{{ raw }}</textarea>
<div style="margin-top:8px"><button type="submit">Save JSON</button></div>
</form>
</section>
</main></body></html>
"""
OVERRIDE_HTML = """
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Overrides</title>
""" + BASE_CSS + """
</head><body>
<header>
<h1>Temporary Overrides</h1>
<div class="toolbar"><a class="btn secondary" href="{{ url_for('home') }}">Back</a></div>
</header>
<main>
<section>
<form method="post" action="{{ url_for('apply_override') }}">
<div class="grid3">
<div><label>Mode</label>
<select name="OVERRIDE_MODE">
{% for m in ["OFF","BRIGHT","SCOREBOARD","MESSAGE","MAINT","CLOCK","LOGO"] %}
<option value="{{m}}" {% if cfg.OVERRIDE_MODE==m %}selected{% endif %}>{{m}}</option>
{% endfor %}
</select>
</div>
<div><label>Duration (minutes, 0 = until cleared)</label>
<input type="number" name="OVERRIDE_DURATION_MIN" min="0" value="{{cfg.OVERRIDE_DURATION_MIN or 0}}">