-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCastAPI.py
3240 lines (2663 loc) · 121 KB
/
CastAPI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
a: zak45
d: 02/04/2024
v: 1.0.0
CastAPI
Cast media to ddp device(s)
DESKTOP: cast your full screen or a window content
capture frames
MEDIA: cast an image / video / capture device
capture frames
cast image with Websocket
create matrix based on ddp devices... so cast to a BIG one
+
API: FastAPI, for integration with third party application (e.g. Chataigne)
Web GUI based on NiceGUI
# 27/05/2024: cv2.imshow with import av freeze
"""
import time
import sys
import os
import concurrent_log_handler
import traceback
import configparser
import queue
import cfg_load as cfg
from starlette.websockets import WebSocketDisconnect
import desktop
import media
import niceutils as nice
import ast
import tkinter as tk
from asyncio import set_event_loop_policy,sleep,create_task
from threading import current_thread
from subprocess import Popen
from ddp_queue import DDPDevice
from socket import gethostbyname
from pathlib import Path as PathLib
from utils import CASTUtils as Utils, LogElementHandler
from utils import HTTPDiscovery as Net
from cv2utils import ImageUtils
from cv2utils import CV2Utils
from niceutils import LocalFilePicker
from utils import ScreenAreaSelection as Sa
from utils import YtSearch
from utils import AnimatedElement as Animate
from multicast import MultiUtils as Multi
from datetime import datetime
from str2bool import str2bool
from PIL import Image
from fastapi.openapi.utils import get_openapi
from fastapi import HTTPException, Path, WebSocket
from starlette.concurrency import run_in_threadpool
from nicegui import app, ui, native, run
from configmanager import ConfigManager
from fontsmanager import FontPreviewManager
cfg_mgr = ConfigManager(logger_name='WLEDLogger.api')
Desktop = desktop.CASTDesktop()
Media = media.CASTMedia()
Netdevice = Net()
if sys.platform.lower() == 'win32':
from asyncio import WindowsSelectorEventLoopPolicy
set_event_loop_policy(WindowsSelectorEventLoopPolicy())
class_to_test = ['Desktop', 'Media', 'Netdevice']
action_to_test = ['stop', 'shot', 'info', 'close-preview', 'host', 'open-preview', 'reset', 'multicast']
app.debug = False
log_ui = None
server_port = None
server_ip = None
"""
When this env var exist, this mean run from the one-file compressed executable.
Load of the config is not possible, folder config should not exist yet.
This avoid FileNotFoundError.
This env not exist when run from the extracted program.
Expected way to work.
"""
if "NUITKA_ONEFILE_PARENT" not in os.environ:
# load optional modules
if str2bool(cfg_mgr.custom_config['player']) or str2bool(cfg_mgr.custom_config['system-stats']):
import psutil
# validate network config
server_ip = cfg_mgr.server_config['server_ip']
if not Utils.validate_ip_address(server_ip):
cfg_mgr.logger.error(f'Bad server IP: {server_ip}')
sys.exit(1)
server_port = cfg_mgr.server_config['server_port']
if server_port == 'auto':
server_port = native.find_open_port()
else:
server_port = int(cfg_mgr.server_config['server_port'])
if server_port not in range(1, 65536):
cfg_mgr.logger.error(f'Bad server Port: {server_port}')
sys.exit(2)
"""
Actions to do at application initialization
"""
async def init_actions():
""" Done at start of app and before GUI available """
cfg_mgr.logger.info(f'Main running {current_thread().name}')
# Apply some default params only once
if str2bool(cfg_mgr.app_config['init_config_done']) is not True:
def on_ok_click():
# Close the window when OK button is clicked
root.destroy()
# Create the main window
root = tk.Tk()
root.title("WLEDVideoSync Information")
root.geometry("820x460") # Set the size of the window
root.configure(bg='#657B83') # Set the background color
# Apply default GUI / param , depend on platform
"""
preview_proc = False
native_ui = False
native_ui_size = 1200, 720
uvicorn = True
"""
if sys.platform.lower() == 'win32':
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'preview_proc', 'False')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'native_ui', 'True')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'native_ui_size', '1200,720')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'uvicorn', 'True')
else:
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'preview_proc', 'True')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'native_ui', 'False')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'native_ui_size', '')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'uvicorn', 'False')
Utils.update_ini_key('config/WLEDVideoSync.ini', 'app', 'init_config_done', 'True')
# Define the window's contents
info_text = "Some Params has changed.... restart your app"
info_label = tk.Label(root, text=info_text, bg='#657B83', fg='white', justify=tk.LEFT)
info_label.pack(padx=10, pady=10)
# Create the OK button
ok_button = tk.Button(root, text="Ok", command=on_ok_click, bg='gray', fg='white')
ok_button.pack(pady=10)
# Start the Tkinter event loop
root.mainloop()
sys.exit()
# Apply presets
try:
if str2bool(cfg_mgr.preset_config['load_at_start']):
if cfg_mgr.preset_config['filter_media'] != '':
cfg_mgr.logger.debug(f"apply : {cfg_mgr.preset_config['filter_media']} to filter Media")
await load_filter_preset('Media', interactive=False, file_name=cfg_mgr.preset_config['filter_media'])
if cfg_mgr.preset_config['filter_desktop'] != '':
cfg_mgr.logger.debug(f"apply : {cfg_mgr.preset_config['filter_desktop']} to filter Desktop")
await load_filter_preset('Desktop', interactive=False, file_name=cfg_mgr.preset_config['filter_desktop'])
if cfg_mgr.preset_config['cast_media'] != '':
cfg_mgr.logger.debug(f"apply : {cfg_mgr.preset_config['cast_media']} to cast Media")
await load_cast_preset('Media', interactive=False, file_name=cfg_mgr.preset_config['cast_media'])
if cfg_mgr.preset_config['cast_desktop'] != '':
cfg_mgr.logger.debug(f"apply : {cfg_mgr.preset_config['cast_desktop']} to cast Desktop")
await load_cast_preset('Desktop', interactive=False, file_name=cfg_mgr.preset_config['cast_desktop'])
# check if linux and wayland
if sys.platform.lower() == 'linux' and os.getenv('WAYLAND_DISPLAY') is not None:
cfg_mgr.logger.error('Wayland detected, preview should not work !!. Switch to X11 session if want to see preview.')
except Exception as e:
cfg_mgr.logger.error(f"Error on app startup {e}")
# to share data between threads and main
t_data_buffer = queue.Queue() # create a thread safe queue
class CastAPI:
dark_mode = False
netstat_process = None
charts_row = None
player = None
progress_bar = None
cpu_chart = None
video_slider = None
media_button_sync = None
slider_button_sync = None
type_sync = 'none' # none, slider , player
last_type_sync = '' # slider , player
search_areas = [] # contains YT search
media_cast = None
media_cast_run = None
desktop_cast = None
desktop_cast_run = None
total_frame = 0
total_packet = 0
ram = 0
cpu = 0
w_image = None
windows_titles = {}
"""
FastAPI
"""
@app.get("/api", tags=["root"])
async def read_api_root():
"""
Status: provide WLEDVideoSync info
"""
return {"info": Utils.compile_info()}
@app.get("/api/{class_name}/params", tags=["params"])
async def all_params(class_name: str = Path(description=f'Class name, should be in: {class_to_test}')):
"""
Retrieve all 'params/attributes' from a class
"""
if class_name not in class_to_test:
raise HTTPException(status_code=400, detail=f"Class name: {class_name} not in {class_to_test}")
class_params = vars(globals()[class_name])
# to avoid delete param from the class, need to copy to another dict
return_data = {k: v for k, v in class_params.items()}
if class_name != 'Netdevice':
del return_data['frame_buffer']
del return_data['cast_frame_buffer']
return {"all_params": return_data}
@app.put("/api/{class_name}/update_attribute", tags=["params"])
async def update_attribute_by_name(class_name: str, param: str, value: str):
"""
Update attribute for a specific class name
"""
if class_name not in class_to_test:
raise HTTPException(status_code=400,
detail=f"Class name: {class_name} not in {class_to_test}")
try:
class_obj = globals()[class_name]
except KeyError:
raise HTTPException(status_code=400,
detail=f"Invalid class name: {class_name}")
if not hasattr(class_obj, param):
raise HTTPException(status_code=400,
detail=f"Invalid attribute name: {param}")
# determine type from class attribute
expected_type = type(getattr(class_obj, param))
# main type validation
if expected_type == bool:
if str2bool(value) is None:
raise HTTPException(status_code=400,
detail=f"Value '{value}' for attribute '{param}' must be a boolean")
else:
value = str2bool(value)
elif expected_type == int:
if param != "viinput":
if not isinstance(value, int) and not str(value).isdigit():
raise HTTPException(status_code=400,
detail=f"Value '{value}' for attribute '{param}' " f"must be an integer")
value = int(value)
elif expected_type == list:
if value is None or value == '':
value = []
value = ast.literal_eval(str(value))
if not isinstance(value, list):
raise HTTPException(status_code=400,
detail=f"Value '{value}' for attribute '{param}' must be a list")
elif expected_type == str:
if not isinstance(value, str):
raise HTTPException(status_code=400,
detail=f"Value '{value}' for attribute '{param}' must be a string")
else:
raise HTTPException(status_code=400,
detail=f"Unsupported attribute type '{expected_type}' for attribute '{param}'")
# special case for viinput , str or int, depend on the entry
if param == 'viinput':
try:
value = int(value)
except ValueError:
cfg_mgr.logger.debug("viinput act as string only")
# check valid IP
if param == 'host':
is_valid = Utils.validate_ip_address(value)
if not is_valid:
raise HTTPException(status_code=400,
detail=f"Value '{value}' for attribute '{param}' must be IP address")
# check cast devices comply to [(0,'IP'), ... ]
if param == 'cast_devices':
is_valid = Multi.is_valid_cast_device(str(value))
if not is_valid:
raise HTTPException(status_code=400,
detail=f"Value '{value}' for attribute '{param}' not comply to list [(0,'IP'),...]")
# set new value to class attribute
setattr(class_obj, param, value)
return {"message": f"Attribute '{param}' updated successfully for : '{class_obj}'"}
@app.get("/api/{class_obj}/buffer", tags=["buffer"])
async def buffer_count(class_obj: str = Path(description=f'Class name, should be in: {class_to_test}')):
"""
Retrieve frame buffer length from a class (image number)
"""
if class_obj not in class_to_test:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} not in {class_to_test}")
class_name = globals()[class_obj]
return {"buffer_count": len(class_name.frame_buffer)}
@app.get("/api/{class_obj}/buffer/{number}", tags=["buffer"])
async def buffer_image(class_obj: str = Path(description=f'Class name, should be in: {class_to_test}'),
number: int = 0):
"""
Retrieve image number from buffer class, result base64 image
"""
if class_obj not in class_to_test:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} not in {class_to_test}")
try:
class_name = globals()[class_obj]
except KeyError:
raise HTTPException(status_code=400, detail=f"Invalid Class name: {class_obj}")
if number > len(class_name.frame_buffer):
raise HTTPException(status_code=400, detail=f"Image number : {number} not exist for Class name: {class_obj} ")
try:
img = ImageUtils.image_array_to_base64(class_name.frame_buffer[number])
except Exception as b_error:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} provide this error : {b_error}")
return {"buffer_base64": img}
@app.get("/api/{class_obj}/buffer/{number}/save", tags=["buffer"])
async def buffer_image_save(class_obj: str = Path(description=f'Class name, should be in: {class_to_test}'),
number: int = 0):
"""
Retrieve image number from buffer class, save it to default folder
"""
if class_obj not in class_to_test:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} not in {class_to_test}")
try:
class_name = globals()[class_obj]
except KeyError:
raise HTTPException(status_code=400, detail=f"Invalid Class name: {class_obj}")
if number > len(class_name.frame_buffer):
raise HTTPException(status_code=400, detail=f"Image number : {number} not exist for Class name: {class_obj} ")
try:
await CV2Utils.save_image(class_name, 'frame_buffer', number)
except Exception as b_error:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} provide this error : {b_error}")
return {"buffer_save": True}
@app.get("/api/{class_obj}/buffer/{number}/asciiart/save", tags=["buffer"])
async def buffer_image_save_ascii(class_obj: str = Path(description=f'Class name, should be in: {class_to_test}'),
number: int = 0):
"""
Retrieve image number from buffer class, save it to default folder as ascii_art
"""
if class_obj not in class_to_test:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} not in {class_to_test}")
try:
class_name = globals()[class_obj]
except KeyError:
raise HTTPException(status_code=400, detail=f"Invalid Class name: {class_obj}")
if number > len(class_name.frame_buffer):
raise HTTPException(status_code=400, detail=f"Image number : {number} not exist for Class name: {class_obj} ")
try:
await CV2Utils.save_image(class_name, 'frame_buffer', number, ascii_art=True)
except Exception as b_error:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} provide this error : {b_error}")
return {"buffer_save": True}
@app.get("/api/{class_obj}/run_cast", tags=["casts"])
async def run_cast(class_obj: str = Path(description=f'Class name, should be in: {class_to_test}')):
"""
Run the cast() from {class_obj}
"""
if class_obj not in class_to_test:
raise HTTPException(status_code=400, detail=f"Class name: {class_obj} not in {class_to_test}")
try:
my_obj = globals()[class_obj]
except KeyError:
raise HTTPException(status_code=400, detail=f"Invalid Class name: {class_obj}")
# run cast and pass the queue to share data
my_obj.cast(shared_buffer=t_data_buffer)
return {"run_cast": True}
@app.get("/api/util/active_win", tags=["desktop"])
async def util_active_win():
"""
Show title from actual active window
"""
return {"window_title": Utils.active_window()}
@app.get("/api/util/win_titles", tags=["desktop"])
async def util_win_titles():
"""
Retrieve all titles from windows
"""
return {"windows_titles": Utils.windows_titles()}
@app.get("/api/util/device_list", tags=["media"])
async def util_device_list():
"""
Show available devices
"""
return {"device_list": Utils.dev_list}
@app.get("/api/util/device_list_update", tags=["media"])
async def util_device_list_update():
"""
Update available devices list
"""
status = "Error"
if Utils.dev_list_update():
status = "Ok"
return {"device_list": status}
@app.get("/api/util/download_yt/{yt_url:path}", tags=["media"])
async def util_download_yt(yt_url: str):
"""
Download video from Youtube Url
"""
if 'youtu' in yt_url:
try:
await Utils.youtube_download(yt_url=yt_url, interactive=False)
except Exception as e:
cfg_mgr.logger.error(f'youtube error: {e}')
raise HTTPException(status_code=400,
detail=f"Not able to retrieve video from : {yt_url} {e}")
else:
raise HTTPException(status_code=400,
detail=f"Looks like not YT url : {yt_url} ")
return {"youtube": "ok"}
@app.get("/api/util/device_net_scan", tags=["network"])
async def util_device_net_scan():
"""
Scan network devices with zeroconf
"""
# run in non-blocking mode
await run_in_threadpool(Netdevice.discover)
return {"net_device_list": "done"}
@app.get("/api/util/blackout", tags=["utility"])
async def util_blackout():
"""
Put ALL ddp devices Off and stop all Casts
"""
cfg_mgr.logger.warning('** BLACKOUT **')
Desktop.t_exit_event.set()
Media.t_exit_event.set()
Desktop.stopcast = True
Media.stopcast = True
async def wled_off(class_name):
await Utils.put_wled_live(class_name.host, on=False, live=False, timeout=1)
if class_name.multicast:
for cast_item in class_name.cast_devices:
await Utils.put_wled_live(cast_item[1], on=False, live=False, timeout=1)
if Desktop.wled:
await wled_off(Desktop)
if Media.wled:
await wled_off(Media)
return {"blackout": "done"}
@app.get("/api/util/casts_info", tags=["casts"])
async def util_casts_info(img: bool = False):
"""
Get info from all Cast Threads
Generate image for preview if requested
:param: img : False/true
"""
cfg_mgr.logger.debug('Request Cast(s) info')
# clear
child_info_data = {}
child_list = []
params = True if img else False
# create casts lists
for item in Desktop.cast_names:
child_list.append(item)
Desktop.cast_name_todo.append(str(item) + '||' + 'info' + '||' + str(params) + '||' + str(time.time()))
for item in Media.cast_names:
child_list.append(item)
Media.cast_name_todo.append(str(item) + '||' + 'info' + '||' + str(params) + '||' + str(time.time()))
# request info from threads
Desktop.t_todo_event.set()
Media.t_todo_event.set()
# use to stop the loop in case of
# start_time = time.time()
cfg_mgr.logger.debug(f'Need to receive info from : {child_list}')
# iterate through all Cast Names
for _ in child_list:
# wait and get info dict from a thread
try:
data = t_data_buffer.get(timeout=3)
child_info_data.update(data)
t_data_buffer.task_done()
except queue.Empty:
cfg_mgr.logger.error('Empty queue, but Desktop/Media cast names list not')
break
# sort the dict
sort_child_info_data = dict(sorted(child_info_data.items()))
Desktop.t_todo_event.clear()
Media.t_todo_event.clear()
cfg_mgr.logger.debug('End request info')
return {"t_info": sort_child_info_data}
@app.get("/api/{class_name}/list_actions", tags=["casts"])
async def list_todo_actions(class_name: str = Path(description=f'Class name, should be in: {class_to_test}')):
"""
List to do actions for a Class name
:param class_name:
:return:
"""
if class_name not in class_to_test:
raise HTTPException(status_code=400,
detail=f"Class name: {class_name} not in {class_to_test}")
try:
class_obj = globals()[class_name]
except KeyError:
raise HTTPException(status_code=400,
detail=f"Invalid class name: {class_name}")
if not hasattr(class_obj, 'cast_name_todo'):
raise HTTPException(status_code=400,
detail=f"Invalid attribute name")
return {"actions": class_obj.cast_name_todo}
@app.put("/api/{class_name}/cast_actions", tags=["casts"])
def action_to_thread(class_name: str = Path(description=f'Class name, should be in: {class_to_test}'),
cast_name: str = None,
action: str = None,
params: str = 'None',
clear: bool = False,
execute: bool = False):
"""
Add action to cast_name_todo for a specific Cast
If clear, remove all to do
:param params: params to pass to the action
:param execute: instruct casts to execute action in to do list
:param clear: Remove all actions from to do list
:param class_name:
:param cast_name:
:param action:
:return:
"""
if class_name not in class_to_test:
cfg_mgr.logger.error(f"Class name: {class_name} not in {class_to_test}")
raise HTTPException(status_code=400,
detail=f"Class name: {class_name} not in {class_to_test}")
try:
class_obj = globals()[class_name]
except KeyError as e:
cfg_mgr.logger.error(f"Invalid class name: {class_name}")
raise HTTPException(
status_code=400, detail=f"Invalid class name: {class_name}"
) from e
if cast_name is not None and cast_name not in class_obj.cast_names:
cfg_mgr.logger.error(f"Invalid Cast name: {cast_name}")
raise HTTPException(status_code=400,
detail=f"Invalid Cast name: {cast_name}")
if not hasattr(class_obj, 'cast_name_todo'):
cfg_mgr.logger.error("Invalid attribute name")
raise HTTPException(status_code=400, detail="Invalid attribute name")
if clear:
class_obj.cast_name_todo = []
cfg_mgr.logger.debug(f" To do cleared for {class_obj}'")
return {"message": f" To do cleared for {class_obj}'"}
if action not in action_to_test and action is not None:
cfg_mgr.logger.error(f"Invalid action name. Allowed : {str(action_to_test)}")
raise HTTPException(
status_code=400,
detail=f"Invalid action name {action}. Allowed : {str(action_to_test)}",
)
if class_name == 'Desktop':
class_obj.t_desktop_lock.acquire()
elif class_name == 'Media':
class_obj.t_media_lock.acquire()
if not execute:
if cast_name is None or action is None:
if class_name == 'Desktop':
class_obj.t_desktop_lock.release()
elif class_name == 'Media':
class_obj.t_media_lock.release()
cfg_mgr.logger.error(f"Invalid Cast/Thread name or action not set")
raise HTTPException(status_code=400,
detail=f"Invalid Cast/Thread name or action not set")
else:
class_obj.cast_name_todo.append(str(cast_name) + '||' + str(action) + '||' + str(params) + '||' + str(time.time()))
if class_name == 'Desktop':
class_obj.t_desktop_lock.release()
elif class_name == 'Media':
class_obj.t_media_lock.release()
cfg_mgr.logger.debug(f"Action '{action}' added successfully to : '{class_obj}'")
return {"message": f"Action '{action}' added successfully to : '{class_obj}'"}
else:
if cast_name is None and action is None:
if class_name == 'Desktop':
class_obj.t_desktop_lock.release()
elif class_name == 'Media':
class_obj.t_media_lock.release()
class_obj.t_todo_event.set()
cfg_mgr.logger.debug(f"Actions in queue will be executed")
return {"message": "Actions in queue will be executed"}
elif cast_name is None or action is None:
if class_name == 'Desktop':
class_obj.t_desktop_lock.release()
elif class_name == 'Media':
class_obj.t_media_lock.release()
cfg_mgr.logger.error("Invalid Cast/Thread name or action not set")
raise HTTPException(status_code=400,
detail="Invalid Cast/Thread name or action not set")
else:
class_obj.cast_name_todo.append(str(cast_name) + '||' + str(action) + '||' + str(params) + '||' + str(time.time()))
if class_name == 'Desktop':
class_obj.t_desktop_lock.release()
elif class_name == 'Media':
class_obj.t_media_lock.release()
class_obj.t_todo_event.set()
cfg_mgr.logger.debug(f"Action '{action}' added successfully to : '{class_obj} and execute is On'")
return {"message": f"Action '{action}' added successfully to : '{class_obj} and execute is On'"}
@app.get("/api/config/presets/{preset_type}/{file_name}/{class_name}", tags=["presets"])
async def apply_preset_api(class_name: str = Path(description=f'Class name, should be in: {class_to_test}'),
preset_type: str = None,
file_name: str = None):
"""
Apply preset to Class name from saved one
:param preset_type:
:param class_name:
:param file_name: preset name
:return:
"""
if class_name not in class_to_test:
raise HTTPException(status_code=400,
detail=f"Class name: {class_name} not in {class_to_test}")
if preset_type not in ['filter', 'cast']:
raise HTTPException(status_code=400,
detail=f"Type preset: {preset_type} unknown")
if preset_type == 'filter':
try:
result = await load_filter_preset(class_name=class_name, interactive=False, file_name=file_name)
if result is False:
raise HTTPException(status_code=400,
detail=f"Apply preset return value : {result}")
except Exception as e:
raise HTTPException(
status_code=400, detail=f"Not able to apply preset : {e}"
) from e
elif preset_type == 'cast':
try:
result = await load_cast_preset(class_name=class_name, interactive=False, file_name=file_name)
if result is False:
raise HTTPException(status_code=400,
detail=f"Apply preset return value : {result}")
except Exception as e:
raise HTTPException(
status_code=400, detail=f"Not able to apply preset : {e}"
) from e
else:
raise HTTPException(status_code=400,
detail=f"unknown error in preset API")
return {"apply_preset_result": True}
"""
FastAPI WebSockets
"""
websocket_info = 'These are the websocket end point calls and result'
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""
WS image Cast (we use WebSocket to minimize delay)
Main logic: check action name, extract params, execute func, return ws status
see page ws/docs for help
usage example:
{"action":{"type":"cast_image", "param":{"image_number":0,"device_number":-1, "class_name":"Media"}}}
"""
action = ''
allowed_actions = cfg_mgr.ws_config['allowed-actions'].split(',')
try:
await websocket.accept()
while True:
data = await websocket.receive_json()
if not Utils.validate_ws_json_input(data):
ws_msg = 'WEBSOCKET: received data not compliant with expected format ({"action":{"type":"","param":{}}})'
cfg_mgr.logger.error(ws_msg)
raise ValueError(ws_msg)
action = data["action"]["type"]
params = data["action"]["param"]
if action not in allowed_actions:
ws_msg = 'WEBSOCKET: received data contains unexpected action'
cfg_mgr.logger.error(ws_msg)
raise ValueError(ws_msg)
if action == 'cast_image':
required_params = ["image_number", "device_number", "class_name"]
for param in required_params:
if param not in params:
ws_msg = f'WEBSOCKET: missing required parameter: {param}'
cfg_mgr.logger.error(ws_msg)
raise ValueError(ws_msg)
optional_params = {
"fps_number": (0, 60),
"duration_number": (0, None),
"retry_number": (0, 10)
}
for param, (min_val, max_val) in optional_params.items():
if param in params:
params[param] = max(min_val, min(params[param], max_val)) if max_val else max(min_val,
params[param])
if "buffer_name" in params:
params["buffer_name"] = params["buffer_name"]
func_name_parts = action.split('.')
if len(func_name_parts) == 2:
all_func = globals().get(func_name_parts[0])
if all_func:
my_func = getattr(all_func, func_name_parts[1], None)
if my_func:
result = await run_in_threadpool(my_func, **params)
else:
raise AttributeError(f'Function {func_name_parts[1]} not found in {func_name_parts[0]}')
else:
raise AttributeError(f'Module {func_name_parts[0]} not found')
elif len(func_name_parts) == 1:
if my_func := globals().get(action):
result = await run_in_threadpool(my_func, **params)
else:
raise AttributeError(f'Function {action} not found')
else:
raise ValueError(f'Invalid function name: {func_name_parts}')
await websocket.send_json({"action": action, "result": "success", "data": result})
except WebSocketDisconnect:
cfg_mgr.logger.warning('ws closed')
except Exception as e:
error_msg = traceback.format_exc()
cfg_mgr.logger.error(error_msg)
await websocket.send_json({"action": action, "result": "internal error", "error": str(e), "data": error_msg})
await websocket.close()
def init_wvs(metadata, mouthCues):
cfg_mgr.logger.info('websocket connection initiated')
cfg_mgr.logger.debug(metadata, mouthCues)
def cast_image(image_number,
device_number,
class_name,
fps_number=25,
duration_number=1000,
retry_number=0,
buffer_name='buffer'):
"""
Cast one image from buffer to a cast device at FPS during duration in s and with retry of n retry_number
:param buffer_name:
:param class_name:
:param image_number:
:param device_number:
:param fps_number:
:param duration_number:
:param retry_number:
:return:
"""
images_buffer = []
class_obj = globals()[class_name]
"""
on 10/04/2024: device_number come from list entry order (0...n)
"""
cfg_mgr.logger.debug('Cast one image from buffer')
cfg_mgr.logger.debug(f"image number: {image_number}")
cfg_mgr.logger.debug(f"device number: {device_number}")
cfg_mgr.logger.debug(f"FPS: {fps_number}")
cfg_mgr.logger.debug(f"Duration (in ms): {duration_number}")
cfg_mgr.logger.debug(f"retry packet number: {retry_number}")
cfg_mgr.logger.debug(f"class name: {class_name}")
cfg_mgr.logger.debug(f"Image from buffer: {buffer_name}")
if device_number == -1: # instruct to use IP from the class.host
ip = class_obj.host
else:
try:
ip = class_obj.cast_devices[device_number][1] # IP is on 2nd position
except IndexError:
cfg_mgr.logger.error('No device set in Cast Devices list')
return
if ip == '127.0.0.1':
cfg_mgr.logger.warning('WEBSOCKET: Nothing to do for localhost 127.0.0.1')
return
if buffer_name.lower() == 'buffer':
images_buffer = class_obj.frame_buffer
elif buffer_name.lower() == 'multicast':
images_buffer = class_obj.cast_frame_buffer
# we need to retrieve the ddp device created during settings and not create one each time ....
find = False
for ddp_device in Utils.ddp_devices:
if ddp_device._destination == ip:
ddp = ddp_device
find = True
break
if find is False:
# create DDP device
ddp = DDPDevice(ip)
Utils.ddp_devices.append(ddp)
start_time = time.time() * 1000 # Get the start time in ms
end_time = start_time + duration_number # Calculate the end time
if class_obj.protocol == "ddp":
while time.time() * 1000 < end_time: # Loop until current time exceeds end time in ms
# Send x frames here
try:
ddp.send_to_queue(images_buffer[image_number], retry_number)
if fps_number != 0:
time.sleep(1 / fps_number) # Sleep in s for the time required to send one frame
except IndexError:
cfg_mgr.logger.error(f'No image set for this index: {image_number}')
return
else:
cfg_mgr.logger.warning('Not DDP')
"""
NiceGUI
"""
@ui.page('/')
async def main_page():
global log_ui
"""
Root page definition
"""
dark = ui.dark_mode(CastAPI.dark_mode).bind_value_to(CastAPI, 'dark_mode')
apply_custom()
if str2bool(cfg_mgr.custom_config['animate-ui']):
# Add Animate.css to the HTML head
ui.add_head_html("""
<link rel="stylesheet" href="./assets/css/animate.min.css"/>
""")
"""
timer created on main page run to refresh datas
"""
ui.timer(int(cfg_mgr.app_config['timer']), callback=root_timer_action)
"""
Header with button menu
"""
await nice.head_set(name='Main', target='/', icon='home')
"""
App info
"""
if str2bool(cfg_mgr.custom_config['animate-ui']):
head_row_anim = Animate(ui.row, animation_name_in='backInDown', duration=1)
head_row = head_row_anim.create_element()
else:
head_row = ui.row()
with head_row.classes('w-full no-wrap'):
ui.label('DESKTOP: Cast Screen / Window content').classes('bg-slate-400 w-1/3')
with ui.card().classes('bg-slate-400 w-1/3'):
img = ui.image("/assets/favicon.ico").classes('self-center')
img.on('click', lambda: animate_toggle(img))
img.style('cursor: pointer')
img.tailwind.border_width('4').width('8')
ui.label('MEDIA: Cast Image / Video / Capture Device (e.g. USB Camera ...)').classes('bg-slate-400 w-1/3')
"""
WLEDVideoSync image
"""
ui.separator().classes('mt-6')
CastAPI.w_image = ui.image("./assets/Source-intro.png").classes('self-center')
CastAPI.w_image.classes(add='animate__animated')
CastAPI.w_image.tailwind.border_width('8').width('1/6')
"""
Video player
"""
if str2bool(cfg_mgr.custom_config['player']):
await video_player_page()
CastAPI.player.set_visibility(False)
"""
Row for Cast /Filters / info / Run / Close
"""