-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdualled_pro.py
More file actions
2212 lines (1994 loc) · 107 KB
/
Copy pathdualled_pro.py
File metadata and controls
2212 lines (1994 loc) · 107 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
# -*- coding: utf-8 -*-
"""
PS5 LED — v2 (DualSense SVG Edition)
=======================================
- رسم DualSense دقيق من أصل SVG مرخّص، بشريطي إضاءة يحضنان التاتشباد كما في اليد الحقيقية
- تتزامن إضاءة اليد المعروضة مع اللون الحقيقي على اليد الفعلية بنسبة 100%
- كشف تلقائي لنوع اليد (PS5/PS4) وعرض النموذج الصحيح
- كل المزايا السابقة محفوظة: ملفات تعريف، خمول تلقائي، تأثيرات، إلخ
التشغيل (ويندوز):
pip install -U pydualsense hidapi
python "V9 - Copy.py"
"""
import os, re, sys, atexit, platform, math, random, json, time, threading, colorsys, argparse, traceback, datetime, hashlib, queue
from pathlib import Path
import tkinter as tk
from tkinter import ttk, messagebox
# --------------------------- Paths / Config ---------------------------
APP_NAME = "DualLED_Pro"
def app_config_dir() -> Path:
sysname = platform.system()
if sysname == "Windows":
return Path(os.getenv("APPDATA", str(Path.home()))) / APP_NAME
elif sysname == "Darwin":
return Path.home() / "Library" / "Application Support" / APP_NAME
else:
return Path.home() / ".config" / APP_NAME
CONFIG_DIR = app_config_dir(); CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CFG_FILE = CONFIG_DIR / "config.json"
LOG_FILE = CONFIG_DIR / "app.log"
def log(*a):
s = " ".join(str(x) for x in a)
try:
# Rotate at ~1 MB so a stuck backend can't grow the log unbounded and fill the disk.
try:
if LOG_FILE.exists() and LOG_FILE.stat().st_size > 1_048_576:
bak = LOG_FILE.with_suffix(".log.1")
try: bak.unlink(missing_ok=True)
except Exception: pass
LOG_FILE.replace(bak)
except Exception:
pass
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {s}\n")
except Exception:
pass
DEFAULT_CFG = {
"language": "ar",
"fullscreen_on_start": True,
"last_mode": "Manual",
"speed": 1.0, # 0.1 .. 5.0
"rainbow_brightness": 0.9, # 0.2 .. 1.0
"flash_duty": 0.5, # 0.1 .. 0.9
"color": "#00aaff",
"alerts": { "low": True, "plug": True, "full": True, "threshold": 15, "rate": 0.6 },
"backend": "auto",
"pds_batt_field": None,
"pds_charge_field": None,
"bgr_swap": False,
"max_instances": 1, # السماح بـ 5 نسخ كحد أقصى
"minimize_to_tray": True, # تصغير للشريط السفلي بدلاً من الإغلاق
"shell_color": "white", # طقم ألوان اليد المعروضة
"profiles": {
"Default": {"mode":"Manual","speed":1.0,"rainbow_brightness":0.9,"flash_duty":0.5,"color":"#00aaff"},
"Fortnite": {"mode":"Manual","speed":1.0,"rainbow_brightness":0.9,"flash_duty":0.5,"color":"#3b82f6"},
"COD": {"mode":"Manual","speed":1.0,"rainbow_brightness":0.9,"flash_duty":0.5,"color":"#ff3434"},
"FIFA": {"mode":"Manual","speed":1.0,"rainbow_brightness":0.9,"flash_duty":0.5,"color":"#22c55e"}
},
"auto_sleep": {"enabled": False, "minutes": 30, "action": "off"}, # off / solid
"bg_starfield": True
}
def load_cfg():
d = json.loads(json.dumps(DEFAULT_CFG))
try:
if CFG_FILE.exists():
on_disk = json.loads(CFG_FILE.read_text(encoding="utf-8"))
def merge(dst, src):
for k, v in src.items():
if isinstance(v, dict) and isinstance(dst.get(k), dict):
merge(dst[k], v)
else:
dst[k] = v
merge(d, on_disk)
except Exception as e:
log("cfg read err:", e)
return d
def save_cfg(cfg):
try:
CFG_FILE.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
except Exception as e:
log("cfg save err:", e)
# خنق الحفظ للمسارات الساخنة (سحب المنتقي/المنزلقات): كتابة واحدة كحد أقصى بالثانية،
# مع flush لاحق يضمن عدم ضياع آخر قيمة.
_CFG_SAVE = {"last": 0.0, "dirty": False}
def save_cfg_throttled(cfg):
now = time.time()
if now - _CFG_SAVE["last"] >= 1.0:
_CFG_SAVE["last"] = now; _CFG_SAVE["dirty"] = False
save_cfg(cfg)
else:
_CFG_SAVE["dirty"] = True
def flush_cfg():
if _CFG_SAVE["dirty"]:
_CFG_SAVE["dirty"] = False; _CFG_SAVE["last"] = time.time()
save_cfg(CFG)
CFG = load_cfg()
# --------------------------- Single Instance (N slots) ---------------------------
# ===== Single-instance & restore via Win32 (ctypes only) =====
_MUTEX_NAME = "Global\\DualSenseLED_SingleInstance"
_EVENT_NAME1 = "Global\\DualSenseLED_Restore"
_EVENT_NAME2 = "Local\\DualSenseLED_Restore" # fallback
_win_handles = {"event": None, "mutex": None}
def _create_or_open_event():
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
CreateEventW = kernel32.CreateEventW
CreateEventW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.BOOL, wintypes.LPCWSTR]
CreateEventW.restype = wintypes.HANDLE
h = CreateEventW(None, False, False, _EVENT_NAME1)
if not h and ctypes.get_last_error() != 0:
h = CreateEventW(None, False, False, _EVENT_NAME2)
return h
def _open_event_for_set():
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
OpenEventW = kernel32.OpenEventW
OpenEventW.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.LPCWSTR]
OpenEventW.restype = wintypes.HANDLE
EVENT_MODIFY_STATE = 0x0002
h = OpenEventW(EVENT_MODIFY_STATE, False, _EVENT_NAME1)
if not h and ctypes.get_last_error() != 0:
h = OpenEventW(EVENT_MODIFY_STATE, False, _EVENT_NAME2)
return h
def _set_event(h):
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
SetEvent = kernel32.SetEvent
SetEvent.argtypes = [ctypes.c_void_p]
SetEvent.restype = ctypes.c_bool
try:
SetEvent(h)
except Exception:
pass
def _wait_event_loop(cb_restore):
import ctypes, time
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
WaitForSingleObject = kernel32.WaitForSingleObject
WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
WaitForSingleObject.restype = wintypes.DWORD
_win_handles["event"] = _create_or_open_event()
if not _win_handles["event"]:
return
INFINITE = 0xFFFFFFFF
while True:
r = WaitForSingleObject(_win_handles["event"], INFINITE)
try:
cb_restore()
except Exception:
pass
time.sleep(0.05)
def _secondary_instance_restore_and_exit():
# Belt-and-suspenders: ping the kernel restore event AND drop the restore.signal
# file. The running instance restores on either path, so if its event-wait
# thread is wedged the 1s file poll still brings the window back — this is what
# fixes "I had to double-click the shortcut several times before it appeared".
h = _open_event_for_set()
if h:
_set_event(h)
_signal_restore_request()
def _acquire_global_mutex():
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
CreateMutexW = kernel32.CreateMutexW
CreateMutexW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.LPCWSTR]
CreateMutexW.restype = wintypes.HANDLE
h = CreateMutexW(None, False, _MUTEX_NAME)
_win_handles["mutex"] = h
# ERROR_ALREADY_EXISTS = 183
return ctypes.get_last_error() != 183
# -- Signal the running instance to restore (file-based ping)
def _signal_restore_request():
try:
(CONFIG_DIR / "restore.signal").write_text("1", encoding="utf-8")
except Exception as e:
log("signal restore err:", e)
# -- Strong Windows single-instance guard (keyed by EXE path so different copies don't conflict)
def _instance_already_running() -> bool:
if os.name != "nt":
return False
import ctypes
from ctypes import wintypes
exe_path = os.path.abspath(sys.argv[0]).lower()
key = hashlib.sha1(exe_path.encode("utf-8")).hexdigest()[:8]
name = f"Global\\{APP_NAME}_SingleInstance_{key}"
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
CreateMutexW = kernel32.CreateMutexW
CreateMutexW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.LPCWSTR]
CreateMutexW.restype = wintypes.HANDLE
handle = CreateMutexW(None, False, name)
# ERROR_ALREADY_EXISTS = 183
return ctypes.get_last_error() == 183
exe_path = os.path.abspath(sys.argv[0]).lower()
key = hashlib.sha1(exe_path.encode("utf-8")).hexdigest()[:8]
name = f"Global\\{APP_NAME}_SingleInstance_{key}"
# Try with pywin32 if available
try:
import win32event, win32api, winerror
h = win32event.CreateMutex(None, False, name)
return win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS
except Exception:
pass
# Fallback to ctypes
try:
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
CreateMutexW = kernel32.CreateMutexW
CreateMutexW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.LPCWSTR]
CreateMutexW.restype = wintypes.HANDLE
handle = CreateMutexW(None, False, name)
# ERROR_ALREADY_EXISTS = 183
return ctypes.get_last_error() == 183
except Exception:
return False
# -- Strong Windows single-instance guard (works even after packaging to EXE)
def _win_mutex_already_running() -> bool:
if os.name != "nt":
return False
try:
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
CreateMutexW = kernel32.CreateMutexW
GetLastError = kernel32.GetLastError
CreateMutexW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.LPCWSTR]
CreateMutexW.restype = wintypes.HANDLE
handle = CreateMutexW(None, False, f"Global\\{APP_NAME}_SingleInstance")
# ERROR_ALREADY_EXISTS = 183
return ctypes.get_last_error() == 183
except Exception:
return False
_lock_fp = None; _lock_path = None
def acquire_slot_lock(max_instances:int) -> bool:
global _lock_fp, _lock_path
for i in range(1, max_instances+1):
path = CONFIG_DIR / f"app.slot{i}.lock"
try:
fp = open(path, "w")
if os.name == "nt":
import msvcrt; msvcrt.locking(fp.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl; fcntl.flock(fp, fcntl.LOCK_EX|fcntl.LOCK_NB)
fp.write(str(os.getpid())); fp.flush()
_lock_fp, _lock_path = fp, path
return True
except Exception:
try: fp.close()
except Exception: pass
continue
print(f"{APP_NAME}: already {max_instances} instance(s) running. Exiting.")
return False
def release_slot_lock():
global _lock_fp, _lock_path
try:
if _lock_fp:
if os.name == "nt":
import msvcrt; msvcrt.locking(_lock_fp.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl; fcntl.flock(_lock_fp, fcntl.LOCK_UN)
_lock_fp.close()
if _lock_path:
try: _lock_path.unlink(missing_ok=True)
except Exception: pass
except Exception:
pass
# --------------------------- Utils ---------------------------
def clamp(x, a=0, b=255): return max(a, min(b, int(x)))
def clamp01(x): return 0.0 if x<0 else 1.0 if x>1 else x
def hex_to_rgb(hx):
hx = hx.strip().lstrip("#")
if len(hx)==3: hx="".join(c*2 for c in hx)
return int(hx[0:2],16), int(hx[2:4],16), int(hx[4:6],16)
def rgb_to_hex(rgb): r,g,b=[clamp(v) for v in rgb]; return f"#{r:02x}{g:02x}{b:02x}"
# --------------------------- Backend ---------------------------
class Backend:
"""PS5 (dualsense-controller/pydualsense) + PS4 USB (hidapi) — auto-detect"""
def __init__(self, prefer="auto"):
self.prefer=prefer; self.kind=None; self.dev=None; self.ds4=None
def _connect_ds4_usb(self):
try:
import hid
except Exception as e:
log(f"hidapi not available: {e}"); return False
try:
VID = 0x054C
PIDs = [0x05C4, 0x09CC, 0x0BA0]
for d in hid.enumerate(VID, 0):
if d.get('product_id') in PIDs:
self.ds4 = hid.device()
self.ds4.open_path(d['path'])
self.ds4.set_nonblocking(True)
self.kind = 'ds4'
log(f"DS4 connected: PID={hex(d.get('product_id'))}")
return True
except Exception as e:
log(f"ds4 connect fail: {e}")
return False
def connect(self)->bool:
if self.prefer in ("auto","dualsense-controller"):
try:
import dualsense_controller as dsc
self.dev=dsc.DualSenseController(); self.dev.connect()
self.kind="dsc"; return True
except Exception as e: log(f"dsc connect fail: {e}")
if self.prefer=="dualsense-controller": return False
if self.prefer in ("auto","pydualsense"):
try:
from pydualsense import pydualsense as PDS
self.dev=PDS(); self.dev.init(); self.kind="pds"; return True
except Exception as e: log(f"pds connect fail: {e}")
if self.prefer in ("auto","ds4"):
if self._connect_ds4_usb():
return True
return False
def set_color(self, r,g,b):
r=int(max(0,min(255,r))); g=int(max(0,min(255,g))); b=int(max(0,min(255,b)))
if CFG.get("bgr_swap"): r,g,b = b,g,r
try:
if self.kind=="ds4":
try:
buf = bytearray(32); buf[0]=0x05; buf[1]=0xFF; buf[6]=r; buf[7]=g; buf[8]=b
self.ds4.write(bytes(buf))
except Exception:
try:
buf = bytearray(33); buf[0]=0x00; buf[1]=0x05; buf[2]=0xFF; buf[7]=r; buf[8]=g; buf[9]=b
self.ds4.write(bytes(buf))
except Exception as e:
log(f"ds4 set_color fail: {e}")
return
if self.kind=="dsc":
for payload in [(r,g,b),(r/255.0,g/255.0,b/255.0)]:
try: self.dev.set_light_color(*payload); return
except Exception: pass
try: self.dev.lightbar.set_color(r,g,b); return
except Exception: pass
elif self.kind=="pds":
try: self.dev.light.setColorI(r,g,b); return
except Exception: pass
except Exception as e: log(f"set_color err: {e}")
# ---- battery
@staticmethod
def _norm_batt(v):
try:
if v is None or isinstance(v,bool): return None
if isinstance(v,(int,float)):
x=float(v)
if 0<=x<=1: return int(round(x*100))
if 0<=x<=10: return int(round(x*10))
return int(max(0,min(100,round(x))))
if isinstance(v,str):
s=v.strip().rstrip("%").strip(); return Backend._norm_batt(float(s))
except Exception: pass
return None
@staticmethod
def _scan_props(obj):
out = []
import inspect
for n in dir(obj):
if n.startswith("_"): continue
try:
v = getattr(obj, n)
if callable(v) and len(inspect.signature(v).parameters)==0:
try: v=v()
except Exception: continue
if isinstance(v,(int,float,bool,str)): out.append((n,v))
except Exception: continue
return out
def get_battery(self):
if self.kind=="ds4" or not self.dev: return None, False
if self.kind=="pds":
try:
batt = getattr(self.dev, "battery", None)
if batt is not None:
bf = CFG.get("pds_batt_field"); cf = CFG.get("pds_charge_field")
if bf:
try:
v = getattr(batt, bf); v=v() if callable(v) else v
p = Backend._norm_batt(v)
except Exception: p=None
else: p=None
ch=False
if cf:
try:
c=getattr(batt,cf); ch=bool(c() if callable(c) else c)
except Exception: ch=False
if p is None:
best=None; chname=None
for n,val in Backend._scan_props(batt):
if Backend._norm_batt(val) is not None: best=n; break
for n,val in Backend._scan_props(batt):
if isinstance(val,bool): chname=n; break
if best:
CFG["pds_batt_field"]=best
if chname: CFG["pds_charge_field"]=chname
save_cfg(CFG)
vv=getattr(batt,best); vv=vv() if callable(vv) else vv
p=Backend._norm_batt(vv)
ch=bool(getattr(batt,chname)) if chname else False
return p, ch
except Exception as e:
log("pds batt err:", e)
# dualsense-controller أو أخرى
try:
cand=["state.battery","state.Battery","state.get_battery()","battery","get_battery()",
"get_battery_level()","battery_level","battery_percentage","get_battery_percent()"]
ch_cand=["state.charging","state.is_charging","state.is_charging()","is_charging","charging"]
def _safe_get(obj, names):
for name in names:
try:
cur=obj
for seg in name.split("."):
if seg.endswith("()"): cur=getattr(cur, seg[:-2])()
else: cur=getattr(cur, seg)
return cur
except Exception: continue
return None
b=_safe_get(self.dev,cand); ch=_safe_get(self.dev,ch_cand)
return Backend._norm_batt(b), bool(ch)
except Exception as e:
log("batt read err:", e); return None, False
def close(self):
try:
if self.kind=="pds": self.dev.close()
except Exception: pass
# --------------------------- EMA ---------------------------
class EMA:
def __init__(self, alpha=0.35): self.a=alpha; self.v=None
def update(self, x):
if x is None: return None
self.v = float(x) if self.v is None else self.a*float(x)+(1-self.a)*self.v
return int(self.v+0.5)
# --------------------------- Engine ---------------------------
class Engine(threading.Thread):
def __init__(self, backend: Backend):
super().__init__(daemon=True)
self.b=backend; self.stop_evt=threading.Event()
self.mode=CFG.get("last_mode","Manual")
if self.mode not in MODE_CODE: self.mode="Manual"
self._seq_i=None
self.speed=float(CFG.get("speed",1.0))
self.rb=float(CFG.get("rainbow_brightness",0.9))
self.duty=float(CFG.get("flash_duty",0.5))
self.color_hex=CFG.get("color","#00aaff")
self.color=hex_to_rgb(self.color_hex)
self._ol = threading.Lock(); self.out = self.color
self._last_apply = 0.0 # 0 = أول إرسال يتم فورًا
# ---- profiles helpers
def snapshot(self):
return {"mode":self.mode,"speed":self.speed,"rainbow_brightness":self.rb,"flash_duty":self.duty,"color":rgb_to_hex(self.color)}
def load_from(self, snap:dict):
try:
self.set_mode(snap.get("mode", self.mode))
self.set_speed(snap.get("speed", self.speed))
self.set_rb(snap.get("rainbow_brightness", self.rb))
self.set_duty(snap.get("flash_duty", self.duty))
self.set_color(hex_to_rgb(snap.get("color", rgb_to_hex(self.color))))
except Exception: pass
def _send(self, rgb):
try:
r,g,b = rgb
self.b.set_color(r,g,b)
with self._ol:
self.out = (int(r),int(g),int(b))
self._last_apply = time.time()
except Exception as e:
log("engine send err:", e)
def set_mode(self,m):
# وضع غير معروف (config محرَّر يدويًا/تالف) → Manual، وإلا حلقة التشغيل تدور بلا نوم
self.mode = m if m in MODE_CODE else "Manual"
self._seq_i = None
CFG["last_mode"]=self.mode; save_cfg(CFG)
def set_speed(self,v): self.speed=float(v); CFG["speed"]=self.speed; save_cfg_throttled(CFG)
def set_rb(self,v): self.rb=float(v); CFG["rainbow_brightness"]=self.rb; save_cfg_throttled(CFG)
def set_duty(self,v): self.duty=float(v); CFG["flash_duty"]=self.duty; save_cfg_throttled(CFG)
def set_color(self,rgb):
self.color=tuple(int(c) for c in rgb); CFG["color"]=rgb_to_hex(self.color); save_cfg_throttled(CFG)
if self.mode=="Manual": self._send(self.color)
# ---- run loop
def run(self):
t0=time.time(); i=0
while not self.stop_evt.is_set():
try:
m=self.mode; s=self.speed; rb=self.rb; c=self.color; duty=self.duty
if m=="Manual":
# اللون ثابت → أرسل فقط عند التغيّر + نبضة تثبيت كل ثانيتين
# (set_color يرسل فورًا عند التغيير، فالحلقة هنا للتثبيت فقط → نوم أطول)
with self._ol: cur = self.out
if tuple(c) != tuple(cur) or (time.time() - self._last_apply) > 2.0:
self._send(c)
time.sleep(0.25)
elif m=="Battery":
# لون تلقائي حسب الشحن: أخضر ≥60، برتقالي ≥30، أحمر أقل — ونبض أثناء الشحن
now=time.time()
if now - getattr(self,"_batt_t",0.0) > 5.0:
try: bp,bch = self.b.get_battery()
except Exception: bp,bch = None,False
self._batt_t=now; self._batt_p=bp; self._batt_ch=bch
bp = getattr(self,"_batt_p",None)
if bp is None: col=(180,180,180)
elif bp>=60: col=(34,197,94)
elif bp>=30: col=(245,158,11)
else: col=(239,68,68)
if getattr(self,"_batt_ch",False):
k=0.55+0.45*(0.5+0.5*math.sin(time.time()*2.2))
col=tuple(int(x*k) for x in col)
self._send(col); time.sleep(0.5)
elif m=="Sequence":
pal=[(255,40,40),(40,200,90),(40,130,255),(160,60,255),(255,255,255),(0,0,0)]
idx=int((time.time()-t0)//max(0.1,s))%len(pal)
if idx != self._seq_i:
self._send(pal[idx]); self._seq_i=idx
time.sleep(1/30)
elif m=="Random":
if i%int(max(1,s*30))==0:
self._send((random.randint(0,255),random.randint(0,255),random.randint(0,255)))
time.sleep(1/30)
elif m=="Rainbow":
cyc=max(0.2,s); u=((time.time()-t0)%cyc)/cyc
r,g,b=[int(255*x) for x in colorsys.hsv_to_rgb(u,1.0,clamp01(rb))]
self._send((r,g,b)); time.sleep(1/60)
elif m=="Pulse": # sinus on current color
per=max(0.2,s); u=((time.time()-t0)%per)/per; k=0.5-0.5*math.cos(2*math.pi*u)
r=int(c[0]*k); g=int(c[1]*k); b=int(c[2]*k); self._send((r,g,b)); time.sleep(1/60)
elif m=="Flash":
per=max(0.2,s); u=((time.time()-t0)%per)/per
base=c if u<duty else (0,0,0); self._send(base); time.sleep(1/60)
elif m=="Breathing":
per=max(0.8,s); u=((time.time()-t0)%per)/per; k=(1-math.cos(2*math.pi*u))*0.5
r=int(c[0]*k); g=int(c[1]*k); b=int(c[2]*k); self._send((r,g,b)); time.sleep(1/60)
elif m=="Heartbeat": # double pulse
per=max(0.8,s); u=((time.time()-t0)%per)/per
k = (1 if u<0.05 else 0.6 if u<0.1 else 1 if 0.3<u<0.35 else 0) # نبضتان سريعتان
r=int(c[0]*k); g=int(c[1]*k); b=int(c[2]*k); self._send((r,g,b)); time.sleep(1/60)
elif m=="Wave": # موجة لونية عبر Hue
cyc=max(0.8,s); u=((time.time()-t0)%cyc)/cyc
r,g,b=[int(255*x) for x in colorsys.hsv_to_rgb(u,0.8,clamp01(rb))]
self._send((r,g,b)); time.sleep(1/60)
elif m=="Gradient": # بين لون ثابت وأبيض
cyc=max(0.8,s); u=((time.time()-t0)%cyc)/cyc; k=0.5-0.5*math.cos(2*math.pi*u)
r=int(c[0]*(1-k)+255*k); g=int(c[1]*(1-k)+255*k); b=int(c[2]*(1-k)+255*k)
self._send((r,g,b)); time.sleep(1/60)
else:
# حزام أمان: وضع غير معروف لا يجوز أن يدوّر الحلقة بلا نوم
time.sleep(0.1)
# Auto Sleep
if CFG.get("auto_sleep",{}).get("enabled", False):
idle = time.time() - self._last_apply
mins = max(1, int(CFG["auto_sleep"].get("minutes",30)))
if idle > mins*60:
act = CFG["auto_sleep"].get("action","off")
if act=="off": self._send((0,0,0))
else: self._send(self.color)
# بعدها ننتظر ثانية لئلا نستهلك CPU
time.sleep(1.0)
i+=1
except Exception as e:
log("engine loop err:", e); time.sleep(0.2)
# --------------------------- Background (headless) ---------------------------
STOP_SIGNAL = CONFIG_DIR / "stop.signal"
def run_background(off_on_exit=False, stop_after_min=None):
log("BG: start")
backend = Backend(prefer=CFG.get("backend","auto"))
if not backend.connect():
log("BG: controller not found"); return
engine = Engine(backend); engine.start()
engine.set_color(hex_to_rgb(CFG.get("color","#00aaff")))
stop_evt = threading.Event()
# Clear any stale stop signal so the new instance doesn't exit immediately.
try: STOP_SIGNAL.unlink(missing_ok=True)
except Exception: pass
# Graceful shutdown on taskkill (no /F), logoff, Ctrl+Break — exits through
# the finally block so the lightbar is cleaned up.
def _on_signal(*_a):
stop_evt.set()
for _sig in ("SIGTERM", "SIGINT", "SIGBREAK"):
try:
import signal as _signal
s = getattr(_signal, _sig, None)
if s is not None: _signal.signal(s, _on_signal)
except Exception:
pass
def battery_logger():
ema = EMA(0.35)
while not stop_evt.is_set():
p,ch = backend.get_battery(); p2 = ema.update(p)
if p2 is not None: log(f"BG: battery={p2}% charging={ch}")
time.sleep(60)
def timer():
if stop_after_min is None: return
time.sleep(max(0,float(stop_after_min))*60); stop_evt.set()
threading.Thread(target=battery_logger, daemon=True).start()
threading.Thread(target=timer, daemon=True).start()
try:
while not stop_evt.is_set():
# Stop channel: a companion '--stop' launch (or the Stop shortcut)
# drops this file so a non-technical user can halt the hidden process.
if STOP_SIGNAL.exists():
try: STOP_SIGNAL.unlink(missing_ok=True)
except Exception: pass
log("BG: stop signal received")
break
time.sleep(0.5)
finally:
try: engine.stop_evt.set()
except Exception: pass
if off_on_exit:
try: backend.set_color(0,0,0)
except Exception: pass
try: backend.close()
except Exception: pass
log("BG: stop")
# --------------------------- Starfield ---------------------------
class Starfield(tk.Canvas):
def __init__(self, master, count=110, **kw):
super().__init__(master, highlightthickness=0, bd=0, **kw)
self.count=count; self.stars=[]; self.running=False; self._after=None
def start(self):
if self.running: return
self.running=True; self._schedule()
def _schedule(self, delay=40):
if not self.running or not self.winfo_exists(): return
self._after=self.after(delay, self._tick) # ~25 FPS وهو ظاهر، ~2Hz وهو خامل
def _idle(self):
try:
if not self.winfo_viewable(): return True
return self.winfo_toplevel().focus_displayof() is None
except Exception:
return False
def _tick(self):
if not self.running or not self.winfo_exists(): return
idle = False
try:
# مخفي أو التطبيق بلا تركيز (داخل لعبة)؟ لا رسم — صفر استهلاك
idle = self._idle()
if idle:
return
w=self.winfo_width(); h=self.winfo_height()
if not self.stars:
for _ in range(self.count):
x=random.random()*w; y=random.random()*h; r=random.random()*1.8+0.5; sp=random.random()*0.8+0.2
self.stars.append([x,y,r,sp])
self.delete("all")
for s in self.stars:
s[1]+=s[3]
if s[1]>h: s[1]=0
x,y,r,_=s; self.create_oval(x-r,y-r,x+r,y+r, fill="#6f7aa7", outline="")
finally:
self._schedule(500 if idle else 40)
def stop(self):
self.running=False
try:
if self._after is not None: self.after_cancel(self._after)
except Exception: pass
# --------------------------- DualSense SVG asset (accurate 2D view) ---------------------------
# يُحمَّل من assets/dualsense-svgrepo.svg (أيقونة line-art مرخّصة من SVG Repo، viewBox 128x128).
# التحليل: 23 مسارًا، أوامر M/L/C/H/V/Z كبيرة فقط. لو الملف مفقود/تغيّر → نرجع للعرض 3D تلقائيًا.
def _flatten_cubic(p0, c1, c2, p1, steps=12):
"""تحويل منحنى Bezier تكعيبي إلى نقاط مستقيمة."""
pts = []
for i in range(1, steps + 1):
t = i / steps
mt = 1.0 - t
a = mt * mt * mt; b = 3 * mt * mt * t; c = 3 * mt * t * t; d = t * t * t
pts.append((a * p0[0] + b * c1[0] + c * c2[0] + d * p1[0],
a * p0[1] + b * c1[1] + c * c2[1] + d * p1[1]))
return pts
def _parse_svg_path_d(d):
"""يفكّك خاصية d (أوامر مطلقة M/L/C/H/V/Z فقط) إلى قائمة subpaths من النقاط."""
toks = re.findall(r"[A-Za-z]|-?\d*\.?\d+(?:[eE][-+]?\d+)?", d)
subs, cur = [], []
x = y = 0.0
i = 0
cmd = None
n = len(toks)
need = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6}
while i < n:
t = toks[i]
if t.isalpha():
if t not in "MLCHVZ":
return None # أمر غير مدعوم (نسبي/قوس) → فشل آمن
cmd = t; i += 1
if cmd == "Z":
if cur: subs.append(cur)
cur = []
continue
# معاملات ناقصة في نهاية السلسلة → فشل آمن بدل IndexError
if cmd in need and i + need[cmd] > n:
return None
if cmd == "M":
x, y = float(toks[i]), float(toks[i + 1]); i += 2
if cur: subs.append(cur)
cur = [(x, y)]
cmd = "L" # إحداثيات لاحقة بعد M تُعامل كـ L
elif cmd == "L":
x, y = float(toks[i]), float(toks[i + 1]); i += 2
cur.append((x, y))
elif cmd == "H":
x = float(toks[i]); i += 1
cur.append((x, y))
elif cmd == "V":
y = float(toks[i]); i += 1
cur.append((x, y))
elif cmd == "C":
c1 = (float(toks[i]), float(toks[i + 1]))
c2 = (float(toks[i + 2]), float(toks[i + 3]))
p1 = (float(toks[i + 4]), float(toks[i + 5])); i += 6
cur.extend(_flatten_cubic((x, y), c1, c2, p1))
x, y = p1
else:
return None
if cur: subs.append(cur)
return subs
# فهرسة مكوّنات الأيقونة (ثابتة لهذا الأصل تحديدًا — تحقّق منها محلّل مسارات مستقل)
_DS_IDX = {
"touch": 0, "body": 1, "btn_tri": 2, "btn_cross": 3, "btn_sq": 4,
"well_r": 5, "well_l": 6, "cap_l": 7, "cap_r": 8, "r1": 9, "l1": 10,
"wing_r": 11, "wing_l": 12, "btn_circ": 13, "mute": 14,
"dp_down": 15, "dp_up": 16, "dp_left": 17, "dp_right": 18,
"opts": 19, "create": 20, "grille2": 21, "grille1": 22,
}
# محور شريط الإضاءة الأيسر — يحضن حافة التاتشباد اليسرى من زاويتها العلوية حتى السفلية
# ثم يلتف قليلًا للداخل حول الزاوية (مطابق لليد الحقيقية: الضوء لا يتجاوز التاتشباد للأسفل).
_DS_LB_LEFT = [((43.4, 28.8), (42.0, 31.0), (41.3, 34.0), (41.4, 37.5)),
((41.4, 37.5), (41.9, 41.0), (42.7, 44.5), (43.4, 47.5)),
((43.4, 47.5), (43.9, 49.8), (44.6, 51.7), (45.8, 52.9)),
((45.8, 52.9), (46.4, 53.5), (47.0, 53.8), (47.8, 53.9))]
def _ds_lightbar_polylines():
left = []
for seg in _DS_LB_LEFT:
if not left: left.append(seg[0])
left.extend(_flatten_cubic(*seg, steps=8))
right = [(128.0 - x, y) for (x, y) in left]
return left, right
_DS_SVG = {"tried": False, "geo": None}
def _load_dualsense_svg():
"""تحميل وتفكيك الأيقونة مرة واحدة. None لو الأصل مفقود أو بنيته غير متوقعة."""
if _DS_SVG["tried"]:
return _DS_SVG["geo"]
_DS_SVG["tried"] = True
try:
here = Path(__file__).resolve().parent
p = here / "assets" / "dualsense-svgrepo.svg"
if not p.exists():
log("dualsense svg asset missing:", p)
return None
txt = p.read_text(encoding="utf-8")
ds = re.findall(r'\bd="([^"]+)"', txt)
paths = [_parse_svg_path_d(d) for d in ds]
if len(paths) != 23 or any(sp is None or not sp for sp in paths):
log("dualsense svg asset unexpected structure; falling back to 3D")
return None
lb_l, lb_r = _ds_lightbar_polylines()
_DS_SVG["geo"] = {"paths": paths, "lb": (lb_l, lb_r)}
log("dualsense svg asset loaded:", len(paths), "paths")
except Exception as e:
log("dualsense svg parse err:", e)
_DS_SVG["geo"] = None
return _DS_SVG["geo"]
# ألوان أطقم DualSense الرسمية الشهيرة — تُطبَّق على رسم اليد
_DS_SHELLS = {
"white": {"shell": (223,226,233), "line": (72,78,92), "touch": (232,234,239), "dpad": (211,215,224), "bump": (58,62,72), "btn": (52,56,66), "glyph": (158,164,176), "inset": (31,34,41)},
"black": {"shell": (45,47,54), "line": (118,124,136),"touch": (56,58,66), "dpad": (58,61,70), "bump": (28,30,36), "btn": (38,41,49), "glyph": (172,177,187), "inset": (22,24,29)},
"red": {"shell": (158,34,48), "line": (232,196,200),"touch": (176,52,66), "dpad": (146,30,44), "bump": (72,16,24), "btn": (84,22,32), "glyph": (240,214,218), "inset": (34,18,22)},
"blue": {"shell": (70,118,205), "line": (214,226,246),"touch": (92,138,218), "dpad": (62,106,188), "bump": (30,48,86), "btn": (38,58,100), "glyph": (222,232,248), "inset": (22,30,48)},
"purple": {"shell": (112,92,168), "line": (226,220,242),"touch": (128,108,184), "dpad": (102,84,156), "bump": (48,38,76), "btn": (60,48,94), "glyph": (230,224,244), "inset": (30,26,46)},
}
# --------------------------- Controller Widget ---------------------------
class Controller3D(tk.Canvas):
"""عرض يد DualSense دقيق من أصل SVG مرخّص — شريطا الإضاءة يتزامنان مع اللون الفعلي 100%."""
def __init__(self, master, controller_type="ps5", width=680, height=260, **kw):
bg = kw.pop("bg", "#0b0f14")
super().__init__(master, width=width, height=height, bg=bg, highlightthickness=0, bd=0, **kw)
self.ctrl_type = controller_type # "ps5" or "ps4"
self._led_color = (0, 170, 255) # RGB tuple — synced with engine output
self._glow_layers = 8 # عدد طبقات التوهج
self._width = width
self._height = height
self._bg = bg
self._draw_id = None
self._mode = "Manual" # active lighting mode (drives glow signature)
self._anim = 0 # free-running phase, advanced once per redraw
self.on_click = None # يضبطه App: نقرة = منتقي الألوان
self._shell = "white" # طقم ألوان اليد (أبيض/أسود/أحمر/أزرق/بنفسجي)
self.configure(cursor="hand2")
self.bind("<Configure>", self._on_resize)
self.bind("<Button-1>", self._on_click)
def _on_resize(self, event=None):
self._width = self.winfo_width()
self._height = self.winfo_height()
self.redraw()
def _on_click(self, ev):
if callable(self.on_click):
self.on_click(ev)
def set_led_color(self, r, g, b):
"""تحديث لون LED — يُستدعى كل 33ms من sync loop."""
rgb = (int(r), int(g), int(b))
# لون ثابت + وضع بلا توقيع متحرك → لا داعي لإعادة الرسم (توفير CPU)
if rgb == self._led_color and self._mode not in ("Rainbow", "Wave", "Sequence"):
return
self._led_color = rgb
self.redraw()
def set_controller_type(self, ctype):
"""توافق خلفي — العرض DualSense دائمًا (اليد الفعلية PS4 تبقى مدعومة بالتحكم)."""
self.ctrl_type = ctype
def set_mode(self, code):
"""تحديث وضع الإضاءة — يغيّر شكل/توقيع توهّج الشريط حسب الوضع المختار"""
self._mode = code or "Manual"
self.redraw()
def set_shell(self, key):
"""تبديل طقم ألوان اليد المعروضة (أطقم DualSense الرسمية)."""
if key in _DS_SHELLS and key != self._shell:
self._shell = key
self.redraw()
def _blend(self, c1, c2, t):
"""خلط لونين بنسبة t (0=c1, 1=c2)"""
return tuple(int(a + (b - a) * t) for a, b in zip(c1, c2))
def _hex(self, rgb):
return f"#{max(0,min(255,rgb[0])):02x}{max(0,min(255,rgb[1])):02x}{max(0,min(255,rgb[2])):02x}"
def _parse_bg(self):
bg = self._bg
if isinstance(bg, str) and bg.startswith("#"):
bg = bg.lstrip("#")
if len(bg) == 3:
bg = "".join(c*2 for c in bg)
return (int(bg[0:2],16), int(bg[2:4],16), int(bg[4:6],16))
return (11, 15, 20)
def redraw(self):
"""يمسح ويعيد رسم يد DualSense مع شريطي الإضاءة."""
self._anim = (self._anim + 1) % 360 # phase advances once per frame
self.delete("all")
bg = self._parse_bg()
geo = _load_dualsense_svg()
if geo is not None:
self._draw_ps5_svg(geo, bg)
else:
self._draw_fallback(bg)
def _draw_fallback(self, bg):
"""احتياط نادر (أصل SVG مفقود): كبسولة LED بسيطة بلون المحرك."""
W, H = max(1, self._width), max(1, self._height)
led = self._led_color
y = H // 2; x0, x1 = int(W * 0.25), int(W * 0.75)
th = max(8, int(H * 0.08))
for i in range(4, 0, -1):
self.create_line(x0, y, x1, y, fill=self._hex(self._blend(bg, led, 0.06 + 0.05 * (4 - i))),
width=th + i * th, capstyle=tk.ROUND)
self.create_line(x0, y, x1, y, fill=self._hex(led), width=th, capstyle=tk.ROUND)
# ==================== نظرة SVG الدقيقة (PS5) ====================
def _svg_tx(self):
"""معامل التحويل من فضاء الأيقونة 128 إلى فضاء الكانفس: (scale, ox, oy)."""
W, H = max(1, self._width), max(1, self._height)
s = min(W * 0.86 / 113.0, H * 0.86 / 75.0)
return s, W / 2.0 - 64.0 * s, H / 2.0 - 64.0 * s
def _poly(self, pts, s, ox, oy):
out = []
for (x, y) in pts:
out.append(ox + x * s); out.append(oy + y * s)
return out
def _draw_ps5_svg(self, geo, bg):
led = self._led_color
s, ox, oy = self._svg_tx()
P = geo["paths"]; I = _DS_IDX
lw = max(1, round(s * 0.5)) # سماكة خطوط الأيقونة
pal = _DS_SHELLS.get(self._shell, _DS_SHELLS["white"])
LINE = self._hex(pal["line"])
SHELL = pal["shell"]
body = P[I["body"]][0]
# ملاحظة: مسار الجسم يعبر جسرًا مزدوجًا في المنتصف → قاعدة even-odd تُفرغ المقبضين،
# لذا نكمل التعبئة بمخططي الجناحين (wing_l/wing_r) اللذين يغطيان المقبضين بالكامل.
wing_l = P[I["wing_l"]][0]; wing_r = P[I["wing_r"]][0]
# (1) ظل خفيف تحت الجسم
SHC = self._hex(self._blend(bg, (0, 0, 0), 0.5))
for part in (body, wing_l, wing_r):
sh = self._poly([(x + 1.6, y + 2.2) for (x, y) in part], s, ox, oy)
self.create_polygon(sh, fill=SHC, outline="")
# (2) الهيكل الأبيض (سيلويت الجسم + الجناحان/المقبضان)
for part in (body, wing_l, wing_r):
self.create_polygon(self._poly(part, s, ox, oy), fill=self._hex(SHELL), outline="")
# (3) القسم الداكن الأوسط حول العصوين (سمة DualSense المميزة)
self._ps5_center_inset(s, ox, oy, pal["inset"])
# (4) سطح التاتشباد — أبيض مع غسلة خفيفة من لون LED
touch = P[I["touch"]][0]
self.create_polygon(self._poly(touch, s, ox, oy),
fill=self._hex(self._blend(pal["touch"], led, 0.08)), outline="")
# (5) شريطا الإضاءة يحضنان حافتي التاتشباد + خط الانتشار على حافته السفلية (البطل)
lb_l, lb_r = geo["lb"]
th = max(3, round(s * 1.2))
self._draw_lightbar_strip(self._poly(lb_l, s, ox, oy), led, bg, th, 0)
self._draw_lightbar_strip(self._poly(lb_r, s, ox, oy), led, bg, th, 1)
# خط انتشار الضوء أسفل التاتشباد (يظهر أبيض متوهّج بلمسة من لون LED كما في العتاد)
dy0 = oy + 54.15 * s
dx0, dx1 = ox + 48.6 * s, ox + 79.4 * s
self.create_line(dx0, dy0, dx1, dy0, fill=self._hex(self._blend(SHELL, led, 0.35)),
width=max(2, round(s * 0.7)), capstyle=tk.ROUND)
self.create_line(dx0, dy0, dx1, dy0, fill=self._hex(self._blend(led, (255, 255, 255), 0.72)),
width=max(1, round(s * 0.3)), capstyle=tk.ROUND)