-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbridge.py
More file actions
2616 lines (2397 loc) · 110 KB
/
Copy pathbridge.py
File metadata and controls
2616 lines (2397 loc) · 110 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
"""Local Windows HID bridge for the DualSense VibeCoding Hub USB path.
The bridge reads DualSense USB input reports, injects configured keyboard
shortcuts through SendInput, and owns status-light output. Bluetooth DualSense
packets use different report layouts and are deliberately not handled here.
"""
from __future__ import annotations
import ctypes
import json
import math
import os
import secrets
import socket
import struct
import threading
import time
import uuid
from ctypes import wintypes
from collections.abc import Callable
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import unquote, urlparse
from approval_detection import has_escalated_shell_request
HOST = "127.0.0.1"
PORT = 37845
APP_DIR = os.path.dirname(os.path.abspath(__file__))
WEB_PORT = 4173
RELEASE_VERSION = "0.1.1"
ALLOWED_WEB_ORIGINS = {"http://127.0.0.1:4173", "http://localhost:4173"}
POST_PATHS = {
"/api/lighting", "/api/mapping", "/api/codex-lighting",
"/api/codex-hook", "/api/haptics", "/api/triggers", "/api/key-capture",
}
BRIDGE_TOKEN_PATH = os.environ.get("DS5VIBEHUB_TOKEN_PATH", "").strip() or os.path.join(
os.environ.get("LOCALAPPDATA", APP_DIR), "DS5VibeHub", "bridge.token"
)
BRIDGE_AUTH_TOKEN = ""
SONY_VENDOR_ID = 0x054C
DS5_USB_REPORT_ID = 0x02
DS5_USB_OUTPUT_LENGTH = 48 # Includes the report ID byte.
DS5_VALID_FLAG0_COMPATIBLE_VIBRATION = 0x01
DS5_VALID_FLAG0_HAPTICS_SELECT = 0x02
DS5_VALID_FLAG0_RIGHT_TRIGGER = 0x04
DS5_VALID_FLAG0_LEFT_TRIGGER = 0x08
DS5_VALID_FLAG1_LIGHTBAR = 0x04
DS5_VALID_FLAG1_PLAYER_LEDS = 0x10
DS5_TRIGGER_EFFECT_OFF = 0x00
DS5_TRIGGER_EFFECT_FEEDBACK = 0x21
DS5_TRIGGER_EFFECT_WEAPON = 0x25
VIRTUAL_TOUCHPAD_VENDOR_ID = 0x1209
VIRTUAL_TOUCHPAD_PRODUCT_ID = 0xD505
VIRTUAL_TOUCHPAD_USAGE_PAGE = 0xFF00
VIRTUAL_TOUCHPAD_REPORT_ID = 0x09
VIRTUAL_TOUCHPAD_REPORT_LENGTH = 50
VIRTUAL_TOUCHPAD_CONTACTS = 4
VIRTUAL_TOUCHPAD_REPORT_SLOTS = 5
VIRTUAL_TOUCHPAD_FRAME_SECONDS = 0.007
VIRTUAL_TOUCHPAD_MOVE_STEPS = 10
DIGCF_PRESENT = 0x00000002
DIGCF_DEVICEINTERFACE = 0x00000010
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
OPEN_EXISTING = 3
FILE_ATTRIBUTE_NORMAL = 0x00000080
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
ERROR_NO_MORE_ITEMS = 259
ERROR_INSUFFICIENT_BUFFER = 122
HIDP_STATUS_SUCCESS = 0x00110000
FRAME_INTERVAL_SECONDS = 1 / 60
BLINK_PERIOD_SECONDS = (2.0, 1.6, 1.2, 0.8, 0.55)
BREATHE_PERIOD_SECONDS = (5.0, 4.0, 3.2, 2.4, 1.7)
HAPTIC_PULSE_END_SECONDS = 0.09
HAPTIC_SECOND_PULSE_START_SECONDS = 0.19
HAPTIC_SECOND_PULSE_END_SECONDS = 0.28
HAPTIC_SETTLE_END_SECONDS = 0.36
HAPTIC_RIGHT_MOTOR = 45
HAPTIC_LEFT_MOTOR = 20
RECOIL_STRIKE_END_SECONDS = 0.045
RECOIL_SETTLE_END_SECONDS = 0.075
RECOIL_PRIORITY_HOLDOFF_SECONDS = 0.6
RECOIL_RIGHT_MOTOR = 255
RECOIL_LEFT_MOTOR = 80
CODEX_HOOK_STALE_SECONDS = 30 * 60
# Do not infer turn completion from a quiet interval. Long-running tools and
# model reasoning can legitimately produce no records for minutes. Explicit
# Stop/task_complete events close turns; the stale-session limit is only a
# last-resort cleanup for abandoned sessions.
CODEX_SESSION_FALLBACK_ENABLED = True
CODEX_SESSION_ROOT = os.path.join(os.path.expanduser("~"), ".codex", "sessions")
CODEX_SESSION_POLL_SECONDS = 0.35
# Session JSONL is only a compatibility source. A synthetic approval must
# never outlive the short window in which the session can actually be waiting.
# A structured approval remains pending until its matching call output, Stop,
# or normal stale-session cleanup. Real approvals can legitimately wait much
# longer than a few seconds while the user reviews the request.
CODEX_FALLBACK_APPROVAL_MAX_SECONDS = CODEX_HOOK_STALE_SECONDS
CODEX_LIGHT_PROFILES = {
"approval": {
"lightbar": {"red": 255, "green": 196, "blue": 0, "brightness": 100},
"playerLeds": 0x1F,
"effect": "blink",
"speed": 4,
},
"working": {
"lightbar": {"red": 255, "green": 54, "blue": 67, "brightness": 100},
"playerLeds": 0x04,
"effect": "breathe",
"speed": 3,
},
"idle": {
"lightbar": {"red": 44, "green": 204, "blue": 113, "brightness": 85},
"playerLeds": 0x04,
"effect": "static",
"speed": 3,
},
}
INPUT_KEYBOARD = 1
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_SCANCODE = 0x0008
MAPVK_VK_TO_VSC_EX = 4
WH_KEYBOARD_LL = 13
HC_ACTION = 0
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
WM_SYSKEYDOWN = 0x0104
WM_SYSKEYUP = 0x0105
WM_QUIT = 0x0012
LLKHF_EXTENDED = 0x01
LLKHF_INJECTED = 0x10
KEY_CAPTURE_TIMEOUT_SECONDS = 15.0
DS5_BUTTONS = (
"dpad_up", "dpad_right", "dpad_down", "dpad_left",
"square", "cross", "circle", "triangle",
"l1", "r1", "l2", "r2", "create", "options", "l3", "r3",
"ps", "touchpad", "mute",
"left_stick_up", "left_stick_right", "left_stick_down", "left_stick_left",
"right_stick_up", "right_stick_right", "right_stick_down", "right_stick_left",
)
STICK_DIRECTION_INPUTS = frozenset(DS5_BUTTONS[-8:])
STICK_DIRECTION_ORDER = {
"left": ("left_stick_up", "left_stick_right", "left_stick_down", "left_stick_left"),
"right": ("right_stick_up", "right_stick_right", "right_stick_down", "right_stick_left"),
}
STICK_ACTIVATION_THRESHOLD = 0.68
STICK_RELEASE_THRESHOLD = 0.42
DEFAULT_TOUCHPAD_GESTURES = {
"enabled": True,
"threshold": 320,
"muteOnSwitch": False,
}
TOUCHPAD_GESTURE_SHORTCUTS = {
"left": ["MetaLeft", "ControlLeft", "ArrowLeft"],
"right": ["MetaLeft", "ControlLeft", "ArrowRight"],
}
VK_CODES = {
"Backspace": 0x08, "Tab": 0x09, "Enter": 0x0D, "ShiftLeft": 0xA0,
"ShiftRight": 0xA1, "ControlLeft": 0xA2, "ControlRight": 0xA3,
"AltLeft": 0xA4, "AltRight": 0xA5, "Pause": 0x13, "CapsLock": 0x14,
"Escape": 0x1B, "Space": 0x20, "PageUp": 0x21, "PageDown": 0x22,
"End": 0x23, "Home": 0x24, "ArrowLeft": 0x25, "ArrowUp": 0x26,
"ArrowRight": 0x27, "ArrowDown": 0x28, "PrintScreen": 0x2C,
"Insert": 0x2D, "Delete": 0x2E, "MetaLeft": 0x5B, "MetaRight": 0x5C,
"ContextMenu": 0x5D, "NumLock": 0x90, "ScrollLock": 0x91,
"Semicolon": 0xBA, "Equal": 0xBB, "Comma": 0xBC, "Minus": 0xBD,
"Period": 0xBE, "Slash": 0xBF, "Backquote": 0xC0,
"BracketLeft": 0xDB, "Backslash": 0xDC, "BracketRight": 0xDD,
"Quote": 0xDE, "NumpadMultiply": 0x6A, "NumpadAdd": 0x6B,
"NumpadSubtract": 0x6D, "NumpadDecimal": 0x6E, "NumpadDivide": 0x6F,
"NumpadEnter": 0x0D, "VolumeMute": 0xAD,
}
VK_CODES.update({f"Key{letter}": ord(letter) for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"})
VK_CODES.update({f"Digit{digit}": ord(digit) for digit in "0123456789"})
VK_CODES.update({f"F{number}": 0x6F + number for number in range(1, 13)})
VK_CODES.update({f"Numpad{digit}": 0x60 + digit for digit in range(10)})
# NumpadEnter shares a VK with Enter; hook reports need the extended flag to
# tell them apart. Keep the ordinary key as the default reverse lookup.
HOOK_CODES_BY_VK = {value: key for key, value in VK_CODES.items() if key != "NumpadEnter"}
MODIFIER_KEY_ORDER = (
"ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight",
"AltLeft", "AltRight", "MetaLeft", "MetaRight",
)
MODIFIER_KEY_CODES = frozenset(MODIFIER_KEY_ORDER)
EXTENDED_CODES = {
"ControlRight", "AltRight", "MetaLeft", "MetaRight", "ContextMenu",
"Insert", "Delete", "Home", "End", "PageUp", "PageDown",
"ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown", "NumLock",
"PrintScreen", "NumpadEnter", "NumpadDivide", "VolumeMute",
}
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
user32 = ctypes.WinDLL("user32", use_last_error=True)
ole32 = ctypes.WinDLL("ole32", use_last_error=True)
setupapi = ctypes.WinDLL("setupapi", use_last_error=True)
hid = ctypes.WinDLL("hid", use_last_error=True)
class GUID(ctypes.Structure):
_fields_ = [
("Data1", wintypes.DWORD),
("Data2", wintypes.WORD),
("Data3", wintypes.WORD),
("Data4", ctypes.c_ubyte * 8),
]
class SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
_fields_ = [
("cbSize", wintypes.DWORD),
("InterfaceClassGuid", GUID),
("Flags", wintypes.DWORD),
("Reserved", ctypes.c_void_p),
]
class HIDD_ATTRIBUTES(ctypes.Structure):
_fields_ = [
("Size", wintypes.ULONG),
("VendorID", wintypes.WORD),
("ProductID", wintypes.WORD),
("VersionNumber", wintypes.WORD),
]
class HIDP_CAPS(ctypes.Structure):
_fields_ = [
("Usage", wintypes.WORD),
("UsagePage", wintypes.WORD),
("InputReportByteLength", wintypes.WORD),
("OutputReportByteLength", wintypes.WORD),
("FeatureReportByteLength", wintypes.WORD),
("Reserved", wintypes.WORD * 17),
("NumberLinkCollectionNodes", wintypes.WORD),
("NumberInputButtonCaps", wintypes.WORD),
("NumberInputValueCaps", wintypes.WORD),
("NumberInputDataIndices", wintypes.WORD),
("NumberOutputButtonCaps", wintypes.WORD),
("NumberOutputValueCaps", wintypes.WORD),
("NumberOutputDataIndices", wintypes.WORD),
("NumberFeatureButtonCaps", wintypes.WORD),
("NumberFeatureValueCaps", wintypes.WORD),
("NumberFeatureDataIndices", wintypes.WORD),
]
class KEYBDINPUT(ctypes.Structure):
_fields_ = [
("wVk", wintypes.WORD),
("wScan", wintypes.WORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.c_size_t),
]
class KBDLLHOOKSTRUCT(ctypes.Structure):
_fields_ = [
("vkCode", wintypes.DWORD),
("scanCode", wintypes.DWORD),
("flags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.c_size_t),
]
class MOUSEINPUT(ctypes.Structure):
_fields_ = [
("dx", wintypes.LONG),
("dy", wintypes.LONG),
("mouseData", wintypes.DWORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", ctypes.c_size_t),
]
class HARDWAREINPUT(ctypes.Structure):
_fields_ = [
("uMsg", wintypes.DWORD),
("wParamL", wintypes.WORD),
("wParamH", wintypes.WORD),
]
class TOUCH_POINT(ctypes.Structure):
_fields_ = [("x", wintypes.LONG), ("y", wintypes.LONG)]
class TOUCH_RECT(ctypes.Structure):
_fields_ = [
("left", wintypes.LONG), ("top", wintypes.LONG),
("right", wintypes.LONG), ("bottom", wintypes.LONG),
]
class POINTER_INFO(ctypes.Structure):
_fields_ = [
("pointerType", wintypes.DWORD), ("pointerId", wintypes.DWORD),
("frameId", wintypes.DWORD), ("pointerFlags", wintypes.DWORD),
("sourceDevice", wintypes.HANDLE), ("hwndTarget", wintypes.HWND),
("ptPixelLocation", TOUCH_POINT), ("ptHimetricLocation", TOUCH_POINT),
("ptPixelLocationRaw", TOUCH_POINT), ("ptHimetricLocationRaw", TOUCH_POINT),
("dwTime", wintypes.DWORD), ("historyCount", wintypes.DWORD),
("InputData", wintypes.LONG), ("dwKeyStates", wintypes.DWORD),
("PerformanceCount", ctypes.c_uint64), ("ButtonChangeType", wintypes.DWORD),
]
class POINTER_TOUCH_INFO(ctypes.Structure):
_fields_ = [
("pointerInfo", POINTER_INFO), ("touchFlags", wintypes.DWORD),
("touchMask", wintypes.DWORD), ("rcContact", TOUCH_RECT),
("rcContactRaw", TOUCH_RECT), ("orientation", wintypes.DWORD),
("pressure", wintypes.DWORD),
]
class INPUT_UNION(ctypes.Union):
_fields_ = [("mi", MOUSEINPUT), ("ki", KEYBDINPUT), ("hi", HARDWAREINPUT)]
class INPUT(ctypes.Structure):
_anonymous_ = ("data",)
_fields_ = [("type", wintypes.DWORD), ("data", INPUT_UNION)]
setupapi.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(GUID), wintypes.LPCWSTR, wintypes.HWND, wintypes.DWORD]
setupapi.SetupDiGetClassDevsW.restype = wintypes.HANDLE
setupapi.SetupDiDestroyDeviceInfoList.argtypes = [wintypes.HANDLE]
setupapi.SetupDiDestroyDeviceInfoList.restype = wintypes.BOOL
setupapi.SetupDiEnumDeviceInterfaces.argtypes = [wintypes.HANDLE, ctypes.c_void_p, ctypes.POINTER(GUID), wintypes.DWORD, ctypes.POINTER(SP_DEVICE_INTERFACE_DATA)]
setupapi.SetupDiEnumDeviceInterfaces.restype = wintypes.BOOL
setupapi.SetupDiGetDeviceInterfaceDetailW.argtypes = [wintypes.HANDLE, ctypes.POINTER(SP_DEVICE_INTERFACE_DATA), ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
setupapi.SetupDiGetDeviceInterfaceDetailW.restype = wintypes.BOOL
hid.HidD_GetHidGuid.argtypes = [ctypes.POINTER(GUID)]
hid.HidD_GetAttributes.argtypes = [wintypes.HANDLE, ctypes.POINTER(HIDD_ATTRIBUTES)]
hid.HidD_GetAttributes.restype = wintypes.BOOL
hid.HidD_GetPreparsedData.argtypes = [wintypes.HANDLE, ctypes.POINTER(ctypes.c_void_p)]
hid.HidD_GetPreparsedData.restype = wintypes.BOOL
hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p]
hid.HidD_FreePreparsedData.restype = wintypes.BOOL
hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(HIDP_CAPS)]
hid.HidP_GetCaps.restype = wintypes.LONG
kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
kernel32.CreateFileW.restype = wintypes.HANDLE
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
kernel32.CloseHandle.restype = wintypes.BOOL
kernel32.WriteFile.argtypes = [wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
kernel32.WriteFile.restype = wintypes.BOOL
kernel32.ReadFile.argtypes = [wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p]
kernel32.ReadFile.restype = wintypes.BOOL
user32.SendInput.argtypes = [wintypes.UINT, ctypes.POINTER(INPUT), ctypes.c_int]
user32.SendInput.restype = wintypes.UINT
user32.MapVirtualKeyW.argtypes = [wintypes.UINT, wintypes.UINT]
user32.MapVirtualKeyW.restype = wintypes.UINT
LowLevelKeyboardProc = ctypes.WINFUNCTYPE(ctypes.c_ssize_t, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM)
user32.SetWindowsHookExW.argtypes = [ctypes.c_int, LowLevelKeyboardProc, wintypes.HINSTANCE, wintypes.DWORD]
user32.SetWindowsHookExW.restype = wintypes.HANDLE
user32.UnhookWindowsHookEx.argtypes = [wintypes.HANDLE]
user32.UnhookWindowsHookEx.restype = wintypes.BOOL
user32.CallNextHookEx.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM]
user32.CallNextHookEx.restype = ctypes.c_ssize_t
user32.GetMessageW.argtypes = [ctypes.POINTER(wintypes.MSG), wintypes.HWND, wintypes.UINT, wintypes.UINT]
user32.GetMessageW.restype = wintypes.BOOL
kernel32.GetCurrentThreadId.argtypes = []
kernel32.GetCurrentThreadId.restype = wintypes.DWORD
user32.PostThreadMessageW.argtypes = [wintypes.DWORD, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
user32.PostThreadMessageW.restype = wintypes.BOOL
user32.GetSystemMetrics.argtypes = [ctypes.c_int]
user32.GetSystemMetrics.restype = ctypes.c_int
user32.InitializeTouchInjection.argtypes = [wintypes.UINT, wintypes.DWORD]
user32.InitializeTouchInjection.restype = wintypes.BOOL
user32.InjectTouchInput.argtypes = [wintypes.UINT, ctypes.POINTER(POINTER_TOUCH_INFO)]
user32.InjectTouchInput.restype = wintypes.BOOL
ole32.CoInitializeEx.argtypes = [ctypes.c_void_p, wintypes.DWORD]
ole32.CoInitializeEx.restype = ctypes.c_long
ole32.CoUninitialize.argtypes = []
ole32.CoUninitialize.restype = None
ole32.CoCreateInstance.argtypes = [ctypes.POINTER(GUID), ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p)]
ole32.CoCreateInstance.restype = ctypes.c_long
CLSCTX_ALL = 0x17
COINIT_APARTMENTTHREADED = 0x2
VIRTUAL_DESKTOP_LEFT = 3
VIRTUAL_DESKTOP_RIGHT = 4
POINTER_TYPE_TOUCH = 2
POINTER_FLAG_INRANGE = 0x00000002
POINTER_FLAG_INCONTACT = 0x00000004
POINTER_FLAG_PRIMARY = 0x00002000
POINTER_FLAG_DOWN = 0x00010000
POINTER_FLAG_UPDATE = 0x00020000
POINTER_FLAG_UP = 0x00040000
TOUCH_MASK_CONTACTAREA = 0x00000001
TOUCH_MASK_ORIENTATION = 0x00000002
TOUCH_MASK_PRESSURE = 0x00000004
TOUCH_FEEDBACK_NONE = 0x00000003
CLSID_IMMERSIVE_SHELL = "C2F03A33-21F5-47FA-B4BB-156362A2F239"
CLSID_VIRTUAL_DESKTOP_MANAGER_INTERNAL = "C5E0CDCA-7B6E-41B2-9FC4-D939CC6E4A48"
IID_SERVICE_PROVIDER = "6D5140C1-7436-11CE-8034-00AA006009FA"
IID_VIRTUAL_DESKTOP_MANAGER_INTERNAL = "AF8DA486-95BB-4460-B3B7-6E7A6B2962B5"
def clamp_byte(value: object) -> int:
return max(0, min(255, int(value)))
def _guid(value: str) -> GUID:
return GUID.from_buffer_copy(uuid.UUID(value).bytes_le)
def _com_method(instance: ctypes.c_void_p, index: int, result_type: object, arg_types: list[object], *args: object) -> object:
vtable = ctypes.cast(instance, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
address = vtable[index]
if not address:
raise RuntimeError(f"COM method {index} is unavailable")
function = ctypes.WINFUNCTYPE(result_type, ctypes.c_void_p, *arg_types)(address)
return function(instance, *args)
def _release_com(instance: ctypes.c_void_p | None) -> None:
if instance and instance.value:
try:
_com_method(instance, 2, ctypes.c_long, [])
except Exception:
pass
def switch_virtual_desktop(direction: str) -> bool:
"""Switch desktops through Explorer's Shell service, outside the foreground app."""
if direction not in {"left", "right"}:
return False
initialized = ole32.CoInitializeEx(None, COINIT_APARTMENTTHREADED)
if initialized not in (0, 1, 0x80010106): # S_OK, S_FALSE, RPC_E_CHANGED_MODE
return False
service_provider = ctypes.c_void_p()
desktop_manager = ctypes.c_void_p()
current_desktop = ctypes.c_void_p()
adjacent_desktop = ctypes.c_void_p()
try:
if initialized == 0x80010106:
return False
result = ole32.CoCreateInstance(
ctypes.byref(_guid(CLSID_IMMERSIVE_SHELL)), None, CLSCTX_ALL,
ctypes.byref(_guid(IID_SERVICE_PROVIDER)), ctypes.byref(service_provider),
)
if result != 0:
return False
result = _com_method(
service_provider, 3, ctypes.c_long,
[ctypes.POINTER(GUID), ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p)],
ctypes.byref(_guid(CLSID_VIRTUAL_DESKTOP_MANAGER_INTERNAL)),
ctypes.byref(_guid(IID_VIRTUAL_DESKTOP_MANAGER_INTERNAL)),
ctypes.byref(desktop_manager),
)
if result != 0:
return False
result = _com_method(
desktop_manager, 6, ctypes.c_long,
[ctypes.POINTER(ctypes.c_void_p)], ctypes.byref(current_desktop),
)
if result != 0:
return False
result = _com_method(
desktop_manager, 8, ctypes.c_long,
[ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)],
current_desktop, VIRTUAL_DESKTOP_LEFT if direction == "left" else VIRTUAL_DESKTOP_RIGHT,
ctypes.byref(adjacent_desktop),
)
if result != 0:
return False
result = _com_method(
desktop_manager, 9, ctypes.c_long,
[ctypes.c_void_p], adjacent_desktop,
)
return result == 0
except Exception:
return False
finally:
_release_com(adjacent_desktop)
_release_com(current_desktop)
_release_com(desktop_manager)
_release_com(service_provider)
if initialized in (0, 1):
ole32.CoUninitialize()
_touch_injection_lock = threading.Lock()
_touch_injection_initialized = False
_touch_injection_frame = 0
def _touch_point(
pointer_id: int,
frame_id: int,
x: int,
y: int,
flags: int,
) -> POINTER_TOUCH_INFO:
point = POINTER_TOUCH_INFO()
point.pointerInfo.pointerType = POINTER_TYPE_TOUCH
point.pointerInfo.pointerId = pointer_id
point.pointerInfo.frameId = frame_id
point.pointerInfo.pointerFlags = flags
point.pointerInfo.ptPixelLocation = TOUCH_POINT(x, y)
point.pointerInfo.ptPixelLocationRaw = TOUCH_POINT(x, y)
point.touchFlags = 0
point.touchMask = TOUCH_MASK_CONTACTAREA | TOUCH_MASK_ORIENTATION | TOUCH_MASK_PRESSURE
point.rcContact = TOUCH_RECT(x - 18, y - 18, x + 18, y + 18)
point.rcContactRaw = TOUCH_RECT(x - 18, y - 18, x + 18, y + 18)
point.orientation = 90
point.pressure = 32000
return point
def inject_four_finger_swipe(direction: str) -> bool:
"""Inject four synchronized touch contacts so Windows Shell sees a swipe."""
global _touch_injection_initialized, _touch_injection_frame
if direction not in {"left", "right"}:
return False
with _touch_injection_lock:
try:
if not _touch_injection_initialized:
if not user32.InitializeTouchInjection(4, TOUCH_FEEDBACK_NONE):
return False
_touch_injection_initialized = True
width = max(640, int(user32.GetSystemMetrics(0)))
height = max(480, int(user32.GetSystemMetrics(1)))
center_y = round(height * 0.54)
spread = max(36, round(width * 0.035))
start_x = round(width * (0.72 if direction == "left" else 0.28))
end_x = round(width * (0.28 if direction == "left" else 0.72))
ys = [center_y - spread * 1.5, center_y - spread * 0.5, center_y + spread * 0.5, center_y + spread * 1.5]
_touch_injection_frame = (_touch_injection_frame + 1) & 0xFFFFFFFF
frame = _touch_injection_frame
down = (POINTER_TOUCH_INFO * 4)(*(
_touch_point(index + 1, frame, start_x, round(y), POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT | (POINTER_FLAG_PRIMARY if index == 0 else 0))
for index, y in enumerate(ys)
))
if not user32.InjectTouchInput(4, down):
return False
steps = 6
for step in range(1, steps + 1):
frame = (frame + 1) & 0xFFFFFFFF
x = round(start_x + (end_x - start_x) * step / steps)
move = (POINTER_TOUCH_INFO * 4)(*(
_touch_point(index + 1, frame, x, round(y), POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT | (POINTER_FLAG_PRIMARY if index == 0 else 0))
for index, y in enumerate(ys)
))
if not user32.InjectTouchInput(4, move):
return False
time.sleep(0.018)
frame = (frame + 1) & 0xFFFFFFFF
up = (POINTER_TOUCH_INFO * 4)(*(
_touch_point(index + 1, frame, end_x, round(y), POINTER_FLAG_UP | (POINTER_FLAG_PRIMARY if index == 0 else 0))
for index, y in enumerate(ys)
))
return bool(user32.InjectTouchInput(4, up))
except Exception:
return False
def perform_touchpad_swipe(direction: str) -> str:
"""Submit a native four-contact gesture through the virtual HID driver."""
if direction not in {"left", "right"}:
raise ValueError("touchpad swipe direction must be left or right")
try:
send_virtual_touchpad_swipe(direction)
except FileNotFoundError:
return "driver-required"
except OSError:
return "unavailable"
return "touch-injection"
_virtual_touchpad_lock = threading.Lock()
_virtual_touchpad_probe_lock = threading.Lock()
_virtual_touchpad_probe_at = 0.0
_virtual_touchpad_probe_result = False
_virtual_touchpad_path: str | None = None
def build_virtual_touchpad_report(
contacts: list[tuple[int, int, bool]],
scan_time: int,
reported_contact_count: int | None = None,
) -> bytearray:
"""Build the vendor report that the driver converts to PTP report ID 5."""
if len(contacts) != VIRTUAL_TOUCHPAD_CONTACTS:
raise ValueError("virtual touchpad reports require exactly four contact slots")
report = bytearray((VIRTUAL_TOUCHPAD_REPORT_ID,))
active_count = 0
for contact_id, (x, y, active) in enumerate(contacts):
x = max(0, min(20000, int(x)))
y = max(0, min(12000, int(y)))
status = 0x01 | ((1 if active else 0) << 1)
report.extend(struct.pack("<BIHH", status, contact_id, x, y))
active_count += int(active)
for _slot in range(VIRTUAL_TOUCHPAD_CONTACTS, VIRTUAL_TOUCHPAD_REPORT_SLOTS):
report.extend(bytes(9))
contact_count = active_count if reported_contact_count is None else int(reported_contact_count)
if not 0 <= contact_count <= VIRTUAL_TOUCHPAD_CONTACTS:
raise ValueError("reported touchpad contact count is out of range")
report.extend(struct.pack("<HBB", scan_time & 0xFFFF, contact_count, 0))
if len(report) != VIRTUAL_TOUCHPAD_REPORT_LENGTH:
raise AssertionError(f"virtual touchpad report is {len(report)} bytes")
return report
def find_virtual_touchpad() -> tuple[str, int] | None:
"""Find the vendor top-level collection exposed by the virtual driver."""
global _virtual_touchpad_path
if _virtual_touchpad_path:
handle = open_handle(_virtual_touchpad_path, GENERIC_WRITE)
if handle is not None:
return _virtual_touchpad_path, handle
_virtual_touchpad_path = None
for path in device_paths():
attributes = attributes_for(path)
if not attributes or (
attributes.VendorID != VIRTUAL_TOUCHPAD_VENDOR_ID
or attributes.ProductID != VIRTUAL_TOUCHPAD_PRODUCT_ID
):
continue
handle = open_handle(path, GENERIC_WRITE)
if handle is None:
continue
caps = caps_for(handle)
if (
caps
and caps.UsagePage == VIRTUAL_TOUCHPAD_USAGE_PAGE
and caps.OutputReportByteLength == VIRTUAL_TOUCHPAD_REPORT_LENGTH
):
_virtual_touchpad_path = path
return path, handle
kernel32.CloseHandle(handle)
return None
def virtual_touchpad_available(force: bool = False) -> bool:
"""Probe the virtual HID collection with a short cache for status polling."""
global _virtual_touchpad_probe_at, _virtual_touchpad_probe_result
with _virtual_touchpad_probe_lock:
now = time.monotonic()
if not force and now - _virtual_touchpad_probe_at < 2.0:
return _virtual_touchpad_probe_result
device = find_virtual_touchpad()
if device is not None:
_path, handle = device
kernel32.CloseHandle(handle)
_virtual_touchpad_probe_result = device is not None
_virtual_touchpad_probe_at = now
return _virtual_touchpad_probe_result
def send_virtual_touchpad_swipe(direction: str) -> None:
"""Send a complete four-finger horizontal gesture to HIDClass."""
with _virtual_touchpad_lock:
device = find_virtual_touchpad()
if device is None:
raise FileNotFoundError("DS5 virtual Precision Touchpad is not installed")
_path, handle = device
global _virtual_touchpad_probe_at, _virtual_touchpad_probe_result
with _virtual_touchpad_probe_lock:
_virtual_touchpad_probe_at = time.monotonic()
_virtual_touchpad_probe_result = True
try:
start_x, end_x = (16500, 3500) if direction == "left" else (3500, 16500)
x_offsets = (-750, -250, 250, 750)
y_positions = (3500, 5200, 6900, 8600)
scan_time = int(time.monotonic() * 10000) & 0xFFFF
def contacts_at(x: int, active: bool) -> list[tuple[int, int, bool]]:
return [
(x + x_offset, y, active)
for x_offset, y in zip(x_offsets, y_positions, strict=True)
]
write_report(handle, build_virtual_touchpad_report(contacts_at(start_x, True), scan_time))
time.sleep(VIRTUAL_TOUCHPAD_FRAME_SECONDS)
steps = VIRTUAL_TOUCHPAD_MOVE_STEPS
scan_step = round(VIRTUAL_TOUCHPAD_FRAME_SECONDS * 10000)
for step in range(1, steps + 1):
x = round(start_x + (end_x - start_x) * step / steps)
scan_time = (scan_time + scan_step) & 0xFFFF
write_report(handle, build_virtual_touchpad_report(contacts_at(x, True), scan_time))
time.sleep(VIRTUAL_TOUCHPAD_FRAME_SECONDS)
scan_time = (scan_time + scan_step) & 0xFFFF
write_report(handle, build_virtual_touchpad_report(
contacts_at(end_x, False),
scan_time,
reported_contact_count=VIRTUAL_TOUCHPAD_CONTACTS,
))
time.sleep(VIRTUAL_TOUCHPAD_FRAME_SECONDS)
scan_time = (scan_time + scan_step) & 0xFFFF
write_report(handle, build_virtual_touchpad_report(contacts_at(end_x, False), scan_time))
finally:
kernel32.CloseHandle(handle)
def load_or_create_bridge_token(path: str = BRIDGE_TOKEN_PATH) -> str:
try:
with open(path, "r", encoding="ascii") as stream:
token = stream.read(256).strip()
if len(token) >= 32:
return token
raise RuntimeError("Bridge token file is invalid")
except FileNotFoundError:
pass
directory = os.path.dirname(path)
if directory:
os.makedirs(directory, exist_ok=True)
token = secrets.token_urlsafe(32)
try:
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
return load_or_create_bridge_token(path)
with os.fdopen(descriptor, "w", encoding="ascii") as stream:
stream.write(token)
return token
def validate_post_request(
path: str,
origin: str,
content_type: str,
hook_token: str,
expected_hook_token: str,
) -> tuple[HTTPStatus, str] | None:
if origin and origin not in ALLOWED_WEB_ORIGINS:
return HTTPStatus.FORBIDDEN, "origin is not allowed"
if content_type.lower() != "application/json":
return HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "application/json is required"
if path == "/api/codex-hook" and (
not expected_hook_token
or not secrets.compare_digest(hook_token, expected_hook_token)
):
return HTTPStatus.UNAUTHORIZED, "invalid bridge token"
return None
def device_paths() -> list[str]:
hid_guid = GUID()
hid.HidD_GetHidGuid(ctypes.byref(hid_guid))
info_set = setupapi.SetupDiGetClassDevsW(ctypes.byref(hid_guid), None, None, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)
if info_set == INVALID_HANDLE_VALUE:
raise ctypes.WinError(ctypes.get_last_error())
paths: list[str] = []
try:
index = 0
while True:
interface = SP_DEVICE_INTERFACE_DATA(cbSize=ctypes.sizeof(SP_DEVICE_INTERFACE_DATA))
if not setupapi.SetupDiEnumDeviceInterfaces(info_set, None, ctypes.byref(hid_guid), index, ctypes.byref(interface)):
if ctypes.get_last_error() == ERROR_NO_MORE_ITEMS:
break
raise ctypes.WinError(ctypes.get_last_error())
required = wintypes.DWORD()
setupapi.SetupDiGetDeviceInterfaceDetailW(info_set, ctypes.byref(interface), None, 0, ctypes.byref(required), None)
if ctypes.get_last_error() != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(ctypes.get_last_error())
detail = ctypes.create_string_buffer(required.value)
# This ABI uses 8 on 64-bit Windows and 6 on 32-bit Windows.
ctypes.cast(detail, ctypes.POINTER(wintypes.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
if not setupapi.SetupDiGetDeviceInterfaceDetailW(info_set, ctypes.byref(interface), detail, required.value, None, None):
raise ctypes.WinError(ctypes.get_last_error())
paths.append(ctypes.wstring_at(ctypes.addressof(detail) + ctypes.sizeof(wintypes.DWORD)))
index += 1
finally:
setupapi.SetupDiDestroyDeviceInfoList(info_set)
return paths
def open_handle(path: str, access: int) -> int | None:
handle = kernel32.CreateFileW(path, access, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None)
return None if handle == INVALID_HANDLE_VALUE else handle
def attributes_for(path: str) -> HIDD_ATTRIBUTES | None:
handle = open_handle(path, 0)
if handle is None:
return None
try:
attributes = HIDD_ATTRIBUTES(Size=ctypes.sizeof(HIDD_ATTRIBUTES))
return attributes if hid.HidD_GetAttributes(handle, ctypes.byref(attributes)) else None
finally:
kernel32.CloseHandle(handle)
def caps_for(handle: int) -> HIDP_CAPS | None:
preparsed = ctypes.c_void_p()
if not hid.HidD_GetPreparsedData(handle, ctypes.byref(preparsed)):
return None
try:
caps = HIDP_CAPS()
status = ctypes.c_ulong(hid.HidP_GetCaps(preparsed, ctypes.byref(caps))).value
return caps if status == HIDP_STATUS_SUCCESS else None
finally:
hid.HidD_FreePreparsedData(preparsed)
def find_dualsense_usb() -> tuple[str, int] | None:
for path in device_paths():
attributes = attributes_for(path)
if not attributes or attributes.VendorID != SONY_VENDOR_ID:
continue
handle = open_handle(path, GENERIC_READ | GENERIC_WRITE)
if handle is None:
continue
try:
caps = caps_for(handle)
if caps and caps.OutputReportByteLength == DS5_USB_OUTPUT_LENGTH and caps.InputReportByteLength >= 11:
return path, attributes.ProductID
finally:
kernel32.CloseHandle(handle)
return None
def normalize_lighting(payload: dict[str, object]) -> dict[str, int | str]:
lightbar = payload.get("lightbar")
if not isinstance(lightbar, dict):
raise ValueError("lightbar object is required")
effect = str(payload.get("effect", "static"))
if effect not in {"static", "blink", "breathe"}:
raise ValueError("effect must be static, blink, or breathe")
speed = max(1, min(5, int(payload.get("speed", 3))))
return {
"red": clamp_byte(lightbar.get("red", 0)),
"green": clamp_byte(lightbar.get("green", 0)),
"blue": clamp_byte(lightbar.get("blue", 0)),
"brightness": max(0, min(100, int(lightbar.get("brightness", 100)))),
"playerLeds": max(0, min(0x1F, int(payload.get("playerLeds", 0)))),
"effect": effect,
"speed": speed,
}
def normalize_trigger(trigger: object) -> dict[str, int | str]:
if not isinstance(trigger, dict):
raise ValueError("trigger configuration must be an object")
mode = str(trigger.get("mode", "off")).strip().lower()
if mode not in {"off", "feedback", "weapon"}:
raise ValueError("trigger mode must be off, feedback, or weapon")
start = max(0, min(9, int(trigger.get("start", 3))))
strength = max(1, min(8, int(trigger.get("strength", 5))))
requested_end = max(1, min(9, int(trigger.get("end", max(start + 1, 6)))))
end = min(9, max(start + 1, requested_end))
if mode == "weapon" and not 2 <= start <= 7:
raise ValueError("weapon trigger start must be between 2 and 7")
if mode == "weapon" and not start < end <= 8:
raise ValueError("weapon trigger end must be after start and no greater than 8")
return {"mode": mode, "start": start, "end": end, "strength": strength}
def normalize_triggers(payload: dict[str, object]) -> dict[str, dict[str, int | str]]:
return {
"left": normalize_trigger(payload.get("left", {})),
"right": normalize_trigger(payload.get("right", {})),
}
def build_trigger_effect(config: dict[str, int | str]) -> bytes:
"""Encode one adaptive trigger using the DualSense common output block."""
effect = bytearray(11)
mode = str(config["mode"])
if mode == "off":
effect[0] = DS5_TRIGGER_EFFECT_OFF
elif mode == "weapon":
start = int(config["start"])
end = int(config["end"])
breakpoints = (1 << start) | (1 << end)
effect[0] = DS5_TRIGGER_EFFECT_WEAPON
effect[1:3] = breakpoints.to_bytes(2, "little")
effect[3] = int(config["strength"]) - 1
else:
# Feedback divides the travel into ten zones. The first 16-bit value
# selects active zones and the following 32 bits store 3-bit forces.
start = int(config["start"])
strength = int(config["strength"]) - 1
active_zones = ((1 << (10 - start)) - 1) << start
force_zones = sum(strength << (zone * 3) for zone in range(start, 10))
effect[0] = DS5_TRIGGER_EFFECT_FEEDBACK
effect[1:3] = active_zones.to_bytes(2, "little")
effect[3:7] = force_zones.to_bytes(4, "little")
return bytes(effect)
def normalize_touchpad_gestures(payload: object) -> dict[str, int | bool]:
if payload is None:
return dict(DEFAULT_TOUCHPAD_GESTURES)
if not isinstance(payload, dict):
raise ValueError("touchpadGestures must be an object")
threshold = int(payload.get("threshold", DEFAULT_TOUCHPAD_GESTURES["threshold"]))
if not 160 <= threshold <= 800:
raise ValueError("touchpad gesture threshold must be between 160 and 800")
return {
"enabled": bool(payload.get("enabled", DEFAULT_TOUCHPAD_GESTURES["enabled"])),
"threshold": threshold,
"muteOnSwitch": bool(payload.get("muteOnSwitch", DEFAULT_TOUCHPAD_GESTURES["muteOnSwitch"])),
}
def normalize_mapping(
payload: dict[str, object],
) -> tuple[bool, dict[str, list[str]], dict[str, int | bool]]:
enabled = bool(payload.get("enabled", False))
raw_mappings = payload.get("mappings", {})
if not isinstance(raw_mappings, dict):
raise ValueError("mappings must be an object")
mappings: dict[str, list[str]] = {}
for button, shortcut in raw_mappings.items():
if button not in DS5_BUTTONS:
raise ValueError(f"unknown controller button: {button}")
if not isinstance(shortcut, list) or not 1 <= len(shortcut) <= 5:
raise ValueError(f"mapping for {button} must contain 1 to 5 keyboard codes")
codes = [str(code) for code in shortcut]
unknown = [code for code in codes if code not in VK_CODES]
if unknown:
raise ValueError(f"unsupported keyboard code: {unknown[0]}")
mappings[button] = codes
gestures = normalize_touchpad_gestures(payload.get("touchpadGestures"))
return enabled, mappings, gestures
def parse_dualsense_usb_input(report: bytes) -> tuple[set[str], dict[str, object]]:
if len(report) < 11 or report[0] != 0x01:
raise ValueError("unsupported DualSense USB input report")
first = report[8]
second = report[9]
third = report[10]
dpad = first & 0x0F
pressed: set[str] = set()
if dpad in {0, 1, 7}:
pressed.add("dpad_up")
if dpad in {1, 2, 3}:
pressed.add("dpad_right")
if dpad in {3, 4, 5}:
pressed.add("dpad_down")
if dpad in {5, 6, 7}:
pressed.add("dpad_left")
for bit, name in enumerate(("square", "cross", "circle", "triangle"), start=4):
if first & (1 << bit):
pressed.add(name)
for bit, name in enumerate(("l1", "r1", "l2", "r2", "create", "options", "l3", "r3")):
if second & (1 << bit):
pressed.add(name)
for bit, name in enumerate(("ps", "touchpad", "mute")):
if third & (1 << bit):
pressed.add(name)
def axis(value: int) -> float:
return round((value - 127.5) / 127.5, 3)
touch_active = False
touch_id: int | None = None
touch_x: int | None = None
touch_y: int | None = None
# USB report 0x01 stores two four-byte touch points at 33..40. Bit 7
# marks an inactive point; X is 12-bit (0..1919) and Y is 12-bit
# (0..1079). Prefer the first active point for single-finger gestures.
for offset in (33, 37):
if len(report) < offset + 4 or report[offset] & 0x80:
continue
touch_active = True
touch_id = report[offset] & 0x7F
touch_x = report[offset + 1] | ((report[offset + 2] & 0x0F) << 8)
touch_y = (report[offset + 2] >> 4) | (report[offset + 3] << 4)
break
axes: dict[str, object] = {
"leftX": axis(report[1]), "leftY": axis(report[2]),
"rightX": axis(report[3]), "rightY": axis(report[4]),
"leftTrigger": round(report[5] / 255, 3),
"rightTrigger": round(report[6] / 255, 3),
"leftTriggerEffectStatus": (report[43] >> 4) & 0x0F if len(report) > 43 else 0,
"rightTriggerEffectStatus": (report[42] >> 4) & 0x0F if len(report) > 42 else 0,
"touchActive": touch_active,
"touchId": touch_id,
"touchX": touch_x,
"touchY": touch_y,
}
return pressed, axes