Python evdev.list_devices() Examples

The following are 15 code examples of evdev.list_devices(). 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: 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 #2
Source File: evdevremapkeys.py    From evdevremapkeys with MIT License 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Re-bind keys for input devices')
    parser.add_argument('-f', '--config-file',
                        help='Config file that overrides default location')
    parser.add_argument('-l', '--list-devices', action='store_true',
                        help='List input devices by name and physical address')
    parser.add_argument('-e', '--read-events', metavar='EVENT_ID',
                        help='Read events from an input device by either '
                        'name, physical address or number.')

    args = parser.parse_args()
    if args.list_devices:
        print("\n".join(['%s:\t"%s" | "%s' %
              (fn, phys, name) for (fn, phys, name) in list_devices()]))
    elif args.read_events:
        read_events(args.read_events)
    else:
        run_loop(args) 
Example #3
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 #4
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 #5
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 #6
Source File: io_evdev_keyboard.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bus):
        self.devices = self.list_devices()

        if len(self.devices) == 0:
            logger.warn("Can't find any keyboards to read from - maybe you need permissions")
        else:
            logger.info("Reading key events from: {}".format(self.devices))

        super().__init__(bus) 
Example #7
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 #8
Source File: evdevremapkeys.py    From evdevremapkeys with MIT License 5 votes vote down vote up
def list_devices():
    devices = [InputDevice(fn) for fn in evdev.list_devices()]
    for device in reversed(devices):
        yield [device.fn, device.phys, device.name] 
Example #9
Source File: evdevremapkeys.py    From evdevremapkeys with MIT License 5 votes vote down vote up
def read_events(req_device):
    for device in list_devices():
        # Look in all 3 identifiers + event number
        if req_device in device or \
           req_device == device[0].replace("/dev/input/event", ""):
            found = evdev.InputDevice(device[0])

    if 'found' not in locals():
        print("Device not found. \n"
              "Please use --list-devices to view a list of available devices.")
        return

    print(found)
    print("To stop, press Ctrl-C")

    for event in found.read_loop():
        try:
            if event.type == evdev.ecodes.EV_KEY:
                categorized = evdev.categorize(event)
                if categorized.keystate == 1:
                    keycode = categorized.keycode if type(categorized.keycode) is str \
                        else " | ".join(categorized.keycode)
                    print("Key pressed: %s (%s)" % (keycode, categorized.scancode))
        except KeyError:
            if event.value:
                print("Unknown key (%s) has been pressed." % event.code)
            else:
                print("Unknown key (%s) has been released." % event.code) 
Example #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: controllers.py    From approxeng.input with Apache License 2.0 4 votes vote down vote up
def find_all_controllers(**kwargs) -> List[ControllerDiscovery]:
    """
    :return:
        A list of :class:`~approxeng.input.controllers.ControllerDiscovery` instances corresponding to controllers
        attached to this host, ordered by the ordering on ControllerDiscovery. Any controllers found will be
        constructed with kwargs passed to their constructor function, particularly useful for dead and hot zone
        parameters.
    """

    def get_controller_classes() -> [{}]:
        """
        Scans for subclasses of :class:`~approxeng.input.Controller` and reads out data from their
        :meth:`~approxeng.input.Controller.registrations_ids` method. This should return a list of
        tuples of `(vendor_id, product_id)` which are then used along with the subclass itself to
        populate a registry of known subclasses.

        :return:
            A generator that produces known subclasses and their registration information
        """
        for controller_class in Controller.__subclasses__():
            for vendor_id, product_id in controller_class.registration_ids():
                yield {'constructor': controller_class,
                       'vendor_id': vendor_id,
                       'product_id': product_id}

    id_to_constructor = {'{}-{}'.format(c['vendor_id'], c['product_id']): c['constructor'] for c in
                         get_controller_classes()}

    def controller_constructor(d: InputDevice):
        id = '{}-{}'.format(d.info.vendor, d.info.product)
        if id in id_to_constructor:
            return id_to_constructor[id]
        return None

    all_devices = list(InputDevice(path) for path in list_devices())

    devices_by_name = {name: list(e for e in all_devices if unique_name(e) == name) for name in
                       set(unique_name(e) for e in all_devices if
                           controller_constructor(e) is not None)}

    controllers = sorted(
        ControllerDiscovery(controller=controller_constructor(devices[0])(**kwargs), devices=devices, name=name) for
        name, devices in devices_by_name.items())

    return controllers