Python evdev.InputDevice() Examples

The following are 30 code examples of evdev.InputDevice(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module evdev , or try the search function .
Example #1
Source File: joystick.py    From derplearning with MIT License 7 votes vote down vote up
def __connect(self):
        device_addr, hidraw_device, event_device = self.__find_device()
        if device_addr is None:
            return False
        self.__report_fd = os.open(hidraw_device, os.O_RDWR | os.O_NONBLOCK)
        self.__fd = FileIO(self.__report_fd, "rb+", closefd=False)
        self.__input_device = InputDevice(event_device)
        self.__input_device.grab()
        buf = bytearray(38)
        buf[0] = 0x02
        try:
            return bool(fcntl.ioctl(self.__fd, 3223734279, bytes(buf)))
        except:
            pass
        if self.recv():
            self.update_controller() 
Example #2
Source File: btspeaker.py    From intel-iot-refkit with MIT License 6 votes vote down vote up
def run(self):
        global pairing
        devices = [evdev.InputDevice(file_name) for file_name in evdev.list_devices()]
        for dev in devices:
          if 'PRP0001' in dev.name:
            device = evdev.InputDevice(dev.fn)
        while 1:
            r,w,x = select([device.fd], [], [], 0.1)
            if r:
                for event in device.read():
                    if event.code == ecodes.KEY_HOME and event.value == 1:
                        if pairing == False:
                            pairing = True
                            buttonwait.set()

# Following function is heavily inspired by BlueZ tests 
Example #3
Source File: agent.py    From btk with MIT License 6 votes vote down vote up
def RequestPasskey(self, device):
        print("RequestPasskey (%s)" % (device))
        passkey = ""
        kb = ev.InputDevice(glob.glob('/dev/input/by-path/*event-kbd')[0])
        print(kb)
        for event in kb.read_loop():
            data = ev.categorize(event)
            if event.type != ev.ecodes.EV_KEY:
                continue
            elif data.keystate == 0: # ignore keyup
                continue

            key = ev.ecodes.KEY[event.code][4:]
            if key == 'ENTER': # we are done
                break
            elif key in ['1','2','3','4','5','6','7','8','9','0']:
                passkey = passkey + key

        set_trusted(device)
        return int(passkey) 
Example #4
Source File: rc.py    From pycozmo with MIT License 6 votes vote down vote up
def run(self):
        logging.debug("Input thread started.")
        dev = InputDevice(self._controller.event_device)
        fds = {dev.fd: dev}
        while not self._stop:
            try:
                r, _, _ = select(fds, [], [], 0.1)
                for fd in r:
                    for event in fds[fd].read():
                        self._handler(event)
            except IOError as e:
                logging.warning("Input I/O error. {}".format(e))
                time.sleep(3)
                dev = InputDevice(self._controller.event_device)
                # TODO: Handle FileNotFoundError.
                fds = {dev.fd: dev}
        logging.debug("Input thread stopped.") 
Example #5
Source File: input.py    From uchroma with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _open_input_devices(self):
        if self._opened:
            return True

        for input_device in self._input_devices:
            try:
                event_device = evdev.InputDevice(input_device)
                self._event_devices.append(event_device)

                task = ensure_future(self._evdev_callback(event_device))
                task.add_done_callback(functools.partial(self._evdev_close, event_device))
                self._tasks.append(task)

                self._logger.info('Opened event device %s', event_device)

            except Exception as err:
                self._logger.exception("Failed to open device: %s", input_device, exc_info=err)

        if self._event_devices:
            self._opened = True

        return self._opened 
Example #6
Source File: evdevremapkeys.py    From evdevremapkeys with MIT License 6 votes vote down vote up
def find_input(device):
    name = device.get('input_name', None)
    phys = device.get('input_phys', None)
    fn = device.get('input_fn', None)

    if name is None and phys is None and fn is None:
        raise NameError('Devices must be identified by at least one ' +
                        'of "input_name", "input_phys", or "input_fn"')

    devices = [InputDevice(fn) for fn in evdev.list_devices()]
    for input in devices:
        if name is not None and input.name != name:
            continue
        if phys is not None and input.phys != phys:
            continue
        if fn is not None and input.path != fn:
            continue
        if input.path in registered_devices:
            continue
        return input
    return None 
Example #7
Source File: controllers.py    From approxeng.input with Apache License 2.0 5 votes vote down vote up
def unique_name(device: InputDevice) -> str:
    """
    Construct a unique name for the device based on, in order if available, the uniq ID, the phys ID and
    finally a concatenation of vendor, product, version and filename.

    :param device:
        An InputDevice instance to query
    :return:
        A string containing as unique as possible a name for the physical entity represented by the device
    """
    if device.uniq:
        return device.uniq
    elif device.phys:
        return device.phys.split('/')[0]
    return '{}-{}-{}-{}'.format(device.info.vendor, device.info.product, device.info.version, device.path) 
Example #8
Source File: RotaryEncoder.py    From redeem with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, dev, cpr, d):
    self.dev = InputDevice(dev)
    self.cpr = float(cpr)    # Cycles pr revolution
    self.d = d
    self.distance = 0
    self.step = 0
    self.t = Thread(target=self._wait_for_event, name="RotaryEncoder")
    self.running = True
    self.t.start() 
Example #9
Source File: EndStop.py    From redeem with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, printer, pin, key_code, name, invert=False):
    self.printer = printer
    self.pin = pin
    self.key_code = key_code
    self.invert = invert
    self.dev = InputDevice(EndStop.inputdev)

    self.name = name
    if name == "X1":
      self.condition_bit = (1 << 0)
    elif name == "Y1":
      self.condition_bit = (1 << 1)
    elif name == "Z1":
      self.condition_bit = (1 << 2)
    elif name == "X2":
      self.condition_bit = (1 << 3)
    elif name == "Y2":
      self.condition_bit = (1 << 4)
    elif name == "Z2":
      self.condition_bit = (1 << 5)
    else:
      raise RuntimeError('Invalid endstop name')

    # Update "hit" state
    self.read_value()

    logging.debug("starting endstop %s", self.name)

    self.key_pin = Key_pin(self.name + "_pin", self.key_code, 0xff, self._handle_event)
    self.active = True 
Example #10
Source File: Key_pin.py    From redeem with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, fd, iomanager):
    self.dev = InputDevice(fd)
    self.iomanager = iomanager
    self.keys = {} 
Example #11
Source File: hid.py    From pyLCI with Apache License 2.0 5 votes vote down vote up
def get_input_devices():
    """Returns list of all the available InputDevices"""
    return [HID(fn) for fn in list_devices()] 
Example #12
Source File: hid.py    From pyLCI with Apache License 2.0 5 votes vote down vote up
def get_path_by_name(name):
    """Gets HID device path by name, returns None if not found."""
    path = None
    for dev in get_input_devices():
        if dev.name == name:
            path = dev.fn
    return path 
Example #13
Source File: hid.py    From pyLCI with Apache License 2.0 5 votes vote down vote up
def get_name_by_path(path):
    """Gets HID device path by name, returns None if not found."""
    name = None
    for dev in get_input_devices():
        if dev.fn == path:
            name = dev.name
    return name 
Example #14
Source File: hid.py    From pyLCI with Apache License 2.0 5 votes vote down vote up
def init_hw(self):
        try:
            self.device = HID(self.path)
        except OSError:
            print("Failed HID")
            return False
        else:
            self.device.grab() #Can throw exception if already grabbed
            return True 
Example #15
Source File: mouse_client.py    From keyboard_mouse_emulate_on_raspberry with MIT License 5 votes vote down vote up
def event_loop():
    while True:
        for i in InputDevice.inputs:
            try:
                for event in i.device.read():
                    i.change_state(event)
            except OSError as err:
                if err.errno == errno.ENODEV:
                    InputDevice.remove_device(i)
                    warning(err) 
Example #16
Source File: controllers.py    From approxeng.input with Apache License 2.0 5 votes vote down vote up
def _check_import():
    """
    Checks whether we imported evdev - it's possible we didn't if we were run as part of a documentation build on a
    system such as OSX which is quite capable of building the docs but can't install evdev. Any attempt to actually
    run this code on such a system should fail as early as possible, we can't fail the import without being unable
    to build docs, but all functions in this module will check to see whether we imported properly and fail if we
    didn't

    :raises ImportError:
    """
    if InputDevice is None:
        raise ImportError('evdev was not imported successfully, nothing will work.') 
Example #17
Source File: inputdev.py    From btk with MIT License 5 votes vote down vote up
def __init__(self, dev_paths, report_id):
        self.devs = [ev.InputDevice(dev_path) for dev_path in dev_paths]
        self.state = [
            0xA1, # This is an input report by USB
            report_id, # Report Id assigned for Mouse, in HID Descriptor
        ] 
Example #18
Source File: daemon.py    From system76-driver with GNU General Public License v2.0 5 votes vote down vote up
def find_device(self, name):
        for ev_path in evdev.list_devices():
            device = evdev.InputDevice(ev_path)
            if device.name == name:
                return device
        return None 
Example #19
Source File: daemon.py    From system76-driver with GNU General Public License v2.0 5 votes vote down vote up
def find_device(self, name):
        for ev_path in evdev.list_devices():
            device = evdev.InputDevice(ev_path)
            if device.name == name:
                return device
        return None 
Example #20
Source File: keyboard_recorder.py    From mozc-devices with Apache License 2.0 5 votes vote down vote up
def __init__(self, verbose=False):
    if evdev is None:
      raise TypeError('KeyboardRecorderFromEvdev needs to be used on Linux ' +
                      '(or POSIX compatible) system. Instead, You can try it ' +
                      'on your console.')
    KeyboardRecorder.__init__(self, verbose)
    self.log('Input from evdev')
    keyboards = []
    ecode_ev_key = evdev.ecodes.ecodes['EV_KEY']
    ecode_key_esc = evdev.ecodes.ecodes['KEY_ESC']
    for device in [evdev.InputDevice(fn) for fn in evdev.list_devices()]:
      # TODO(shimazu): Consider more solid criteria to get 'regular' keyboards.
      if ecode_ev_key in device.capabilities() and \
         ecode_key_esc in device.capabilities()[ecode_ev_key]:
        keyboards.append(device)
    if len(keyboards) == 0:
      raise IOError('No keyboard found.')
    self._keyboards = keyboards
    for keyboard in keyboards:
      self.log('----')
      self.log(keyboard)
      self.log('name: {0}'.format(keyboard.name))
      self.log('phys: {0}'.format(keyboard.phys))
      self.log('repeat: {0}'.format(keyboard.repeat))
      self.log('info: {0}'.format(keyboard.info))
      self.log(keyboard.capabilities(verbose=True)) 
Example #21
Source File: joy.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def setupJoysticks():
    """Search for joysticks"""
    devices = [InputDevice(path) for path in list_devices()]
    for device in devices:
        try:
            index = JOYSTICKNAMES.index(device.name)
            #this is a known joystick, add it to the array
            #index will throw a ValueError if not found
            logging.debug(f'adding {device}')
            joystick = {}
            joystick['device'] = device
            joystick['path'] = device.path
            #force joystick color by USB port
            if device.phys.find('usb-1.3')>0:
                #top right, red
                index = 0
            elif device.phys.find('usb-1.2')>0:
                #bottom right, blue
                index = 1
            elif device.phys.find('usb-1.1.2')>0:
                #top left, white
                index = 2
            elif device.phys.find('usb-1.1.3')>0:
                #bottom left, black
                index = 3
            joystick['color'] = JOYSTICKSBYINPUT[index]
            joystick['move'] = ''
            joystick['movelocked'] = False
            joystick['movetopic'] = 'joystick/move/' + JOYSTICKSBYINPUT[index]
            joystick['statustopic'] = 'joystick/status/' + JOYSTICKSBYINPUT[index]
            joystick['lights'] = LIGHTS[len(joysticks)]
            joysticks.append(joystick)
            logging.info(f'{joysticks}')
            logging.info(f'{joysticks[len(joysticks)-1]} joystick added')
        except ValueError:
                logging.debug(f'not adding {device.path} : {device.name}')
    logging.info(f'Joysticks found: {joysticks}') 
Example #22
Source File: mouse_client.py    From keyboard_mouse_emulate_on_raspberry with MIT License 5 votes vote down vote up
def set_leds_all(ledvalue):
        for dev in InputDevice.inputs:
            dev.set_leds(ledvalue) 
Example #23
Source File: badgereader_hid_keystroking.py    From makerspace-auth with Apache License 2.0 5 votes vote down vote up
def get_scanner_device(self):
        """Finds connected device matching device_name.

        Returns:
          The file for input events that read_input can listen to
        """

        devices = [evdev.InputDevice(x) for x in evdev.list_devices()]
        for dev in devices:
            if str(dev.name) == self._device_name:
                return dev

        raise NoMatchingDevice(
            self._device_name, [d.name for d in devices], "check permissions?"
        ) 
Example #24
Source File: wheels.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def set_autocenter(self, device_id, autocenter):
        autocenter = str(int(65535 * autocenter / 100))
        logging.debug("Setting autocenter strength: " + autocenter)
        path = self.checked_device_file(device_id, "autocenter")
        if path:
            with open(path, "w") as file:
                file.write(autocenter)
        else:
            dev = InputDevice(self.devices[device_id]['dev'])
            dev.write(ecodes.EV_FF, ecodes.FF_AUTOCENTER, int(autocenter))
        return True 
Example #25
Source File: wheels.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def set_ff_gain(self, device_id, gain):
        gain = str(int(65535 * gain / 100))
        logging.debug("Setting FF gain: " + gain)
        path = self.checked_device_file(device_id, "gain")
        if path:
            with open(path, "w") as file:
                file.write(gain)
        else:
            dev = InputDevice(self.devices[device_id]['dev'])
            dev.write(ecodes.EV_FF, ecodes.FF_GAIN, int(gain)) 
Example #26
Source File: gui.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def change_device(self, device_id):
        if device_id == None:
            self.device = None
            return

        self.device = InputDevice(self.wheels.id_to_dev(device_id))

        if not self.wheels.check_permissions(device_id):
            self.install_udev_file()

        self.read_settings(device_id)

        self.ui.set_ffbmeter_overlay(False)
        self.ui.set_wheel_range_overlay('never') 
Example #27
Source File: gui.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def set_emulation_mode(self, device_id, mode):
        self.device.close()
        self.device = None
        self.wheels.set_mode(device_id, mode)
        self.emulation_mode = mode
        self.device = InputDevice(self.wheels.id_to_dev(device_id))
        self.ui.set_device_id(device_id)
        self.read_settings(device_id, True) 
Example #28
Source File: tinyjoy.py    From fygimbal with MIT License 5 votes vote down vote up
def _default_joystick(self):
        """Return the first (sorted) device with an absolute X axis."""
        for fn in sorted(evdev.list_devices()):
            device = evdev.InputDevice(fn)
            for axis, info in device.capabilities().get(evdev.ecodes.EV_ABS, []):
                if axis == evdev.ecodes.ABS_X:
                    return device
        raise IOError('No joystick device found') 
Example #29
Source File: io_evdev_keyboard.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def list_devices(self):
        devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
        def hasAKey(device):
            caps = device.capabilities(verbose=True)
            events = caps.get(('EV_KEY', 1), [])
            a_keys = [e for e in events if e[0] == 'KEY_A']
            return len(a_keys) > 0
        
        return list(filter(hasAKey, devices)) 
Example #30
Source File: io_evdev_keyboard.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def reader_thread(self):
        # A mapping of file descriptors (integers) to InputDevice instances.
        devices = {dev.fd: dev for dev in self.devices}

        while True:
            r, w, x = select(devices, [], [])
            for fd in r:
                for event in devices[fd].read():
                    ce = evdev.categorize(event)
                    if isinstance(ce, evdev.KeyEvent):
                        self.handle_key(ce.keycode, ce.keystate)

        return