-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLEDcommander.py
More file actions
1516 lines (1150 loc) · 51.9 KB
/
LEDcommander.py
File metadata and controls
1516 lines (1150 loc) · 51.9 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
# LEDcommander.py - Multiprocessing Command Dispatcher for LEDarcade
# To do
# =====
#
# - work on transitions between displays
# - this is tough because each different display type is spawned as a process
# - perhaps the calling function can take a screen shot (deep copy ScreenArray)
# and put that in the CommandQueue so we can fade back to it later
"""
===============================================================================
LEDcommander.py - Multiprocessing Command Dispatcher for LEDarcade
===============================================================================
Author: William McEvoy (@datagod)
DESCRIPTION:
This module coordinates all LED display tasks by acting as a command-and-control
process. It uses Python's `multiprocessing` library to delegate screen updates
(such as digital clocks, terminal messages, or titles) to subprocesses.
KEY ARCHITECTURE:
- The main `Run()` function monitors a shared `CommandQueue`.
- Based on the command type (`Action`), it starts/stops worker processes.
- Each subprocess initializes and controls the hardware via `LEDarcade` safely.
IMPORTANT: Display + GPIO Access
- The `LEDarcade` module interfaces directly with LED matrices via GPIO or
framebuffer libraries (like `rpi-rgb-led-matrix`).
- Due to hardware constraints, **display initialization must be done inside child processes** only.
- Initializing the display in the main process can lead to:
- corrupted hardware state
- silent failures
- GPIO conflicts and undefined behavior
✅ Always import `LEDarcade` and call `LED.Initialize()` inside the subprocess
✅ Never use GPIO display functions from the parent process
MULTIPROCESS DESIGN:
- Subprocesses are spawned using `multiprocessing.Process` (fork model).
- Only one active `DisplayProcess` is allowed at any time to avoid buffer collisions.
- A shared `StopEvent` is used to gracefully shut down current subprocesses.
COMMANDQUEUE:
- A shared `multiprocessing.Queue` used to deliver structured command dictionaries.
- `Run()` consumes commands in order (FIFO) and dispatches the corresponding worker.
- For TerminalMode, `Run()` forwards terminal messages back into the same queue
(this avoids direct queue collisions between parent and subprocess).
TERMINAL MODE:
- A persistent terminal subprocess that waits for new text messages.
- Displays each message sequentially with typing and scrolling effects.
- Maintains a local FIFO queue (`message_queue`) to handle rapid incoming messages.
- When idle, shows a blinking cursor until the next message arrives.
SPAWN METHOD (OPTIONAL SAFETY):
For more isolation (especially with native libraries), consider:
import multiprocessing
multiprocessing.set_start_method("spawn")
This ensures new interpreter processes are used instead of forks. It's slightly
slower but more reliable when working with C/C++ extensions like GPIO.
EXAMPLES:
To start TerminalMode and send a message:
CommandQueue.put({"Action": "terminalmode_on", "Message": "Hello", ...})
To send more messages:
CommandQueue.put({"Action": "terminalmessage", "Message": "Next line!", ...})
To stop TerminalMode:
CommandQueue.put({"Action": "terminalmode_off"})
"""
print("")
print("=============================================")
print("== LEDcommander.py =")
print("=============================================")
print("")
import time
import traceback
import random
import itertools # for generator function
from multiprocessing import Event, Process, Queue
import queue
from flask import Flask, request, jsonify
import logging
import os
#GLOBAL VARS
RotateClockDelay = 10 #minutes between rotation of different display styles
IsOnAirActive = False
RotateClockDelay = 5
IMAGE_DIR = "./images" # Adjust to your actual path, e.g., "/home/pi/LEDarcade/images"
def serve_web_control(queue, port=5055):
"""
Starts a minimal Flask server to receive control commands and put them into the command queue.
Supports all LEDarcade actions with field customization.
"""
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app = Flask(__name__)
VALID_ACTIONS = {
"showclock": [],
"stopclock": [],
#"showtitlescreen": ["BigText", "LittleText", "LittleTextRGB", "ScrollText", "ScrollTextRGB", "ScrollSleep", "DisplayTime", "ExitEffect", "LittleTextZoom"],
"analogclock": [],
"retrodigital": [],
"starrynightdisplaytext": ["text1","text2","text3"],
"launch_dotinvaders": ["duration"],
"launch_defender": ["duration"],
"launch_tron": ["duration"],
"launch_outbreak": ["duration"],
"launch_spacedot": ["duration"],
"launch_blasteroids": ["duration"],
"launch_stockticker": ["duration"],
"launch_fallingsand": ["duration"],
"launch_gravitysim": ["duration"],
#"twitchtimer_on": ["StreamStartedDateTime", "StreamDurationHHMMSS"],
#"twitchtimer_off": [],
#"terminalmode_on": ["Message", "RGB", "ScrollSleep"],
"terminalmessage": ["Message", "RGB", "ScrollSleep"],
"terminalmode_off": [],
"showheart": [],
"showintro": [],
"showonair": ["duration"],
"showonair_off": [],
"showdemotivate": [],
"showgif": ["GIF", "loops", "sleep"],
"showviewers": ["chatusers"],
#"showimagezoom": ["image", "zoommin", "zoommax", "zoomfinal", "sleep", "step"],
"quit": []
}
def sanitize_data(data, action):
# General RGB tuple parsing
for key in data:
if 'RGB' in key and isinstance(data[key], str):
try:
data[key] = tuple(map(int, data[key].split(",")))
except Exception:
data[key] = (255, 255, 255) # Default white
# Action-specific sanitization
if action in ["showgif", "showimagezoom", "showtitlescreen", "terminalmode_on", "terminalmessage", "showonair"]:
for key in ["Duration", "loops", "sleep", "ScrollSleep", "DisplayTime", "zoommin", "zoommax", "zoomfinal", "step", "duration"]:
if key in data:
try:
data[key] = float(data[key]) if '.' in str(data[key]) else int(data[key])
except ValueError:
pass
if action == "showgif":
if "GIF" in data and not data["GIF"].startswith("/"):
data["GIF"] = os.path.join(IMAGE_DIR, os.path.basename(data["GIF"]))
if action == "showimagezoom":
if "image" in data and not data["image"].startswith("/"):
data["image"] = os.path.join(IMAGE_DIR, os.path.basename(data["image"]))
if action == "showviewers":
if "chatusers" in data and isinstance(data["chatusers"], str):
data["chatusers"] = data["chatusers"].split(",")
return data
@app.route('/command', methods=['POST'])
def handle_command():
data = request.json if request.is_json else request.form.to_dict()
print(f"[LEDweb] Received: {data}")
action = data.get("Action")
print("[LEDweb] Action:",action)
if not action or action not in VALID_ACTIONS:
return jsonify({'status': 'error', 'message': f'Invalid or missing action: {action}'}), 400
data = sanitize_data(data, action)
allowed_fields = set(VALID_ACTIONS[action] + ["Action"])
filtered_data = {k: v for k, v in data.items() if k in allowed_fields}
queue.put(filtered_data)
return jsonify({'status': 'ok', 'message': f"Queued: {action}"}), 200
@app.route('/', methods=['GET'])
def homepage():
html = """
<html>
<head>
<title>LED Commander 1.0</title>
<style>
body {
font-family: 'Courier New', monospace;
padding: 20px;
background-color: #000;
color: #0f0;
text-shadow: 0 0 5px rgba(0, 255, 0, 0.5);
position: relative;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: repeating-linear-gradient(
to bottom,
transparent 0px,
transparent 1px,
rgba(0, 0, 0, 0.3) 1px,
rgba(0, 0, 0, 0.3) 2px
);
pointer-events: none;
z-index: 1;
opacity: 0.5;
}
.commands-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
position: relative;
z-index: 2;
}
.command-section {
padding: 15px;
border: 1px solid #0f0;
border-radius: 5px;
background-color: #111;
box-shadow: 0 0 10px rgba(0, 255, 0, 0.2);
}
.command-section h2 {
margin-top: 0;
color: #0f0;
}
label {
color: #0f0;
}
input[type="text"] {
width: 100%;
background-color: #222;
color: #0f0;
border: 1px solid #0f0;
padding: 5px;
font-family: 'Courier New', monospace;
}
input[type="submit"] {
background-color: #0f0;
color: #000;
border: none;
padding: 8px;
cursor: pointer;
font-family: 'Courier New', monospace;
}
input[type="submit"]:hover {
background-color: #00ff00;
}
#status-message {
position: fixed;
top: 10px;
left: 50%;
transform: translateX(-50%);
padding: 10px;
border-radius: 5px;
z-index: 1000;
display: none;
}
.success {
background-color: #004400;
color: #0f0;
}
.error {
background-color: #440000;
color: #ff0000;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
const forms = document.querySelectorAll('form');
forms.forEach(form => {
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page reload
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());
fetch('/command', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
const statusMsg = document.getElementById('status-message');
statusMsg.innerText = result.message;
statusMsg.className = 'success';
statusMsg.style.display = 'block';
setTimeout(() => { statusMsg.style.display = 'none'; }, 3000);
})
.catch(error => {
const statusMsg = document.getElementById('status-message');
statusMsg.innerText = 'Error: ' + error;
statusMsg.className = 'error';
statusMsg.style.display = 'block';
setTimeout(() => { statusMsg.style.display = 'none'; }, 3000);
});
});
});
});
</script>
</head>
<body>
<div id="status-message"></div>
<h1>LED Commander Control Panel 1.0</h1>
<div class="commands-container">
"""
for action, fields in VALID_ACTIONS.items():
html += f'<div class="command-section"><h2>{action.capitalize()}</h2><form action="/command" method="post">'
html += f'<input type="hidden" name="Action" value="{action}">'
for field in fields:
html += f'<label>{field}: <input type="text" name="{field}"></label><br>'
html += '<input type="submit" value="Submit"></form></div>'
html += "</div></body></html>"
return html
app.run(host='0.0.0.0', port=port, threaded=False)
@app.route('/command', methods=['POST'])
def handle_command():
data = request.json if request.is_json else request.form.to_dict()
print(f"[LEDweb] Received: {data}")
action = data.get("Action")
print("[LEDweb] Action:",action)
if not action or action not in VALID_ACTIONS:
return jsonify({'status': 'error', 'message': f'Invalid or missing action: {action}'}), 400
data = sanitize_data(data, action)
allowed_fields = set(VALID_ACTIONS[action] + ["Action"])
filtered_data = {k: v for k, v in data.items() if k in allowed_fields}
queue.put(filtered_data)
return jsonify({'status': 'ok', 'message': f"Queued: {action}"}), 200
@app.route('/', methods=['GET'])
def homepage():
html = """
<html>
<head>
<title>LED Commander 1.0</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.command-section { margin-bottom: 40px; padding: 20px; border: 1px solid #ccc; border-radius: 8px; }
.command-section h2 { margin-top: 0; }
input[type="text"] { width: 300px; }
</style>
</head>
<body>
<h1>LED Commander Control Panel 1.0</h1>
"""
for action, fields in VALID_ACTIONS.items():
html += f'<div class="command-section"><h2>{action.capitalize()}</h2><form action="/command" method="post">'
html += f'<input type="hidden" name="Action" value="{action}">'
for field in fields:
html += f'<label>{field}: <input type="text" name="{field}"></label><br>'
html += '<input type="submit" value="Send"></form></div>'
html += '</body></html>'
return html
app.run(host="0.0.0.0", port=port, use_reloader=False) # use_reloader=False for multiprocessing safety
CursorH = 0
CursorV = 0
StopEvent = Event()
DisplayProcess = None
CurrentDisplayMode = None
TerminalQueue = Queue()
ClockFallbackEnabled = True
def fallback_action_generator():
# Your sequence from __main__ in the documents; customize durations/styles
actions = [
{"Action": "showclock", "Style": 4, "Zoom": 1, "duration": 10, "Delay": 10},
{"Action": "retrodigital", "duration": 10},
{"Action": "showclock", "Style": 5, "Zoom": 1, "duration": 10, "Delay": 10},
{"Action": "showclock", "Style": 3, "Zoom": 2, "duration": 10, "Delay": 10},
{"Action": "showclock", "Style": 1, "Zoom": 3, "duration": 10, "Delay": 30},
{"Action": "launch_defender", "duration": 10},
{"Action": "analogclock", "duration": 10 },
{"Action": "launch_dotinvaders", "duration": 10},
{"Action": "retrodigital", "duration": 10},
{"Action": "launch_gravitysim", "duration": 10},
{"Action": "retrodigital", "duration": 10},
{"Action": "launch_tron", "duration": 10},
{"Action": "retrodigital", "duration": 10},
{"Action": "launch_outbreak", "duration": 10},
{"Action": "retrodigital", "duration": 10},
{"Action": "launch_spacedot", "duration": 10},
{"Action": "retrodigital", "duration": 10},
{"Action": "launch_fallingsand", "duration": 10},
]
for action in itertools.cycle(actions):
yield action
def Run(CommandQueue):
global StopEvent, DisplayProcess, CurrentDisplayMode, IsOnAirActive, FallbackGenerator
print("\n" + "=" * 65)
print("🧠 LEDcommander Launched")
print("=" * 65)
print("Multiprocessing control engine for LEDarcade.")
print("Handles dynamic screen updates, effects, and real-time commands.")
print("Developed by William McEvoy (@datagod) for Raspberry Pi environments.")
print("Core Features:")
print(" - Isolated subprocess rendering (clock, titles, etc.)")
print(" - Clean LED shutdown via command queue")
print(" - Expandable message-based architecture")
print(" - Safe multiprocessing for GPIO hardware")
print("-------------------------------------------------------------")
print("Command your pixels like a pro — with LEDcommander.")
print("=" * 65 + "\n")
print("")
print("")
while True:
try:
# Get command or handle empty
try:
Command = CommandQueue.get(timeout=1)
except queue.Empty:
# Check for timed-out OnAir
if IsOnAirActive and DisplayProcess and not DisplayProcess.is_alive():
print("[LEDcommander] OnAir timed out, proceeding to next")
IsOnAirActive = False
CurrentDisplayMode = None
# If idle (no OnAir, no process), pull generator
if not IsOnAirActive and (DisplayProcess is None or not DisplayProcess.is_alive()):
print("[LEDcommander] Queue empty and idle—using fallback generator")
Command = next(FallbackGenerator)
else:
continue # Wait if something's running
print(f"[LEDcommander][Run] Received command: {Command}")
if not isinstance(Command, dict):
continue
Action = Command.get("Action", "").lower()
print(f"<-- [LEDcommander] Action: {Action}")
# Handle off (force stop, proceed)
if Action == "showonair_off":
if IsOnAirActive:
print("[LEDcommander] Manual stop OnAir, proceeding to next")
StopEvent.set()
if DisplayProcess and DisplayProcess.is_alive():
DisplayProcess.join(timeout=5) # Prevent hangs
IsOnAirActive = False
CurrentDisplayMode = None
continue # Loop will now pull next queue/generator
# Handle on (start with duration)
if Action == "showonair":
print("[LEDcommander] Starting OnAir")
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join(timeout=5)
StopEvent.clear()
CurrentDisplayMode = "onair"
IsOnAirActive = True
DisplayProcess = Process(target=ShowOnAir, args=(Command, StopEvent))
DisplayProcess.start()
continue
# For other actions (interrupt if OnAir active)
if IsOnAirActive:
print("[LEDcommander] Non-OnAir command during OnAir—interrupting")
StopEvent.set()
DisplayProcess.join(timeout=5)
IsOnAirActive = False
CurrentDisplayMode = None
#----------------------------------
#-- CLOCK MODE
#----------------------------------
if Action == "showclock":
print("Starting the clock")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Restarting")
#time.sleep(10)
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "clock"
DisplayProcess = Process(target=ShowDigitalClock, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "stopclock":
print("Stopping the clock")
StopEvent.set()
if DisplayProcess and DisplayProcess.is_alive():
DisplayProcess.join()
#----------------------------------
#-- TITLE SCREEN
#----------------------------------
elif Action == "showtitlescreen":
print("Showing title screen")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "title"
DisplayProcess = Process(target=ShowTitleScreen, args=(Command, StopEvent))
DisplayProcess.start()
#----------------------------------
#-- ANALOG CLOCK
#----------------------------------
elif Action == "analogclock":
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "clock"
DisplayProcess = Process(target=ShowAnalogClock, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "retrodigital":
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "clock"
DisplayProcess = Process(target=ShowRetroDigital, args=(Command, StopEvent))
DisplayProcess.start()
#----------------------------------
#-- STARRY NIGHT VARIATIONS
#----------------------------------
elif Action == "starrynightdisplaytext":
print("[LEDcommander][Run] Starry Night Display Text")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "starrynight"
DisplayProcess = Process(target=StarryNightDisplayText, args=(Command, StopEvent))
DisplayProcess.start()
#----------------------------------
#-- LAUNCH PROGRAMS
#----------------------------------
elif Action == "launch_dotinvaders":
print("[LEDcommander][Run] Launching DotInvaders")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "dotinvaders"
DisplayProcess = Process(target=LaunchDotInvaders, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_defender":
print("[LEDcommander][Run] Launching Defender")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "defender"
DisplayProcess = Process(target=LaunchDefender, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_tron":
print("[LEDcommander][Run] Launching Tron")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "tron"
DisplayProcess = Process(target=LaunchTron, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_outbreak":
print("[LEDcommander][Run] Launching Outbreak")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "outbreak"
DisplayProcess = Process(target=LaunchOutbreak, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_spacedot":
print("[LEDcommander][Run] Launching SpaceDot")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "spacedot"
DisplayProcess = Process(target=LaunchSpaceDot, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_blasteroids":
print("[LEDcommander][Run] Launching Blasteroids")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "blasteroids"
DisplayProcess = Process(target=LaunchBlasteroids, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_stockticker":
print("[LEDcommander][Run] Launching StockTicker")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "stockticker"
DisplayProcess = Process(target=LaunchStockTicker, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_fallingsand":
print("[LEDcommander][Run] Launching fallingsand")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "tron"
DisplayProcess = Process(target=LaunchFallingSand, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "launch_gravitysim":
print("[LEDcommander][Run] Launching GravitySim")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "gravitysim"
DisplayProcess = Process(target=LaunchGravitySim, args=(Command, StopEvent))
DisplayProcess.start()
#----------------------------------
#-- TWITCH TIMER
#----------------------------------
elif Action == "twitchtimer_on":
print("Showing title screen")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "twitch"
DisplayProcess = Process(target=StartTwitchTimer, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "twitchtimer_off":
print("Showing title screen")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display in use. Stopping process.")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "stopped"
#----------------------------------
#-- TERMINAL MODE
#----------------------------------
elif Action == "terminalmode_on":
if DisplayProcess and DisplayProcess.is_alive():
print("[LEDcommander][Run] TerminalMode already active.")
else:
StopEvent.clear()
CurrentDisplayMode = "terminal"
DisplayProcess = Process(target=StartTerminalMode, args=(CommandQueue, StopEvent, Command))
DisplayProcess.start()
elif Action == "terminalmessage":
if DisplayProcess and DisplayProcess.is_alive() and CurrentDisplayMode == "terminal":
TerminalQueue.put(Command)
else:
print("[LEDcommander] TerminalMode not active. Auto-starting it.")
StopEvent.set()
if DisplayProcess and DisplayProcess.is_alive():
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "terminal"
TerminalQueue = Queue() # reset queue to avoid stale messages
DisplayProcess = Process(target=StartTerminalMode, args=(TerminalQueue, StopEvent, Command))
DisplayProcess.start()
# In StartTerminalMode(), replace CommandQueue with TerminalQueue
elif Action == "terminalmode_off":
print("[LEDcommander] terminalmode_OFF detected")
CurrentDisplayMode = "stopped"
DisplayProcess = Process(target=StopTerminalMode, args=())
DisplayProcess.start()
StopEvent.set()
if DisplayProcess and DisplayProcess.is_alive():
DisplayProcess.join()
print("[LEDcommander] TerminalMode stopped.")
#----------------------------------------
# ANIMATIONS --
#----------------------------------------
elif Action == "showheart":
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "heart"
DisplayProcess = Process(target=ShowHeart, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "showintro":
print("[LEDcommander][Run] Launching Intro")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "showintro"
DisplayProcess = Process(target=ShowIntro, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "showdemotivate":
print("[LEDcommander][Run] Launching Demotivate")
if DisplayProcess and DisplayProcess.is_alive():
print("LED display already in use. Stopping process then restarting")
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "showdemotivate"
DisplayProcess = Process(target=ShowDemotivate, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "showgif":
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "gif"
DisplayProcess = Process(target=ShowGIF, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "showviewers":
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "gif"
DisplayProcess = Process(target=ShowViewers, args=(Command, StopEvent))
DisplayProcess.start()
elif Action == "showimagezoom":
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
StopEvent.clear()
CurrentDisplayMode = "image"
DisplayProcess = Process(target=ShowImageZoom, args=(Command, StopEvent))
#After showing Image, we restart the clock
CommandQueue.put(OldCommand)
DisplayProcess.start()
elif Action == "quit":
print("[LEDcommander] Quit received.")
if DisplayProcess and DisplayProcess.is_alive():
StopEvent.set()
DisplayProcess.join()
print("[LEDcommander][Run] Shutdown complete.")
break # Exit the loop and end the process
except Exception as e:
print(f"[LEDcommander] Run error: {e}")
traceback.print_exc()
if ClockFallbackEnabled:
CommandQueue.put({"Action": "showclock"}) # Fallback
#----------------------------------------------------------
#-- Action functions
#----------------------------------------------------------
def ShowDigitalClock(Command,StopEvent):
import LEDarcade as LED
LED.Initialize()
print("RedR: ",LED.RedR)
#Sprite display locations ?? maybe not needed
#LED.ClockH, LED.ClockV, LED.ClockRGB = 0,0, (0,150,0)
#LED.DayOfWeekH, LED.DayOfWeekV, LED.DayOfWeekRGB = 8,20, (125,20,20)
#LED.MonthH, LED.MonthV, LED.MonthRGB = 28,20, (125,30,0)
#LED.DayOfMonthH, LED.DayOfMonthV, LED.DayOfMonthRGB = 47,20, (115,40,10)
ClockStyle = Command.get("Style", 1)
ZoomFactor = Command.get("Zoom", 2)
RunMinutes = Command.get("duration", 1)
AnimationDelay = Command.get("Delay", 30)
print(f"[LEDcommander] Showing clock: Style={ClockStyle}, Zoom={ZoomFactor}, Duration={RunMinutes}")
LED.DisplayDigitalClock(
ClockStyle=ClockStyle,
CenterHoriz=True,
v=1,
hh=24,
RGB=LED.LowGreen,
ShadowRGB = LED.ShadowGreen,
ZoomFactor = ZoomFactor,
AnimationDelay = AnimationDelay,
RunMinutes = RunMinutes,
StopEvent = StopEvent
)
#LED.SweepClean()
def ShowRetroDigital(Command,StopEvent):
import LEDarcade as LED
LED.Initialize()
ClockStyle = Command.get("Style", 4)
ZoomFactor = Command.get("Zoom", 1)
RunMinutes = Command.get("duration", 5)
AnimationDelay = Command.get("Delay", 30)
print(f"[LEDcommander] Showing clock: Style={ClockStyle}, Zoom={ZoomFactor}, Duration={RunMinutes}")
LED.DisplayDigitalClock(
ClockStyle=ClockStyle,
CenterHoriz=True,
v=1,
hh=24,
RGB=LED.LowGreen,
ShadowRGB = LED.ShadowGreen,
ZoomFactor = ZoomFactor,
AnimationDelay = AnimationDelay,
RunMinutes = RunMinutes,
StopEvent = StopEvent
)
#LED.SweepClean()
def StartTwitchTimer(Command,StopEvent):
import LEDarcade as LED
LED.Initialize()
StreamStartedDateTime = Command.get("StreamStartedDateTime", 1)
StreamDurationHHMMSS = Command.get("StreamDurationHHMMSS", 1)
print(f"[LEDcommander][StartTwitchTimer] StreamDurationHHMMSS: ",StreamDurationHHMMSS)
LED.DisplayTwitchTimer(
CenterHoriz = True,
CenterVert = False,
h = 0,
v = 1,
hh = 24,
RGB = LED.LowGreen,
ShadowRGB = LED.ShadowGreen,
ZoomFactor = 3,
AnimationDelay = 30,
RunMinutes = 10,
StartDateTimeUTC = StreamStartedDateTime,
HHMMSS = StreamDurationHHMMSS,
StopEvent = StopEvent