Example #1
1
    def run(self):
        devices = map(InputDevice, list_devices())
        for device in devices:
            if device.name == RFID_DEVICE:
                dev = InputDevice(device.fn)
        try:
            dev.grab()
        except:
            logger.error("Unable to grab InputDevice")
            sys.exit(1)

        logger.info("Starting the Kiosk Reader daemon...")
        while True:
            rfid = ""
            for event in dev.read_loop():
                if event.type == ecodes.EV_KEY:
                    data = categorize(event)
                    if data.keystate == 1 and data.scancode != 42: # Catch only keydown, and not Enter
                        if data.scancode == 28:
                            # We have a RFID tag
                            logger.info("RFID tag read: %s" % rfid)
                            url = "https://marmix.ig.he-arc.ch/gelato/w/rfid/%s/%s/" % (KIOSK, rfid)
                            url_string = "uri " + url
                            uzblctrl(url_string)
                            rfid = ""
                        else:
                            rfid += SCANCODES[data.scancode]
Example #2
0
    def __init__(self, kbname, lidname):
        self.key = next(InputDevice(dev) for dev in list_devices() if kbname in InputDevice(dev).name)
        self.lid = next(InputDevice(dev) for dev in list_devices() if lidname in InputDevice(dev).name)
        self.loop = asyncio.get_event_loop()
        self.listening = False
        self.sequence = []
        self.finish_handle = None
        self.lastlid = 0

        self.patterns = []
Example #3
0
def detectInputKey():
    devices = [InputDevice(fn) for fn in list_devices()]
    find_dev = False
    for dev in devices:
        dev_name = dev.name
        if "keyboard" in dev_name or "kbd" in dev_name:
            find_dev = True
            break
    if not find_dev:
        return
    dev = InputDevice(dev.fn)
    key = Key()
    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            key_event = categorize(event)
            timestamp = key_event.event.timestamp()
            if 1 in dev.leds():
                key.caps_lock = 1
            else:
                key.caps_lock = 0
            if 0 in dev.leds():
                key.num_lock = True

            try:
                ks = ('up', 'down', 'hold')[key_event.keystate]
                args = ({"key_code": key_event.scancode}, {"timestamp":timestamp, "key_code": key_event.scancode}, {"key_code": key_event.scancode})[key_event.keystate]
                run_func = getattr(key, ks)(**args)
            except IndexError:
                ks = 'unknown'
Example #4
0
    def __init__(self):
        context = pyudev.Context()
        self._topic  = str(mt.Sensors.Keyboard)
        self._monitor = pyudev.Monitor.from_netlink(context)
        self._monitor.filter_by(subsystem='input')
        # NB: Start monitoring BEFORE we query evdev initially, so that if
        # there is a plugin after we evdev.list_devices() we'll pick it up
        self._monitor.start()

        self._event = None
 
        # Populate the "active devices" map, mapping from /dev/input/eventXX to
        # InputDevice
        self._devices = {}
        for d in map(evdev.InputDevice, evdev.list_devices()):
            if self.pred(d):
                print d
                self._devices[d.fn] = d

        # "Special" monitor device
        self._devices['monitor'] = self._monitor

        # start a new thread that continuously polls the keys/devices
        self._keepRunning = True
        self._readThread = threading.Thread(target=self.readEvents)
        self._readThread.start()
def main():
	devices = [InputDevice(fn) for fn in list_devices()]
	viewer = subprocess.Popen(['eog', "image/alphabet.jpg", "-fg"], stdout = subprocess.PIPE, stderr=subprocess.PIPE)
	singer = subprocess.Popen(['mplayer', "image/null.mp3"], stdout = subprocess.PIPE, stderr=subprocess.PIPE)
	
	for dev in devices :
		if re.search("KB", dev.name) : #Put something that can define your keyboard name here
			print("Using input device at : "+dev.fn)
			keyb = dev#break #Normally you need to break, 
							 #but I comment it as my keyboard contains a section for media-player
							 #which is presented as another device with the same name.
	for event in keyb.read_loop():
		if event.type == ecodes.EV_KEY and event.value == 0x1 :
			if event.code == ecodes.KEY_ESC: #Quit
				singer.terminate()
				singer.kill()
				subprocess.Popen(["mplayer", "sound/goodbye.mp3"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
				time.sleep(2)
				singer.terminate()
				singer.kill()
				viewer.terminate()
				viewer.kill()
				quit()
			#Continue program
			viewer.terminate()
			viewer.kill()
			singer.terminate()
			singer.kill()
			#print(categorize(event)) #Uncomment if you need to debug
			singer = sing(event.code)
			viewer = show(event.code)
Example #6
0
def select_devices(device_dir='/dev/input'):
    '''
    Select one or more devices from a list of accessible input devices.
    '''

    def devicenum(device_path):
        digits = re.findall('\d+$', device_path)
        return [int(i) for i in digits]

    devices = sorted(list_devices(device_dir), key=devicenum)
    devices = [InputDevice(path) for path in devices]
    if not devices:
        msg = 'error: no input devices found (do you have rw permission on %s/*?)'
        print(msg % device_dir, file=sys.stderr)
        sys.exit(1)

    dev_format = '{0:<3} {1.fn:<20} {1.name:<35} {1.phys}'
    dev_lines  = [dev_format.format(n, d) for n, d in enumerate(devices)]

    print('ID  {:<20} {:<35} {}'.format('Device', 'Name', 'Phys'))
    print('-' * len(max(dev_lines, key=len)))
    print('\n'.join(dev_lines))
    print()

    choices = input('Select devices [0-%s]: ' % (len(dev_lines)-1))

    try:
        choices = choices.split()
        choices = [devices[int(num)] for num in choices]
    except ValueError:
        msg = 'error: invalid input - please enter one or more numbers separated by spaces'
        print(msg, file=sys.stderr)
        sys.exit(1)

    return choices
Example #7
0
def main(config):
    graphite_server = config.get("graphite", "server")
    graphite_prefix = config.get("graphite", "prefix")
    print "Initializing graphiteudp, server: {}, prefix: {}".format(graphite_server, graphite_prefix)
    graphiteudp.init(graphite_server, prefix=graphite_prefix)
    dbfile = os.path.join(os.environ.get('HOME'), 'scans.sqlite3')
    dbfile = 'scans.sqlite3'
    need_schema = False
    if not os.path.exists(dbfile):
        need_schema = True

    db = sqlite3.connect(dbfile)

    if need_schema:
        db.execute('create table scans(barcode text, timestamp datetime, event_id text)')

    dev = [InputDevice(device) for device in list_devices()
           if InputDevice(device).name == scanner_name][0]

    def signal_handler(signal, frame):
        print 'Stopping'
        dev.ungrab()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    dev.grab()

    barcode = ""
    last_event_time = 0
    last_event_id = None

    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            data = categorize(event)
            # Catch only keydown, and not Enter
            if data.keystate == 1 and data.scancode != 42:
                if data.scancode == 28:
                    timestamp = time.time()

                    if timestamp - last_event_time < 10:
                        event_id = last_event_id
                    else:
                        event_id = uuid.uuid1()
                        last_event_id = event_id

                    last_event_time = timestamp

                    graphiteudp.send('event.scan', 1)
                    db.execute(
                        'insert into scans (barcode, timestamp, event_id) ' +
                        'values (:barcode, :timestamp, :event_id)',
                        [barcode, timestamp, event_id.get_urn()])
                    db.commit()
                    barcode = ""
                else:
                    try:
                        barcode += scancodes[data.scancode]
                    except KeyError:
                        print >>sys.stderr, "Unknown scancode: {0}".format(data.scancode)
Example #8
0
    def __init__(self, deviceVendor, deviceProduct):

        QThread.__init__(self)

        # Get list of available devices
        devices = map(InputDevice, list_devices())

        # Try to find the desired device
        for device in devices:

            # If multiple devices of same type available,
            # select the first, e.g. phys ".../input0"
            isDesiredDevice = \
                (device.info.vendor == deviceVendor) and \
                (device.info.product == deviceProduct) and \
                (device.phys.endswith('0'))

            if isDesiredDevice:
                self.device = device
                break

        # Get exclusive access to the device
        if self.isConnected():
            print 'Grab keypad input device.'
            self.device.grab()
def initiate_gesture_find():
    """
    This function will scan all input devices until it finds an
    ELAN touchscreen. It will then enter a loop to monitor this device
    without blocking its usage by the system.
    """
    for device in list_devices():
        dev = InputDevice(device)
        if (dev.name == 'ELAN Touchscreen') or (dev.name == 'Atmel Atmel maXTouch Digitizer'):
            break
    codes = dev.capabilities()
    Abs_events = {}
    for code in codes:
        if code == 3:
            for type_code in codes[code]:
                Abs_events[type_code[0]] = ecodes.ABS[type_code[0]]

    MT_event = None
    for event in dev.read_loop():
        if MT_event:
            if MT_event.discard == 1:
                MT_event = None
        if event.type == ecodes.EV_ABS:
            if MT_event is None:
                MT_event = TrackedEvent()
            event_code = Abs_events[event.code]
            if event_code == 'ABS_MT_SLOT':
                MT_event.add_finger(event.value)
            elif event_code == 'ABS_X' or event_code == 'ABS_Y':
                MT_event.position_event(event_code, event.value)
            elif event_code == 'ABS_MT_TRACKING_ID':
                if event.value == -1:
                    MT_event.remove_fingers()
                else:
                    MT_event.trackit()
Example #10
0
    def __init__(self, disptach_event = None, threadID=0):
        '''
        Initialises parameters to manage the joystick asynchornously.
        When this thread class is instantiated the thread ID should be passed to it
        '''
        self.sense = SenseHat()
        self.device = None

        # Check for the joystick presence
        devices = [InputDevice(fn) for fn in list_devices()]
        for dev in devices:
            if dev.name == JOYSTICK_NAME:
                self.device = dev # Device found!
                break

        if self.device is None:
            if DEBUG:
                print('Raspberry Pi Sense HAT Joystick not found. Aborted')
        else:
            # If the dispatch event method callback has not been specified, the thread is not started
            if disptach_event is not None:
                # Initializes the thread parent class and get the thread ID parameter
                self.dispatch = disptach_event
                Thread.__init__(self)
                self.threadID = threadID
                if DEBUG:
                    print('Thread.__init__()')
Example #11
0
 def __init__(self, state="down"):
     resource.CoAPResource.__init__(self)
     self.state = state
     self.visible = True
     devices = [InputDevice(fn) for fn in list_devices()]
     self.device = [d for d in devices if d.name == JOYSTICK_DEVICE_NAME][0]
     self.tstamp = time.time()
def Configure():
	devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]

	for i in range(0, len(devices)):
		print(str(i)+' - '+devices[i].name+'('+devices[i].fn+', '+devices[i].phys+')')

	devId = input ('Select device id: ')

	device = devices[devId]

	keyremap = []

	for i in range (len(xboxdrvUtil.keymap)):
		print("Button for "+xboxdrvUtil.keymap[i]+": ")
		press = ReadInput(device)
		print(press)
		keyremap.append(press)

	absremap = []

	for i in range (len(xboxdrvUtil.absmap)):
		print("Axis for "+xboxdrvUtil.absmap[i]+": ")
		press = ReadInput(device)
		print(press)
		absremap.append(press)

	cfgfile = open((device.name).replace(" ", ""),'w')

	xboxdrvUtil.PrintConfig(cfgfile, keyremap, absremap)

	cfgfile.close()

	print("\nSaved as: "+cfgfile.name+"\n")
Example #13
0
 def follow_mouse (self):
     devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
     for dev in devices:
         if "Mouse" in  dev.name:
             break
     else:
         print ("No mouse found. Please check usb input.")
         return
     posB, posA = self.mot_B.position, self.mot_A.position
     ciblex, cibley = Writer.motorpos_to_coordinates (posB, posA)
     self.pen_up()
     while True:
         try:
             for event in dev.read():
                 if (event.type == evdev.ecodes.EV_KEY and event.code == evdev.ecodes.BTN_LEFT):
                     if (event.value):
                         self.pen_down(wait=0)
                     else:
                         self.pen_up(wait=0)
                 if (event.type == evdev.ecodes.EV_REL and event.code == evdev.ecodes.REL_X):
                     ciblex -= event.value/100.
                 if (event.type == evdev.ecodes.EV_REL and event.code == evdev.ecodes.REL_Y):
                     cibley += event.value/100.
         except:
             pass
         if (not self.set_speed_to_coordinates (ciblex,cibley,brake=1.0,max_speed = 100)):
             self.mot_A.stop(stop_command='hold')
             self.mot_B.stop(stop_command='hold')
         time.sleep(0.1)
Example #14
0
    def __init__(self, hass, device_name, device_descriptor, key_value):
        """Construct a thread listening for events on one device."""
        self.hass = hass
        self.device_name = device_name
        self.device_descriptor = device_descriptor
        self.key_value = key_value

        if self.device_descriptor:
            self.device_id = self.device_descriptor
        else:
            self.device_id = self.device_name

        self.dev = self._get_keyboard_device()
        if self.dev is not None:
            _LOGGER.debug("Keyboard connected, %s", self.device_id)
        else:
            _LOGGER.debug(
                "Keyboard not connected, %s. "
                "Check /dev/input/event* permissions", self.device_id)

            id_folder = '/dev/input/by-id/'

            if os.path.isdir(id_folder):
                from evdev import InputDevice, list_devices
                device_names = [InputDevice(file_name).name
                                for file_name in list_devices()]
                _LOGGER.debug(
                    "Possible device names are: %s. "
                    "Possible device descriptors are %s: %s",
                    device_names, id_folder, os.listdir(id_folder))

        threading.Thread.__init__(self)
        self.stopped = threading.Event()
        self.hass = hass
Example #15
0
 def list(cls, show_all=False):
     # list the available devices
     devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
     if show_all:
         for device in devices:
             print("event: " + device.fn, "name: " + device.name, "hardware: " + device.phys)
     return devices
Example #16
0
def get_device():
    dev = None
    devices = map(InputDevice, list_devices())
    for device in devices:
        if device.name == READER_DEVICE:
            dev = InputDevice(device.fn)
    return dev
Example #17
0
    def _connect_to_device(self):
        try:
            if self._scanner != None:
                self._scanner.ungrab()
        except:
            pass

        scanner_found = False

        try:
            devices = map(InputDevice, list_devices())

            for device in devices:
                if device.name == self._scan_device:
                    self._scanner = InputDevice(device.fn)
                    scanner_found = True
        except:
            print('Could not connect to scanner. Trying again in a few seconds.')

            time.sleep(self._error_wait_time)
            self._connect_to_device()

        if not scanner_found:
            print('No scanner found. Trying again in a few seconds.')

            time.sleep(self._error_wait_time)
            self._connect_to_device()
        else:
            print('Connected to the scanner.')
Example #18
0
def hook_linux_pyzmo():
    from pyzmo import chord
    from evdev import list_devices, InputDevice

    print("OK")
    print(InputDevice('/dev/input/event1'))
    print(list_devices())
    functions = {}
    for key_combination, action in SHORTCUTS:
        @chord(*key_combination)
        def _f(events):
            action()
        functions[key_combination] = _f

    print(list_devices())
    for dev in list_devices():
        print(dir(dev))
def selectDevice():
	'''Connect to the joystick or quit if one is not connected'''
	devices = [InputDevice(i) for i in reversed(list_devices('/dev/input/'))]
	if(len(devices) >2):
		return devices[2]
	else:
		print("No joysticks found!)")
		exit()
Example #20
0
    def __init__(self, msg_queue, dev_names, keymap_file = '../data/keymap.xml'):
        multiprocessing.Process.__init__(self)
        self.msg_queue = msg_queue
        self.read_keymap(keymap_file)
	available_devices = list_devices()
	devices_to_use = [d for d in dev_names if d in available_devices]
        devices = map(InputDevice, devices_to_use)
        self.devices = {dev.fd: dev for dev in devices}
def selectDevice():
	'''Select a device from the list of accessible input devices.'''
	devices = [InputDevice(i) for i in reversed(list_devices('/dev/input/'))]
	if(len(devices) > 2):
		return devices[2]
	else:
		print("No joysticks found!")
		exit()
def get_scanner_device():
    devices = map(InputDevice, list_devices())
    device = None
    for dev in devices:
        if dev.name == 'RFIDeas USB Keyboard':
            device = dev
            break
    return device
Example #23
0
def findDevice():
    devs = [InputDevice(fn) for fn in list_devices()]

    for dev in devs:
        if(re.search('eyboard', dev.name)):
            kb_device = dev.fn
            return kb_device
    return False
Example #24
0
def get_scanner_device():
    devices = map(InputDevice, list_devices())
    device = None
    for dev in devices:
        if dev.name == DEVICE_NAME:
            device = dev
            break
    return device
Example #25
0
def main(argv=sys.argv[1:]):
    """
    Parse command line arguments and act accordingly.

    :param argv: command line arguments
    :type argv: list
    :returns: application exit code
    :rtype: int
    """
    info = evmapy.util.get_app_info()
    parser = argparse.ArgumentParser(prog=info['name'])
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-L", "--list-all", action='store_true',
                       help="list available devices")
    group.add_argument("-l", "--list", action='store_true',
                       help="list currently handled devices")
    group.add_argument("-G", "--generate", metavar="DEVICE",
                       help="generate a sample configuration for DEVICE")
    group.add_argument("-g", "--generate-minimal", metavar="DEVICE",
                       help="generate a minimal configuration for DEVICE")
    group.add_argument("-c", "--configure", metavar="DEVICE:FILE",
                       help="load DEVICE configuration from FILE")
    group.add_argument("-D", "--debug", action='store_true',
                       help="run in debug mode")
    args = parser.parse_args(argv)
    if args.list_all:
        for dev_path in evdev.list_devices():
            device = evdev.InputDevice(dev_path)
            print("%s: %s" % (device.fn, device.name))
    elif args.list:
        devices = evmapy.controller.perform_request({
            'command':  'list',
            'wait':     True,
        })
        for device in devices:
            print("%(path)s: %(name)s" % device)
    elif args.generate:
        exit(evmapy.config.create(args.generate))
    elif args.generate_minimal:
        exit(evmapy.config.create(args.generate_minimal, with_actions=False))
    elif args.configure:
        try:
            (dev_path, config_file) = args.configure.split(':')
        except ValueError:
            exit("Bad --configure argument syntax")
        evmapy.controller.perform_request({
            'command':  'config',
            'device':   dev_path,
            'file':     config_file,
            'wait':     False,
        })
    else:
        info = evmapy.util.get_app_info()
        logger = initialize_logging(info['name'], args.debug)
        logger.info("%s %s initializing", info['name'], info['version'])
        logger.info("running as user %s", info['user'].pw_name)
        logger.info("using configuration directory %s", info['config_dir'])
        evmapy.multiplexer.Multiplexer().run()
    def __init__(self, argv, config=dict()):
        self.dev = None

        self.edges = ["left", "top", "right", "bottom"]
        self.gestures = {"left":0,
                         "top": 1,
                         "right": 2,
                         "bottom": 3}
        self.orientations = {"normal": 0,
                             "left": 1,
                             "inverted": 2,
                             "right": 3}

        self.checkOrientation = bool(config.get('checkOrientation', True))

        self.ecodesX = ecodes.ABS_MT_POSITION_X
        self.ecodesY = ecodes.ABS_MT_POSITION_Y

        self.running = False
        self.counter = 0
        self.last_tap = -1

        self.margin = int(config.get('margin', 2))
        self.touching = 0
        self.handling = ""

        self.value = -1
        self.last_value = -1

        self.min_x = self.min_y = self.max_x = self.max_y = self.min_xy = -1

        self.deviceName = config.get('deviceName', None)

        searchTerm = ((self.deviceName is not None and self.deviceName) or
                      (len(argv) > 1 and argv[1] or "finger")
                      )

        for d in evdev.list_devices():
            de = InputDevice(d)
            if de.name.lower().rfind(searchTerm.lower()) > 0:
                self.dev = de
                break

        print("device: ", self.dev, file=sys.stderr)
        if self.dev:
            for cap in self.dev.capabilities()[ecodes.EV_ABS]:
                if cap[0] == self.ecodesX:
                    self.min_x = int(config.get('min_x', cap[1].min))
                    self.max_x = int(config.get('max_x', cap[1].max))
                elif cap[0] == self.ecodesY:
                    self.min_y = int(config.get('min_y', cap[1].min))
                    self.max_y = int(config.get('max_y', cap[1].max))

            self.min_xy = min(self.max_y - self.min_y, self.max_x - self.min_x)
            print("min x: ", self.min_x, file=sys.stderr)
            print("max x: ", self.max_x, file=sys.stderr)
            print("min y: ", self.min_y, file=sys.stderr)
            print("max y: ", self.max_y, file=sys.stderr)
 def findEzKey(self):
   device = None
   devices = [InputDevice(fn) for fn in list_devices()]
   for dev in devices:
     if re.match('Adafruit EZ-Key|Zeemote: SteelSeries FREE', dev.name):
       print(dev.fn)
       device = dev.fn
       break
   return device
def list_devices():
    devices = [(int(DEV_ID_PATTERN.findall(fn)[0]), evdev.InputDevice(fn))
               for fn in evdev.list_devices()]

    dev_id_len = len(str(max([dev_id for dev_id, dev in devices])))

    for dev_id, dev in sorted(devices, key=lambda x: x[0]):
        print("%s: %s (%s, %s)" %
              (str(dev_id).rjust(dev_id_len), dev.name, dev.fn, dev.phys))
Example #29
0
 def get_matching_devices(self):
     self.matches=0
     self.matching_devices=[]
     devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
     for device in devices:
         if self.selected_device_name in device.name:
             device_ref = evdev.InputDevice(device.fn)
             self.matching_devices.append(device_ref)
             self.matches+=1
Example #30
0
def joystickSetup():
	devices = [InputDevice(fn) for fn in list_devices()]
	for dev in devices:
		if dev.name == "Raspberry Pi Sense HAT Joystick":
			dev = InputDevice(dev.fn)
			print "Listenting to " + dev.name
			break

	return dev
Example #31
0
def findAC511():
  # print "find";

  ac511Event = None;

  devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
  for device in devices:
    if device.name.find(devName) != -1:
      ac511Event = device.fn;

  if ac511Event is not None:
    openAC511(ac511Event);

  return;
Example #32
0
    def run(self):
        """Do what get_devices describes."""
        # evdev needs asyncio to work
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        logger.debug('Discovering device paths')
        devices = [evdev.InputDevice(path) for path in evdev.list_devices()]

        # group them together by usb device because there could be stuff like
        # "Logitech USB Keyboard" and "Logitech USB Keyboard Consumer Control"
        grouped = {}
        for device in devices:
            if device.name == 'Power Button':
                continue

            # only keyboard devices
            # https://www.kernel.org/doc/html/latest/input/event-codes.html
            capabilities = device.capabilities(absinfo=False)
            if EV_KEY not in capabilities and EV_ABS not in capabilities:
                # or gamepads, because they can be mapped like a keyboard
                continue

            is_gamepad = map_abs_to_rel(capabilities)

            name = device.name
            path = device.path

            info = str(device.info)
            if grouped.get(info) is None:
                grouped[info] = []

            logger.spam('Found "%s", "%s", "%s"', info, path, name)

            grouped[info].append((name, path, is_gamepad))

        # now write down all the paths of that group
        result = {}
        for group in grouped.values():
            names = [entry[0] for entry in group]
            devs = [entry[1] for entry in group]
            is_gamepad = True in [entry[2] for entry in group]
            shortest_name = sorted(names, key=len)[0]
            result[shortest_name] = {
                'paths': devs,
                'devices': names,
                'gamepad': is_gamepad
            }

        self.pipe.send(result)
Example #33
0
    def enumerate(self):
        self.dev = None
        print "enumerating joystick..."
	while not rospy.is_shutdown() and self.dev==None:
                devices = map(InputDevice, list_devices())
                for d in devices:
                    print d.name
                    if "pad" in d.name.lower():
                        self.dev = d
                        break
                if self.dev!=None: break
                time.sleep(2)

        assert(self.dev != None)
Example #34
0
def monitor_device(hidg_dev):
    event_handlers = {}
    processed_devices = []
    while True:
        time.sleep(1)
        device_list = evdev.list_devices()
        for pdev in processed_devices:
            if pdev in device_list:
                device_list.remove(pdev)
        if len(device_list) > 0:
            print('device_list = {}'.format(device_list))
        if len(device_list) == 0:
            continue
        devices = [evdev.InputDevice(fn) for fn in device_list]
        if len(devices) == 0:
            print('No input devices are found. Waiting for next detection')
            time.sleep(1)
            continue
        for device in devices:
            print('Searching new device')
            if device.path in processed_devices:
                continue
            print('Found new device{}'.format(device))
            if device.name in device_config.ALLOWED_MOUSE_DEVS:
                print('Mouse device: {} is found on {}.'.format(
                    device.name, device.path))
                print('Device capabilities: {}'.format(
                    device.capabilities(verbose=True)))
                target_device = evdev.InputDevice(device.fn)
                thread = threading.Thread(target=handle_mouse_event,
                                          args=(
                                              hidg_dev,
                                              target_device,
                                          ))
                event_handlers[device.path] = (device.name, thread, 'mouse')
                thread.start()
            elif device.name in device_config.ALLOWED_KEYBOARD_DEVS:
                print('Keyboard device: {} is found on {}.'.format(
                    device.name, device.path))
                print('Device capabilities: {}'.format(
                    device.capabilities(verbose=True)))
                target_device = evdev.InputDevice(device.fn)
                thread = threading.Thread(target=handle_keyboard_event,
                                          args=(
                                              hidg_dev,
                                              target_device,
                                          ))
                event_handlers[device.path] = (device.name, thread, 'keyboard')
                thread.start()
            processed_devices.append(device.path)
Example #35
0
 def __init__(self, settingsManager, keymapper):
     """
         This requires both the SettingsManager and KeyMapper classes. It will use the SettingsManager to load all
         the different devicename.yaml config files enabled in the main.yaml. Each one should load a new Device
         class. It will pass the KeyMapper along to the different devices it finds.
         NOTE: the 'inputDevices' variable that is set actually is a list of all known input devices on the box. Each
             device will look through that list to try to find its device. This is a large point of failure.
     :param settingsManager: SettingsManager object
     :param keymapper: KeyMapper object
     """
     self.settings = settingsManager
     self.keymapper = keymapper
     self.inputDevices = [InputDevice(fn) for fn in evdev.list_devices()]
     self.get_device_configs()
Example #36
0
 def __init__(self,
              pipe,
              msg_queue,
              dev_names,
              keymap_file='../data/keymap.xml'):
     multiprocessing.Process.__init__(self)
     self.pipe = pipe
     self.msg_queue = msg_queue
     self.read_keymap(keymap_file)
     available_devices = list_devices()
     devices_to_use = [d for d in dev_names if d in available_devices]
     devices = map(InputDevice, devices_to_use)
     self.devices = {dev.fd: dev for dev in devices}
     self.timeout = 0.1  # in seconds
Example #37
0
    def __init__(self, name='小米蓝牙手柄'):
        devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
        for device in devices:
            print(device)
            if device.name == name:
                xiaomidev = device.fn

        print("=======")

        self.gamepad = evdev.InputDevice(xiaomidev)
        print(self.gamepad)
        print(self.gamepad.capabilities(verbose=True))

        print("=======")
Example #38
0
def run(args):

    if not rootCheck():
        sys.exit(1)

    fw = open(args.outfile, 'wb')

    dList = evdev.list_devices()
    try:
        dList.index(args.device)

    except ValueError, e:
        print 'Problem opening input: ', e
        sys.exit(1)
Example #39
0
    def __init__(self, longpress_time=LONGPRESS_DELAY):
        super(Powermate, self).__init__()

        self._longpress_delay = longpress_time

        # Get a handle on the powermate device
        for device_path in evdev.list_devices():
            tmp_device = evdev.InputDevice(device_path)
            tmp_info = tmp_device.info
            if tmp_info.vendor == ID_VENDOR and tmp_info.product == ID_PRODUCT:
                self._device = tmp_device
                break
        else:
            raise RuntimeError("No Powermate device found")
Example #40
0
    def __fetch_keyboard(self):
        print("Waiting for keyboard...")
        while True:
            devices = [InputDevice(path) for path in list_devices()]

            # Select devices with EV_KEY capability
            devices = [d for d in devices if 1L in d.capabilities()]
            devices = {d.fd: d for d in devices}
            self.devices = devices

            if len(self.devices) > 0:
                print("Keyboard found")
                break

            time.sleep(3)
Example #41
0
    def getJoysticks(self):
        js_devices = glob.glob("/dev/input/js*")
        js_devices.sort()

        ev_devices = []
        ev_device_list = [
            evdev.InputDevice(device)
            for device in reversed(evdev.list_devices())
        ]
        for device in ev_device_list:
            if re.search('x.box', device.name, re.IGNORECASE):
                print("Found joystick device at %s" % device.fn)
                ev_devices.append(device.fn)

        return js_devices, ev_devices
Example #42
0
def update_devices():
    """Scan connected devices and grab relevant ones."""
    for file_name in evdev.list_devices():
        if file_name not in devices and file_name not in ignore_devices:
            dev = evdev.InputDevice(file_name)
            print(dev)
            if match_dev(dev.name):
                devices[file_name] = dev
                dev.grab()
                print("grab")
                asyncio.ensure_future(dispatch_events(file_name, dev))
            else:
                ignore_devices.append(file_name)
    if not STOP:
        loop.call_later(3, update_devices)
Example #43
0
    def __init__(self, device):
        self.logger = Logger("Barcode scan")

        devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
        for d in devices:
            if device in d.name:
                self.logger.info("Found device " + d.name)
                self.device = d
                break

        if self.device is None:
            raise Exception("No barcode device found")

        self.q = queue.Queue()
        start_new_thread(self.scan, ())
Example #44
0
def select_device():
    ''' Select a device from the  list of accessible input devices '''

    devices = [InputDevice(i) for i in reversed(list_devices(device_dir))]

    dev_fmt = '{0:<3} {1.fn:<20} {1.name:<35} {1.phys}'
    dev_lns = [dev_fmt.format(n, d) for n, d in enumerate(devices)]

    print('ID  {:<20} {:<35} {}'.format('Device', 'Name', 'Phys'))
    print('-' * len(max(dev_lns, key=len)))
    print('\n'.join(dev_lns))
    print('')

    choice = input('Select device [0-{}]:'.format(len(dev_lns) - 1))
    return devices[int(choice)]
Example #45
0
 def _get_keyboard_device(self):
     from evdev import InputDevice, list_devices
     if self.device_name:
         devices = [InputDevice(file_name) for file_name in list_devices()]
         for device in devices:
             if self.device_name == device.name:
                 return device
     elif self.device_descriptor:
         try:
             device = InputDevice(self.device_descriptor)
         except OSError:
             pass
         else:
             return device
     return None
Example #46
0
def get_values_name(name):
    port = None
    devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
    for device in devices:
        #print device
        if device.name == name:
            port = device.fn
            print port
    if port:
        device = evdev.InputDevice(port)
        for event in device.read_loop():
            typ = event.type
            cod = event.code
            val = int(event.value)
            logging.debug(str(typ) + " " + str(cod) + " " + str(val))
Example #47
0
 def __init__(self, devname):
     #self.reader = self
     path = os.path.dirname(os.path.realpath(__file__))
     self.keys = "X^1234567890XXXXqwertzuiopXXXXasdfghjklXXXXXyxcvbnmXXXXXXXXXXXXXXXXXXXXXXX"
     devices = get_input_devices()
     logging.info("looking among " + str(list_devices()))
     for device in devices:
         if device.name == devname:
             self.dev = device
             break
     try:
         self.dev
     except:
         logging.error("no device found: " + str(devices))
         sys.exit('Could not find the device %s\n. Make sure is connected' % deviceName)
Example #48
0
    def listen(self) -> None:
        # Add currently known devices
        for path in evdev.list_devices():
            self.add_device(path)

        # Track devices that are added / removed
        context = pyudev.Context()
        monitor = pyudev.Monitor.from_netlink(context)
        monitor.filter_by(subsystem='input')
        observer = pyudev.MonitorObserver(monitor, self._handle_udev_event)
        observer.start()

        # Start receiving events
        self.event_loop.set_exception_handler(self._handle_exception)
        self.event_loop.run_forever()
Example #49
0
File: evinfo.py Project: hopr/hopr
def find_devices(include):
    devices = []
    for path in ed.list_devices():
        dev = ed.InputDevice(path)

        if not include:
            devices.append(dev)
        else:
            for match in include:
                (key, pattern) = match.split('=')
                text = str(getattr(dev, key))
                if re.search(pattern, text, re.I):                
                    devices.append(dev)
                
    return sorted(devices, key=lambda dev : dev.path)
Example #50
0
def joystickupdate():
    found = False
    devices = [InputDevice(fn) for fn in list_devices()]
    for dev in devices:
        if dev.name == 'Raspberry Pi Sense HAT Joystick':
            found = True
            break

    if not (found):
        log('Raspberry Pi Sense HAT Joystick not found. Aborting ...')
        sys.exit()
    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            if event.value == 0:  # key up
                handle_code(event.code)
Example #51
0
def device(device_keyword: str):
    """Find the specified device from all devices.

    :device_keyword: str: specify device's keyword
    :returns: specify device or False

    """
    devs = [InputDevice(dev) for dev in list_devices()]

    for dev in devs:
        if re.search(device_keyword, dev.phys):
            device = dev.path
            return device

    return False
    def __init__(self):
        PySide.QtCore.QThread.__init__(self)
        self.joyDev = None
        self.killMe = False
        if not evdev_available:
            print "Evdev system not available!"
            return
        devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]
        for dev in devices:
            if pycnc_config.JOY_IDENTIFIER in dev.name:
                self.joyDev = dev
                break

        if self.joyDev is None:
            print "Joystick not found!"
Example #53
0
 def dev_init(self):
     '''
     Initializes information regarding available input devices
     :return: Dictionary of input devices, indexed by hardware id
     '''
     devices = {}
     # take the device listing and convert it to a dictionary, indexed by the
     # vendor_id:product_id (as is seen via lsusb and other tools)
     for dev in list_devices():
         dev = InputDevice(dev)
         v_id = self.hwd_id(dev.info[1])
         p_id = self.hwd_id(dev.info[2])
         id = str(v_id) + ":" + str(p_id)
         devices[id] = dev
     return devices
Example #54
0
def findMouseEvent():
	devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
	for device in devices:
		cap = device.capabilities();
		rel=cap.get(evdev.ecodes.EV_REL)
		if rel is not None:
			try:
				#generate exception if not found
				rel.index(evdev.ecodes.REL_X)
				rel.index(evdev.ecodes.REL_Y)
				rel.index(evdev.ecodes.REL_WHEEL)
				return device.path
			except:
				pass
	return None
Example #55
0
    def _finddevice(self):
        """Search for the device that represents the xbox controller
        
        Returns:
            InputDevice: The xbox controller
            
        Raises:
            IOError: When no controller can be found
        """
        devices = [InputDevice(fn) for fn in list_devices()]
        for dev in devices:
            if dev.name.startswith('Xbox Gamepad'):
                return dev

        raise IOError("No Xbox controller found")
 def __init__(self):
     self.coord = [[0, 0], 0, 0]
     devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
     path = ''
     for device in devices:
         print(device.path, device.name, device.phys)
         path = device.path
     try:
         self.device = evdev.InputDevice(str(path))
         print(self.device.capabilities(verbose=True))
         self.coordLock = threading.Lock()
         JoyThread = threading.Thread(target=self.listen_to_joystick)
         JoyThread.start()
     except:
         print('No Joystick is Detected')
Example #57
0
def findKeyEvent():
	devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
	for device in devices:
		cap = device.capabilities();
		key=cap.get(evdev.ecodes.EV_KEY)
		if key is not None:
			try:
				#generate exception if not found
				key.index(evdev.ecodes.KEY_A)
				key.index(evdev.ecodes.KEY_B)
				key.index(evdev.ecodes.KEY_C)
				return device.path
			except:
				pass
	return None
Example #58
0
 def __init__(self):
     self.events = Queue.Queue()
     self.kbds = []
     # Detect which things in /dev/input/event* are keyboards
     dograb = False
     for path in evdev.list_devices()[::-1]:
         kbd = AsyncRawKeyboard(path,
                                len(self.kbds),
                                self.events,
                                grab=dograb)
         if not kbd.is_keyboard:
             continue
         dograb = True
         self.kbds.append(kbd)
         kbd.start()
Example #59
0
def bluetoothTest():
    devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
    for device in devices:
        print(device.path, device.name, device.phys)

    if path.exists('/dev/input/event0'):
        speakerButtons = evdev.InputDevice('/dev/input/event0')
        try:
            events = speakerButtons.read_loop()
            for event in events:
                print(event)
        except IOError:
            print("Device not found")
    else:
        print("Device not found")
Example #60
0
def init_joystick():
    devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()]

    device_fn = None
    for device in devices:
        print(device.fn, device.name, device.phys)
        c = device.capabilities()
        if evdev.ecodes.EV_ABS in c and evdev.ecodes.EV_KEY in c:
            print(device.fn, "device has EV_ABS and EV_KEY")
            device_fn = device.fn

    print("using joystick device", device_fn)
    device = evdev.InputDevice(device_fn)
    init_rattle(device)
    return device