def map_device(kb_name: str, config_path: str, ui_name: str = 'kbmap') -> None: """ Create virtual device with ui_name that will remap keyboard events from device with name device_name and delegate event handling. :param kb_name: source device name. This device will be grabbed :param config_path: path to configuration file :param ui_name: optional UInput device name """ config = c.load(config_path) error_list = c.validate(config) if not error_list.empty(): error('\n - '.join(['invalid config; errors:'] + error_list.errors)) sys.exit(1) init_mapper(config) kb = keyboard.get_device_by_name(kb_name) keyboard.grab(kb) ui = UInput.from_device(kb, name=ui_name) with ui: keyboard.listen_key_events(kb, lambda e: handle_event(e, ui, config), False)
def createUInputDev(self, fd): if not self.env['runtime']['settingsManager'].getSettingAsBool( 'keyboard', 'grabDevices'): self.uDevices[fd] = None return try: test = self.uDevices[fd] return except KeyError: self.uDevices[fd] = None if self.uDevices[fd] != None: return try: self.uDevices[fd] = UInput.from_device(self.iDevices[fd], name='fenrir-uinput', phys='fenrir-uinput') except Exception as e: try: self.env['runtime']['debug'].writeDebugOut( 'InputDriver evdev: compat fallback: ' + str(e), debug.debugLevel.WARNING) dev = self.iDevices[fd] cap = dev.capabilities() del cap[0] self.uDevices[fd] = UInput(cap, name='fenrir-uinput', phys='fenrir-uinput') except Exception as e: self.env['runtime']['debug'].writeDebugOut( 'InputDriver evdev: init Uinput not possible: ' + str(e), debug.debugLevel.ERROR) return
def main() -> None: devices = find_devices_by_names(NAMES) with UInput.from_device(*devices, name='trackpoint-keyboard') as ui: for device in devices: device.grab() ensure_future(translate_input(device, ui, DISABLED, MAPPING)) get_event_loop().run_forever()
def make_controller(name): return UInput.from_device(real_controller, name='Microsoft X-Box 360 pad', vendor=0x045e, product=0x028e, version=110, bustype=3, devnode='/dev/uinput', phys='py-evdev-uinput-1')
def setup_devices(original_path): raw = InputDevice(original_path) target_dev = '/dev/uinput' try: fixed = UInput.from_device(raw, devnode=target_dev, name="Calibrated {}".format(raw.name)) except UInputError as e: raise PermissionError("You should run this command as root") from e log.info("Redirecting fixed stream to {}".format(target_dev)) return raw, fixed
def __init__(self, eventloop, options): self.lock = asyncio.Lock() self.loop = eventloop self.options = options self.repeat = options.repeat / 1000 self.inputdevice = InputDevice(options.inputdevice) self.outputdevice = UInput.from_device(self.inputdevice, name=options.name) try: self.inputdevice.grab() except IOError: print("could not grab input device", file=sys.stderr)
def __init__(self, name): self.name = name self.mapping = { 'Y': e.BTN_WEST, 'A': e.BTN_SOUTH, 'X': e.BTN_NORTH, 'B': e.BTN_EAST, } EVENT_ID = 10 real_controller = InputDevice(f'/dev/input/event{EVENT_ID}') self.interface = UInput.from_device(real_controller, name='Microsoft X-Box 360 pad', vendor=0x045e, product=0x028e, version=110, bustype=3, devnode='/dev/uinput', phys='py-evdev-uinput-1')
def grabDevice(self, fd): try: self.uDevices[fd] = UInput.from_device(self.iDevices[fd].fn) except Exception as e: try: self.env['runtime']['debug'].writeDebugOut('InputDriver evdev: compat fallback: ' + str(e),debug.debugLevel.ERROR) dev = self.iDevices[fd] cap = dev.capabilities() del cap[0] self.uDevices[fd] = UInput( cap, dev.name, ) except Exception as e: self.env['runtime']['debug'].writeDebugOut('InputDriver evdev: init Uinput not possible: ' + str(e),debug.debugLevel.ERROR) return try: self.iDevices[fd].grab() except Exception as e: self.env['runtime']['debug'].writeDebugOut('InputDriver evdev: grabing not possible: ' + str(e),debug.debugLevel.ERROR)
save_queue = False elif opt in ("-r"): if arg == 'true': global_variables.randomplay = True else: global_variables.randomplay = False """ HOOK GAMEPAD. """ # Listen to events from the following device. print('Will Inject on device:', list_devices()[0]) dev = InputDevice(list_devices()[0]) print('Device Hooked.') # Then create our own devices for our own events. # (It is possible to write events directly to the original device, but that has caused me mysterious problems in the past.) global_variables.virtual_gamepad = UInput.from_device( dev, name="Virtual Microsoft X-Box 360 pad") #name="virtual-gamepad") # Now we monopolize the original devices. dev.grab() # Sends all events from the source to the target, to make our virtual keyboard behave as the original. print('Virtual Gamepad created. \nReady to play videogames!') """ LOADING MODEL """ print('\n\nLoading Models...') global_variables.score_model = generate_scoring_model() global_variables.time_model = generate_time_model() global_variables.model = generate_model()
keys = tmpdev.capabilities().get(EV_KEY) if keys == None: continue if BTN_TOOL_PEN in keys and BTN_TOOL_RUBBER in keys: device = '/dev/input/' + name if device is not None: print('Found event: ' + device) else: print('No event found! Exiting.') sys.exit(-ENOENT) dev = InputDevice(device) virt = UInput.from_device(dev, name=dev.name + ' Virtual Stylus') def handleExit(s, f): dev.ungrab() sys.exit(0) # Take over complete control over the device - no events will be passed to # other listeners. They are relayed to the virtual stylus created above. signal(SIGINT, handleExit) dev.grab() for event in dev.read_loop(): # When putting the eraser down, IPTS first sends an event that puts
"""バーチャルなジョイスティックを操作する Args: vjoystick(evdev.uinput.UInput): バーチャルジョイスティックインスタンス joystick mode steer_value(int): ステアリング操作量、0~256の整数、中心が128 eurotruck axis mode center accel_value(int): アクセル操作量、0~256の整数、フルスロットルが256 eurotruck axis mode normal brake_value(int): ブレーキ操作量、0~256の整数、フルブレーキが256 eurotruck axis mode normal dt(float): 入力する時間 """ vjoy.write(e.EV_ABS, e.ABS_X, steer_value) # steer vjoy.write(e.EV_ABS, e.ABS_RZ, accel_value) # accel vjoy.write(e.EV_ABS, e.ABS_Z, brake_value) # brake vjoy.write(e.EV_ABS, e.ABS_Z, 0) # brake vjoy.syn() time.sleep(dt) if __name__ == "__main__": devices = [InputDevice(path) for path in list_devices()] for device in devices: print(f"{device.path}, {device.name}") print("どのデバイスの仮想デバイスを作成しますか?") print("パスを入力してください /dev/input/以下を入力") device_path = input(">> ") device_path = "/dev/input/" + device_path vjoy = UInput.from_device(InputDevice(device_path), name="vjoy") print(vjoy) vjoy.close()
e.KEY_5: e.KEY_F5, e.KEY_6: e.KEY_F6, e.KEY_7: e.KEY_F7, e.KEY_8: e.KEY_F8, e.KEY_9: e.KEY_F9, e.KEY_0: e.KEY_F10, e.KEY_MINUS: e.KEY_F11, e.KEY_EQUAL: e.KEY_F12, e.KEY_BACKSPACE: e.KEY_DELETE, } # The names can be found with evtest or in evdev docs. esc = False intercepted = False # Create a new keyboard mimicking the original one. with UInput.from_device(kbd, name='kbdremap') as ui: for ev in kbd.read_loop(): # Read events from original keyboard. if ev.type == e.EV_KEY: # Process key events. # ke = evdev.categorize(ev) act = kbd.active_keys() # print(act) # print(ev.value) if e.KEY_ESC in act: esc = True for k, v in REMAP_TABLE.items(): if k in act: intercepted = True ui.write(e.EV_KEY, v, 1) ui.write(e.EV_KEY, v, 0) ui.syn() elif esc and not intercepted:
from evdev import InputDevice, categorize, ecodes, UInput, list_devices, ecodes as e devices = [InputDevice(fn) for fn in list_devices()] for device in devices: if device.name == 'Microsoft Microsoft® Comfort Mouse 4500': print(device.fn, device.name, device.phys) dev = InputDevice(device.fn) print(dev) dev.grab() mouse = UInput.from_device(dev) for event in dev.read_loop(): c = categorize(event) if event.code == 275 and c.keystate == c.key_down: try: print(categorize(event)) ui = UInput() ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 1) ui.write(ecodes.EV_KEY, ecodes.KEY_C, 1) ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 0) ui.write(ecodes.EV_KEY, ecodes.KEY_C, 0) ui.syn() ui.close() except: pass elif event.code == 276 and c.keystate == c.key_down: try:
commands = [0, 0, 0, 0, 0] # global capture capture_screen = False model_not_compiled = True if __name__ == '__main__': """ HOOK GAMEPAD. """ # Listen to events from the following device. print('Will Inject on device:', list_devices()[0]) dev = InputDevice(list_devices()[0]) # Then create our own devices for our own events. # (It is possible to write events directly to the original device, but that has caused me mysterious problems in the past.) virtual_gamepad = UInput.from_device( dev, name="Microsoft X-Box 360 pad") #name="virtual-gamepad") # Now we monopolize the original devices. dev.grab() # Sends all events from the source to the target, to make our virtual keyboard behave as the original. print('Virtual Gamepad created. \nReady to play videogames!') """ LOADING MODEL """ print('\n\nLoading Models...') score_model = generate_scoring_model() time_model = generate_time_model() model = generate_model()
def onthefly(input_file, keyboard_match_string): configfile = appdirs.user_config_dir() + '/onthefly/config.cfg' bookkeep_config_file(keyboard_match_string, configfile) keyboard_match_string = read_config_match_string(configfile) dev = find_keyboard(keyboard_match_string) if not dev: print("""Error: No keyboard found. Use $ sudo python -m evdev.evtest to find the name of your keyboard and pass it to the `keyboard` option when invoking onthefly, e.g.: $ sudo onthefly --keyboard="Logitech K330" /path/to/file """) sys.exit() file_characters = read_input_file( input_file) # read all characters in the input file current_char_idx = 0 # indicates the next character to be emulated dev.grab( ) # Grab, i.e. prevent the keyboard from emitting original events. # Create a new keyboard mimicking the original one. with UInput.from_device(dev, name='onthefly') as ui: for event in dev.read_loop(): # Read events from original keyboard. if event.type == ecodes.EV_KEY: # Process key events. if event.code == ecodes.KEY_PAUSE and event.value == 1 \ or current_char_idx == len(file_characters): # Exit on pressing PAUSE or when all characters have been written. dev.ungrab() # mrv break elif event.code == ecodes.KEY_BACKSPACE and event.value == 1: # Decrement counter current_char_idx -= 1 # Passthrough key event unmodified ui.write(ecodes.EV_KEY, event.code, 1) ui.write(ecodes.EV_KEY, event.code, 0) ui.syn() # Write next char when: # - current key pressed is in the set of permitted keys # - Control key is not pressed # - current action is a press and not a release elif event.code in WRITE_NEXT_CHAR_KEYS \ and ecodes.KEY_LEFTCTRL not in dev.active_keys() \ and event.value == 1: # Check if we need to press shift if file_characters[current_char_idx] in ascii2keycode: # No, we don't. Lookup the key we want to press/release remapped_code = ascii2keycode[ file_characters[current_char_idx]] ui.write(ecodes.EV_KEY, remapped_code, 1) ui.syn() ui.write(ecodes.EV_KEY, remapped_code, 0) ui.syn() elif file_characters[ current_char_idx] in shift_ascii2keycode: # Yes, we do. Lookup the key we want to press/release remapped_code = shift_ascii2keycode[ file_characters[current_char_idx]] ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1) # press shift ui.syn() ui.write(ecodes.EV_KEY, remapped_code, 1) ui.syn() ui.write(ecodes.EV_KEY, remapped_code, 0) ui.syn() ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0) # release shift ui.syn() else: # The character is not in either dictionary, then it must be a unicode # Press Control+Shift+U ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 1) ui.syn() ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1) ui.syn() ui.write(ecodes.EV_KEY, ecodes.KEY_U, 1) ui.syn() ui.write(ecodes.EV_KEY, ecodes.KEY_U, 0) ui.syn() ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0) ui.syn() ui.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 0) ui.syn() # Write each hex digit for hex_digit in '%X' % ord( file_characters[current_char_idx]): keycode = getattr(ecodes, 'KEY_%s' % hex_digit) ui.write(ecodes.EV_KEY, keycode, 1) ui.syn() ui.write(ecodes.EV_KEY, keycode, 0) ui.syn() # Press Enter ui.write(ecodes.EV_KEY, ecodes.KEY_ENTER, 1) ui.write(ecodes.EV_KEY, ecodes.KEY_ENTER, 0) ui.syn() # Increment counter current_char_idx += 1 else: # Passthrough other key events unmodified. ui.write(ecodes.EV_KEY, event.code, event.value) ui.syn() else: # Passthrough other events unmodified (e.g. SYNs). ui.write(event.type, event.code, event.value) ui.syn()
def run_listern_btn_ts(): mouse = Controller() def on_move(x, y): mouse print('Pointer moved to {0}'.format((x, y))) # Press and release mouse.press(Button.left) mouse.release(Button.left) def run(): with Listener(on_move=on_move) as listener: listener.join() from evdev import UInput, ecodes as e import time ui = UInput() ui = UInput.from_device('/dev/input/event0', name='ts_mouse') def run2(): while True: ui.write(e.EV_KEY, e.BTN_LEFT, 1) ui.syn() time.sleep(0.5) ui.write(e.EV_KEY, e.BTN_LEFT, 0) ui.syn() print('BTN_LEFT') time.sleep(1) # ui.close() import evdev def run_3(): device = evdev.InputDevice('/dev/input/event0') mouse = Controller() for event in device.read_loop(): if event.type == evdev.ecodes.EV_KEY: r = evdev.categorize(event) print( type(r), r.scancode, r.keystate, r.keycode ) # <class 'evdev.events.KeyEvent'> 330 1 BTN_TOUCH <class 'evdev.events.KeyEvent'> 330 0 BTN_TOUCH # r.keystate key_up= 0 key_down= 1 key_hold= 2 print(r) # if 'BTN_TOUCH' in str(r): # print('ts down') # print('ts up') # if r.keycode in 'BTN_TOUCH': if r.keystate == r.key_down: print('ts down') mouse.press(Button.left) if r.keystate == r.key_up: print('ts up') mouse.release(Button.left) x = Thread(target=run_3, daemon=True) x.start()
def replicate(source_device, target_device): for event in source_device.async_read_loop(): #print('Man Generated Event',event) target_device.write_event(event) if __name__ == '__main__': """ HOOK GAMEPAD. """ # Listen to events from the following device. print('Will Inject on device:', list_devices()[0]) dev = InputDevice(list_devices()[0]) # Then create our own devices for our own events. # (It is possible to write events directly to the original device, but that has caused me mysterious problems in the past.) virtual_gamepad = UInput.from_device(dev, name="virtual-gamepad") # Now we monopolize the original devices. dev.grab() #controller. monitor_thread = threading.Thread(target=replicate, args=(dev, virtual_gamepad)) monitor_thread.daemon = True monitor_thread.start() while True: pass
from evdev import UInput from evdev import InputDevice from evdev import ecodes as e UDP_IP = '0.0.0.0' UDP_PORT = 8444 DEVICES = [evdev.InputDevice(fn) for fn in evdev.list_devices()] PS4 = None for dev in DEVICES: if dev.name == 'Sony Computer Entertainment Wireless Controller': PS4 = dev.fn INPUT_DEVICE = InputDevice(PS4) USER_INPUT = UInput.from_device(INPUT_DEVICE, name='xboxdrv_emu') print('Found PS4-controller.') SOCK = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) SOCK.bind((UDP_IP, UDP_PORT)) while True: data, addr = SOCK.recvfrom(10000000) LIST = [re.sub('[^A-Za-z0-9.-]+', "", x) for x in data.split(",")] CONTROLLER_1 = LIST[0:15] CONTROLLER_2 = LIST[15:30] # Lateral movement, min: 0, max: 255 [int] USER_INPUT.write(e.EV_ABS, e.ABS_X, int(255. * (float(CONTROLLER_1[0]) + 1.0) / 2.0))