-
Notifications
You must be signed in to change notification settings - Fork 0
/
usbmapper.py
83 lines (69 loc) · 2.48 KB
/
usbmapper.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
import usb.core
import usb.util
import time
import pydirectinput
import hid2text
import config
class USBMapper:
def __init__(self, config, device):
self.key_down = []
self.config = config
self.config_device = device
def on_key_down(self, keys, device):
for key in keys:
key_name = hid2text.hid_code_to_string(key)
if key != 0 and key not in self.key_down and key_name in device.mappings:
self.key_down.append(key)
target = device.mappings[key_name]
print(f'keydown {key_name} into {target}')
for subkey in target:
pydirectinput.keyDown(subkey)
time.sleep(self.config.key_stroke_delay)
def on_key_up(self, keys, device):
to_remove = self.key_down.copy()
for key in keys:
if key != 0 and key in to_remove:
to_remove.remove(key)
for key in to_remove:
key_name = hid2text.hid_code_to_string(key)
self.key_down.remove(key)
target = device.mappings[key_name].copy()
print(f'keyup {key_name} into {target}')
target.reverse()
for subkey in target:
pydirectinput.keyUp(subkey)
time.sleep(self.config.key_stroke_delay)
def init(self):
device = self.config_device
self.dev = usb.core.find(
idVendor=int(device.vid, base=16), idProduct=int(device.pid, base=16))
self.endpoint = self.dev[0][(0, 0)][0]
def tick(self):
device = self.config_device
control = None
try:
control = self.dev.read(self.endpoint.bEndpointAddress,
self.endpoint.wMaxPacketSize, config.USB_TIMEOUT)
except usb.core.USBTimeoutError:
pass
if control != None:
mods = control[0]
keys = control[2:]
all_keys = hid2text.mods_to_keys(mods) + list(keys)
self.on_key_down(all_keys, device)
self.on_key_up(all_keys, device)
def loop(self):
while True:
self.tick()
time.sleep(0.01)
if __name__ == "__main__":
_config = config.load_config("config.yaml")
mappers = []
for device in _config.devices:
mapper = USBMapper(_config, device)
mapper.init()
mappers.append(mapper)
while True:
for mapper in mappers:
mapper.tick()
time.sleep(0.01)