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]
def _process_event(self): '''Process events. Capture the codes and notify the readers if ready ''' event = self.device.read_one() if event.type != evdev.ecodes.EV_KEY: return None if event.code == evdev.ecodes.KEY_LEFTSHIFT: self.lshift = evdev.categorize(event) return None if event.code == evdev.ecodes.KEY_RIGHTSHIFT: self.rshift = evdev.categorize(event) return None keys = KEYS if ( self.lshift is not None and self.lshift.keystate == evdev.events.KeyEvent.key_down ): keys = CAPKEYS if ( self.rshift is not None and self.rshift.keystate == evdev.events.KeyEvent.key_down ): keys = CAPKEYS if event.value == evdev.events.KeyEvent.key_down: if event.code == evdev.ecodes.KEY_ENTER: for future in self.readers: future.set_result(bytes(self.code, self.encode)) self.reset() return self.code = self.code + keys[event.code] if keys[event.code] == 'X' and event.code != evdev.ecodes.KEY_X: LOGGER.warning("Ignoring unexpected code: %s", event.code)
def run(self): gamepad = InputDevice("/dev/input/event3") #print(gamepad.capabilities()) print(gamepad) valuesDirection, valuesSpeed = 0, 0 constantDirection = 255/80 constantSpeed = 255/40 for event in gamepad.read_loop(): if event.type == ecodes.EV_ABS and event.code == 00: absevent = categorize(event) if(valuesDirection != int(event.value/constantDirection)): valuesDirection = int(event.value/constantDirection) list1 = ["girar",valuesDirection-40] globalVariables.fila.put(list1) #print(valuesDirection-40) elif event.type == ecodes.EV_ABS and event.code == 49: absevent = categorize(event) if(valuesSpeed != int(event.value/constantSpeed)): valuesSpeed = int(event.value/constantSpeed) list2=["velocidad",valuesSpeed/4] globalVariables.fila.put(list2) if event.type == ecodes.EV_KEY: keyevent = categorize(event) if keyevent.keystate == KeyEvent.key_down: if keyevent.keycode == 'BTN_BASE2': print ("Left") elif keyevent.keycode == 'BTN_PINKIE': print ("Right") elif keyevent.keycode == 'BTN_TOP2': print ("Forward") elif keyevent.keycode == 'BTN_BASE': print ("Backward")
def listen_key(result_queue): seq_map = {"KEY_KPDOT": ".", "KEY_KPPLUS": "+", "KEY_KPMINUS": "-", "KEY_KPCOMMA": ",", "KEY_KPASTERISK": "*", "KEY_KPEQUAL": "=", "KEY_KPRIGHTPAREN": ")", "KEY_KPLEFTPAREN": "(", "KEY_KPSLASH": "/", "KEY_KPENTER": "\n"} ecodes_rev = dict((v, k) for k, v in ecodes.ecodes.items()) dev = InputDevice('/dev/input/event0') print(dev) sequence = "" for event in dev.read_loop(): if event.type == ecodes.EV_KEY and event.value == 00: print event.code event_code_name = ecodes_rev[event.code] if event_code_name in [k for k in ecodes.ecodes.keys() if re.match(r"KEY_KP\d", k)]: sequence += event_code_name.replace("KEY_KP", "") elif event_code_name in seq_map: sequence += seq_map[event_code_name] #if event.code == ecodes.ecodes['']: # print "============= ENTER ============" # result_queue.put("stop") # #sequence += print sequence print categorize(event)
def setup_keyboard(): dev = InputDevice('/dev/input/event1') print(dev) for event in dev.read_loop(): if event.type == ecodes.EV_KEY: print(categorize(event).keycode) tiny_screen.oled_putString(decode(categorize(event)))
def handle_event(self, event): try: if event.type == ecodes.EV_ABS: self.recveived = True axis = self.axes[event.code] self.axes_data[axis] = self.axes_sign[axis] * self.factor(axis, event.value) self.publish() elif event.type == ecodes.EV_KEY: self.recveived = True self.button_data[self.buttons[event.code]] = 1 if event.value != 0 else 0 self.publish() except KeyError: if self.debug: print categorize(event)
def _listen_events(self, panel, grab): if grab: self.dev[panel].grab() for event in self.dev[panel].read_loop(): if event.type == ecodes.EV_KEY and event.value == 1: keycode = keys[event.code] try: if NAGA_BUTTON[keycode] in self.current[panel]: print json.dumps(self.current[panel][NAGA_BUTTON[keycode]], indent = 2) self._execute_action(self.current[panel][NAGA_BUTTON[keycode]]) print keys[event.code] print event print categorize(event) except: continue
def readID(): ID = '' path = os.popen("ls /dev/input/by-path/ | grep kbd").read().split('\n', 1)[0] if None == path: return 'blank' path = '/dev/input/by-path/' + path dev = evdev.InputDevice(path) scancodes = { # Scancode: ASCIICode 0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8', 10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R', 20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL', 30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u';', 40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N', 50: u'M', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 100: u'RALT' } for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: data = evdev.categorize(event) # Save the event temporarily to introspect it if data.keystate == 1: # Down events only key_lookup = scancodes.get(data.scancode) or u'UNKNOWN:{}'.format(data.scancode) # Lookup or return UNKNOWN:XX if key_lookup != 'CRLF': if key_lookup != 'LSHFT' and key_lookup != 'UNKNOWN:57': ID = ID + key_lookup else: return ID[4:16].encode("utf-8"), ID[20:].encode("utf-8")
async def listen_to_numpad(): active_key_task = None async for event in device.async_read_loop(): if event.type != ecodes.EV_KEY: continue if event.value == 2: # repeated continue if event.value == 0: # released active_keycodes.remove(event.code) if event.value == 1: # pressed active_keycodes.add(event.code) # execute one instant action # # When handle_active_keys() runs the key may already be released # again, because the key handler runs before the coroutine we start # right here... silly... this probably would have just worked # if it followed Javascript's Promises/A+ spec... volume_keys([event.code]) if not active_key_task or active_key_task.done(): active_key_task = asyncio.ensure_future(handle_active_keys()) if event.code == ecodes.KEY_KPENTER: mplaylist.send(b'\n') if event.code == ecodes.KEY_KP1: mplaylist.send(b'p\n') if event.code == ecodes.KEY_KP2: mplaylist.send(b'n\n') if event.code == ecodes.KEY_KP0: mplaylist.send(b's\n') if event.code == ecodes.KEY_NUMLOCK: continue print(evdev.categorize(event))
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)
def run(self): dev = InputDevice('/dev/input/event2') print(dev) for event in dev.read_loop(): if event.type == ecodes.EV_KEY: key_pressed = str(categorize(event)) if ', down' in key_pressed: print(key_pressed) if 'KEY_PLAYPAUSE' in key_pressed: print('play') sendCommand('p') if 'KEY_FASTFORWARD' in key_pressed: print('fastforward') sendCommand('n') if 'KEY_NEXTSONG' in key_pressed: print('skip') sendCommand('n') if 'KEY_POWER' in key_pressed: print('power') sendCommand('q') if 'KEY_VOLUMEUP' in key_pressed: print('volume up') sendCommand('v%2b') if 'KEY_VOLUMEDOWN' in key_pressed: print('volume down') sendCommand('v-') if 'KEY_CONFIG' in key_pressed: print('Random Station') getRandomStation()
def run (self): sync = self.SyncQueue.get () dev = InputDevice(self.InputDeviceName) for event in dev.read_loop (): if event.type == ecodes.EV_KEY: key = categorize (event) if ecodes.KEY[ecodes.KEY_ESC] == key.keycode: self.iRacer.Direction = Direction.Stop self.iRacer.Speed = Speed.Stop self.SyncQueue.task_done () return if key.keystate == KeyEvent.key_down or key.keystate == KeyEvent.key_hold: if ecodes.KEY[ecodes.KEY_UP] == key.keycode: self.SetDirection (Direction.Forwards) elif ecodes.KEY[ecodes.KEY_DOWN] == key.keycode: self.SetDirection (Direction.Backwards) elif ecodes.KEY[ecodes.KEY_LEFT] == key.keycode: self.SetDirection (Direction.Left) elif ecodes.KEY[ecodes.KEY_RIGHT] == key.keycode: self.SetDirection (Direction.Right) elif key.keystate == KeyEvent.key_up: if ecodes.KEY[ecodes.KEY_UP] == key.keycode or ecodes.KEY[ecodes.KEY_DOWN] == key.keycode: self.iRacer.Accelerating = False elif ecodes.KEY[ecodes.KEY_LEFT] == key.keycode or ecodes.KEY[ecodes.KEY_RIGHT] == key.keycode: self.iRacer.Straighten ()
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'
def handle_event(self, event): event = categorize(event) if isinstance(event, events.KeyEvent): if event.event.code == ecodes.BTN_MOUSE: self.handler.reset() #TODO consider not doing this unless double-clicking? self.handler.on() elif event.event.code == ecodes.BTN_RIGHT: self.handler.reset() #TODO consider not doing this at all? self.handler.off() elif isinstance(event, events.RelEvent): if event.event.code == ecodes.REL_X: #left/right movement if event.event.value < 0: self.handler.move_left(event.event.value) elif event.event.value > 0: self.handler.move_right(event.event.value) elif event.event.code == ecodes.REL_Y: #up/down movement if event.event.value > 0: self.handler.move_down(event.event.value) elif event.event.value < 0: self.handler.move_up(event.event.value) else: print 'other relative event' self.handler.update()
def main(): while True: r,w,x = select([dev], [], []) for event in dev.read(): print('event: ' + str(event.type)) if event.type == ecodes.EV_KEY: print(categorize(event))
def read_input(self): """Listens solely to the RFID keyboard and returns the scanned badge. Args: device: input device to listen to Returns: badge value as string """ rfid = '' capitalized = 0 device = self.f print "About to read_input" for event in device.read_loop(): #print "read_input event", event data = evdev.categorize(event) if event.type == evdev.ecodes.EV_KEY and data.keystate == 1: if data.scancode == self.LSHIFT_SCANCODE: capitalized = 1 if data.keycode == 'KEY_ENTER': break if data.scancode != self.LSHIFT_SCANCODE: if capitalized: rfid += self.capscancodes[data.scancode] capitalized ^= 1 else: rfid += self.scancodes[data.scancode] print "Badge read:", rfid return rfid
def loop(self): if self._client.loop() != 0: print('Fatal error. Trying to reconnect to the scanner.') self._reconnect_to_broker() try: for event in self._scanner.read_loop(): if event.type == ecodes.EV_KEY: data = categorize(event) if data.keystate == 1 and data.scancode != 42: if data.scancode == 28: print('Scanned code: ' + self._code) sending_thread = threading.Thread(target=self.send_code, args=[copy.deepcopy(self._code)]) sending_thread.start() self._code = '' else: self._code += self._scan_codes[data.scancode] except: print('Fatal error. Trying to reconnect to the scanner.') time.sleep(self._error_wait_time) self._connect_to_device()
def evdev_live_monitor(eventdev): '''evdev: monitor all keypresses from device live''' dev = InputDevice('/dev/input/' + eventdev) print(dev) for event in dev.read_loop(): if event.type == ecodes.EV_KEY: print(categorize(event))
def build_payload(event): event = evdev.categorize(event) return { 'code': event.scancode, 'key': event.keycode[0] if type(event.keycode) == list else event.keycode, 'state': {0: 'UP', 1: 'DOWN', 2: 'HOLD'}[event.keystate], 'captured_at': datetime.datetime.fromtimestamp(event.event.timestamp()).isoformat() }
def process_events(self,r): for re in r: for event in re.read(): # print '\nEvent Rxd: ',event,'\n',evdev.categorize(event) if event.type == evdev.ecodes.EV_KEY: # print 'Key Event Rxd: ',event key_event = evdev.categorize(event) self.process_event(key_event.keycode,key_event.keystate)
def read_input(dev): print("Reading from %s" % dev.name) scancodes = { # Scancode: ASCIICode 0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8', 10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'q', 17: u'w', 18: u'e', 19: u'r', 20: u't', 21: u'y', 22: u'u', 23: u'i', 24: u'o', 25: u'p', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL', 30: u'a', 31: u's', 32: u'd', 33: u'f', 34: u'g', 35: u'h', 36: u'j', 37: u'k', 38: u'l', 39: u';', 40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'z', 45: u'x', 46: u'c', 47: u'v', 48: u'b', 49: u'n', 50: u'm', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 100: u'RALT' } capscodes = { 0: None, 1: u'ESC', 2: u'!', 3: u'@', 4: u'#', 5: u'$', 6: u'%', 7: u'^', 8: u'&', 9: u'*', 10: u'(', 11: u')', 12: u'_', 13: u'+', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R', 20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'{', 27: u'}', 28: u'CRLF', 29: u'LCTRL', 30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u':', 40: u'\'', 41: u'~', 42: u'LSHFT', 43: u'|', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N', 50: u'M', 51: u'<', 52: u'>', 53: u'?', 54: u'RSHFT', 56: u'LALT', 100: u'RALT' } # setup vars input_buffer = '' caps = False command = None value = None # grab that shit dev.grab() # loop for event in dev.read_loop(): if event.type == ecodes.EV_KEY: # Save the event temporarily to introspect it data = categorize(event) if data.scancode == 42: if data.keystate == 1: caps = True if data.keystate == 0: caps = False if data.keystate == 1: # Down events only if caps: key_lookup = u'{}'.format(capscodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format( data.scancode) # Lookup or return UNKNOWN:XX else: key_lookup = u'{}'.format(scancodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format( data.scancode) # Lookup or return UNKNOWN:XX if (data.scancode != 42) and (data.scancode != 28): input_buffer += key_lookup # Print it all out! if(data.scancode == 28): if command is None: command = input_buffer value = None else: value = input_buffer sender(command, value) command = None value = None input_buffer = ''
def main(config): """Initializes the scanner and runs the main event loop. :param config: Scanner configuration object """ init_graphite(config.get("graphite", "server"), config.get("graphite", "prefix")) connection = init_database() dev = get_input_device() def signal_handler(incoming_signal, dataframe): # pylint: disable=unused-argument """Handle SIGINTs :param incoming_signal: The signal :param dataframe: The data associated with the signal. """ 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) connection.execute( 'insert into scans (barcode, timestamp, event_id) ' + 'values (:barcode, :timestamp, :event_id)', [barcode, timestamp, event_id.get_urn()]) connection.commit() barcode = "" else: try: barcode += SCANCODES[data.scancode] except KeyError: print >>sys.stderr, "Unknown scancode: {0}".format(data.scancode)
def handle_read(self): for event in self.recv(): if event.type == evdev.ecodes.EV_KEY: event = evdev.categorize(event) if event.keystate == event.key_down: self.engaged(event) elif event.keystate == event.key_up: self.released(event)
def get_input(device): val = '' for event in device.read_loop(): ev = categorize(event) if event.type == ecodes.EV_KEY and ev.keystate == ev.key_down: if ev.keycode == 'KEY_ENTER': break val += KEYCODES[ev.keycode] return val
def debug(self, device): dev = evdev.InputDevice("/dev/input/{}".format(device)) print("Device chosen:") print(dev) for event in dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: if event.value == evdev.KeyEvent.key_hold or event.value == evdev.KeyEvent.key_down: print(evdev.categorize(event))
def read_input(device): rfid = '' for event in device.read_loop(): data = categorize(event) if event.type == ecodes.EV_KEY and data.keystate == data.key_down: if data.keycode == KEY_ENTER: break rfid += SCANCODES[data.scancode] return rfid
def premain(argparser): signal.signal(signal.SIGINT, SigHandler_SIGINT) #here devices = [evdev.InputDevice(path) for path in evdev.list_devices()] for device in devices: print(device.path, device.name, device.phys) dev = InputDevice("/dev/input/event6") for event in dev.read_loop(): print(categorize(event))
def detectInputKey(): dev = InputDevice('/dev/input/event1') print(dev) # while True: # select([dev], [], []) # for event in dev.read(): # print "code: %s value: %s" %(event.code, event.value) for event in dev.read_loop(): if event.type == ecodes.EV_KEY: print(categorize(event))
def readBarcode(): code = "" for event in dev.read_loop(): if event.type == ecodes.EV_KEY: data = categorize(event) if data.keystate == 1: if data.scancode == 28: return code else: code += scancodes.get(data.scancode) or u"UNKNOWN:{}".format(data.scancode)
def run(self): """Run the loop of the KeyboardRemote.""" from evdev import categorize, ecodes if self.dev is not None: self.dev.grab() _LOGGER.debug("Interface started for %s", self.dev) while not self.stopped.isSet(): # Sleeps to ease load on processor time.sleep(.05) if self.dev is None: self.dev = self._get_keyboard_device() if self.dev is not None: self.dev.grab() self.hass.bus.fire( KEYBOARD_REMOTE_CONNECTED, { DEVICE_DESCRIPTOR: self.device_descriptor, DEVICE_NAME: self.device_name } ) _LOGGER.debug("Keyboard re-connected, %s", self.device_id) else: continue try: event = self.dev.read_one() except IOError: # Keyboard Disconnected self.dev = None self.hass.bus.fire( KEYBOARD_REMOTE_DISCONNECTED, { DEVICE_DESCRIPTOR: self.device_descriptor, DEVICE_NAME: self.device_name } ) _LOGGER.debug("Keyboard disconnected, %s", self.device_id) continue if not event: continue if event.type is ecodes.EV_KEY and event.value is self.key_value: _LOGGER.debug(categorize(event)) self.hass.bus.fire( KEYBOARD_REMOTE_COMMAND_RECEIVED, { KEY_CODE: event.code, DEVICE_DESCRIPTOR: self.device_descriptor, DEVICE_NAME: self.device_name } )
def _proc_until_enter(self, arg_event): """ recognize pressed key """ res = False c_ev = categorize(arg_event) if c_ev.keystate == 0: # key UP logging.debug('st=%s, code=%s', c_ev.keystate, c_ev.keycode) if c_ev.keycode != 'KEY_ENTER': # and c_ev.keystate == 0: self.card_num_list.append(c_ev.keycode.replace('KEY_', '')) else: logging.debug('ENTER detected. Exiting...') res = True return res
def read_scan(self): chars = '' for event in self.input.read_loop(): if event.type == evdev.ecodes.EV_KEY: e = evdev.categorize(event) if e.keystate != e.key_down: continue # print(f"keys are {e.keystate}, {e.key_down}, {e.key_up}, {e.keycode}, {e.event}, {e.scancode}") key = e.keycode[4:] if key == "ENTER": return int(chars[:-1]) # remove checksum key chars += key
def run(): print("Running reader thread") global q for event in joystick.read_loop(): print() # print(categorize(event)) if event.type == BUTTON: keyevent = categorize(event) if keyevent.keycode[0] == commands.JOYSTICK: if keyevent.keycode[1] == commands.TRIGGER: if keyevent.keystate == keyevent.key_down: print("Fire") q.put(commands.FIRE) elif keyevent.keystate == keyevent.key_up: print("Release fire") q.put(commands.STOP_FIRE) elif event.type == AXIS: if event.code == ABS_X: print("ABS_X with value: ", event.value) # Do nothing here # Panning functionality? elif event.code == ABS_Y: print("ABS_Y with value: ", event.value) if event.value == 127: print("Releasing Tilt") q.put(commands.RELEASE_TILT) elif event.value > 127: print("Tilting up") q.put(commands.TILT_UP) elif event.value < 127: print("Tilting down") q.put(commands.TILT_DOWN) elif event.code == ABS_RZ: print("ABS_RZ with value: ", event.value) if event.value == 127: print("Releasing Rotate") q.put(commands.RELEASE_ROTATE) elif event.value > 127: print("Rotating right") q.put(commands.ROTATE_RIGHT) elif event.value < 127: print("Rotating left") q.put(commands.ROTATE_LEFT) elif event.code == ABS_THROTTLE: print("ABS_THROTTLE with value: ", event.value) # Do nothing # Sensitivity setting? elif event.code == ABS_HAT0X: print("ABS_HAT0X with value: ", event.value) # Do nothing elif event.code == ABS_HAT0Y: print("ABS_HAT0Y with value: ", event.value)
async def read_device(device): with device.grab_context(): read_line = '' async for event in device.async_read_loop(): cat_event = evdev.categorize(event) if isinstance(cat_event, evdev.events.KeyEvent): if cat_event.keystate == 1: k = cat_event.keycode.lstrip('KEY_') if k != 'NTER': read_line += k else: asyncio.create_task(execute_task(read_line)) read_line = ''
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
def read_data2(self): ''' Read data one by one when the device is establish This method return an event (include key) which read from device ''' if self.current_device: print('-----Begin to receive data-----') for event in self.current_device.read_loop(): if event.type == evdev.ecodes.EV_KEY: # print(event) print(evdev.categorize(event)) else: print('The device is not valid. Please try again.')
def read_loop_device(device): code = "" result = StringIO() sys.stdout = result for event in device.read_loop(): if event.type == ecodes.EV_KEY: e = categorize(event) if e.keystate == e.key_up: sys.stdout.write(parse_key_to_char(e.keycode)) sys.stdout.flush() return result
def test(): nilai = 0 while nilai == 0 : r,w,x = select([gamepad], [], []) for event in gamepad.read(): if event.type == ecodes.EV_ABS: absevent = categorize(event) if ecodes.bytype[absevent.event.type][absevent.event.code] == "ABS_X": print('nilai :%i'%(event.type)) if event.value == 1: print("break") nilai = 1 print("finish")
def event(self, event): categorized_event = evdev.categorize(event) #print(categorized_event) if isinstance(categorized_event, evdev.events.KeyEvent): self._key_event(categorized_event) elif isinstance(categorized_event, evdev.events.AbsEvent): self._abs_event(categorized_event) elif isinstance(categorized_event, evdev.events.RelEvent): self._rel_event(categorized_event) elif isinstance(categorized_event, evdev.events.InputEvent): self._input_event(categorized_event) elif isinstance(categorized_event, evdev.events.SynEvent): pass
def _read_all_available_events(self, data): """ Reads all current ready events from device and adds the translated data to the data list.""" try: for raw_event in self.device.read(): event = evdev.categorize(raw_event) translated_event = self._translate_event(event) if translated_event: data.append(translated_event) except BlockingIOError: # This indicates there are no more events to read # In theory this will never happen as we check before we read # If it happens, ignore it pass
def main(): device = InputDevice("/dev/input/event0") # my keyboard print("reading...") for event in device.read_loop(): if event.type == ecodes.EV_KEY: desc = categorize(event) event = KeyEvent(event) time = camera.now_str() category = code_to_category.get(event.keycode) print("key_pressed:", desc, category) if category and event.keystate == KeyEvent.key_down: camera.capture(f"data/{category}/{time}.jpg", format="jpeg") os.system("aplay ./WAV/lock_chime.wav")
def readData(self): ''' Record all keyboard events until KEY_ENTER is pressed ''' keyEvents = [] for event in self.reader.read_loop(): if event.type == evdev.ecodes.EV_KEY: temp = evdev.categorize(event) if temp.keystate: keyEvents.append(temp) if keyEvents[-1].keycode in ["KEY_ENTER", "KEY_KPENTER"]: break return keyEvents[:-1]
def __init__(self, debug=True): self.controller = InputDevice('/dev/input/event0') for event in self.controller.read_loop(): try: if event.type == ecodes.EV_ABS: absevent = categorize(event) print(ecodes.bytype[absevent.event.type][ absevent.event.code]) # if ecodes.bytype[absevent.event.type][absevent.event.code] == 'ABS_LZ': except IOError: pass
async def handle_mouse(): async for event in mouse.async_read_loop(): if event.type == ecodes.EV_KEY: key_event = evdev.categorize(event) print(key_event.keycode) if key_event.keycode == "BTN_SIDE" or key_event.keycode == "BTN_EXTRA": state = key_event.keystate virtual_mouse.write(ecodes.EV_KEY, ecodes.BTN_MIDDLE, state) continue else: virtual_mouse.write_event(event) else: virtual_mouse.write_event(event)
def run(): from evdev import InputDevice, categorize, ecodes, KeyEvent, util devices = [InputDevice(fn) for fn in util.list_devices()] found = False for device in devices: if device.name == 'Logitech Gamepad F710' or device.name == 'Logitech Gamepad F310': gamePad = InputDevice(device.fn) found = True break if found == False: print("Device not found") return print("\nPrint gamepad object information\n") print (gamePad) print("\n") print("Press gamepad buttons\n") for event in gamePad.read_loop(): if event.type == ecodes.EV_KEY: keyevent = categorize(event) print(keyevent) print("") if keyevent.keystate == KeyEvent.key_down: print('key down detected') print("keyevent.keycode") print(keyevent.keycode) print("") if keyevent.keycode[1] == 'BTN_X': print('button X\n') elif keyevent.keycode[0] == 'BTN_B': print('button B\n') elif keyevent.keycode[0] == 'BTN_A': print('button A\n') elif keyevent.keycode[1] == 'BTN_Y': print('button Y\n') elif keyevent.keycode == 'BTN_TL': print('button thumb left\n') elif keyevent.keycode == 'BTN_TR': print("button thumb right\n")
def controllerOverride(self, **kwargs): """ Blocking: use for debug/override only """ # Get the name of the Logitech Device def getInputDeviceByName(name): devices = [InputDevice(fn) for fn in list_devices()] for device in devices: if device.name == name: return InputDevice(device.fn) return None # Import our gamepad. gamepad = getInputDeviceByName('Logitech Gamepad F710') for event in gamepad.read_loop(): if event.type == ecodes.EV_KEY: keyevent = categorize(event) if keyevent.keystate == KeyEvent.key_down: print(keyevent.keycode) # example key detection code if 'BTN_A' in keyevent.keycode: # Do something here when the A button is pressed pass elif 'BTN_START' in keyevent.keycode: # Do something here when the START button is pressed pass elif event.type == ecodes.EV_ABS: if event.code == 0: print('PAD_LR '+str(event.value)) elif event.code == 1: print('PAD_UD '+str(event.value)) elif event.code == 2: print('TRIG_L '+str(event.value)) self.runDiff([-1,-1],int(event.value*180.2)) elif event.code == 3: print('JOY_LR '+str(event.value)) self.runDiff([1,-1],event.value) elif event.code == 4: print('JOY_UD '+str(event.value)) #self.runAngle([1,1], event.value) elif event.code == 5: print('TRIG_R '+str(event.value)) self.runDiff([1,1],int(event.value*182.2)) elif event.code == 16: print('HAT_LR '+str(event.value)) elif event.code == 17: print('HAT_UD '+str(event.value)) else: pass
async def device_reader(dev : evdev.InputDevice): with dev.grab_context(), evdev.UInput.from_device(dev) as ui: async for event in dev.async_read_loop(): if event.type == evdev.ecodes.EV_KEY: kevent = evdev.categorize(event) print(kevent) if kevent.scancode in key_bindings: key_bindings[kevent.scancode](kevent) else: ui.write_event(event) ui.syn() else: ui.write_event(event) ui.syn()
def bt_key_handler(name, mpd_support=0) -> None: """Actual key handler, once bluetooth device is connected""" # Try to open the event device, will exit with exception on fail dev = bt_open_device(name) logger.debug(dev) bt_on_connect(mpd_support) path = os.path.dirname(os.path.realpath(__file__)) # Infinite loop reading the events. Will fail, if event device gets disconnected for event in dev.read_loop(): if event.type == ev.ecodes.EV_KEY: # Report the button event logger.debug(ev.categorize(event)) # Only act on button press, not button release if event.value == 1: if event.code == bt_keycode_play: proc = subprocess.run( f"{path}/../../../scripts/playout_controls.sh -c=playerpause", shell=True, check=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) elif event.code == bt_keycode_pause: proc = subprocess.run( f"{path}/../../../scripts/playout_controls.sh -c=playerpause", shell=True, check=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) elif event.code == bt_keycode_next: proc = subprocess.run( f"{path}/../../../scripts/playout_controls.sh -c=playernext", shell=True, check=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) elif event.code == bt_keycode_prev: proc = subprocess.run( f"{path}/../../../scripts/playout_controls.sh -c=playerprev", shell=True, check=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) logger.debug(proc.stdout) if proc.returncode != 0: logger.error("#" * 60) logger.error( f"In subprocess execution (retcode = {str(proc.returncode())})" ) logger.error(proc.stdout) logger.error("#" * 60)
def main(): dev = InputDevice('/dev/input/event0') data = '' for event in dev.read_loop(): if event.type == ecodes.EV_KEY: raw = str(categorize(event)) if 'down' in raw: start = raw.index('KEY_') + 4 data += raw[start:start + 1] if len(data) == 11: data = data[:10] url = 'http://127.0.0.1:3000/api/newAccess?id=' + data res = requests.get(url) data = ''
def run(self): """Endless loop grabbing content from barcode and RFID scanner.""" scan_dev = InputDevice( self.conf.get(ScannerClient.CONF_SECTION, 'barcode-device')) rfid_dev = InputDevice( self.conf.get(ScannerClient.CONF_SECTION, 'rfid-device')) code = '' try: if not self.debug: scan_dev.grab() rfid_dev.grab() self.logger.info('Prepaid Mate up and running') while True: readable_dev, _, _ = select.select([scan_dev, rfid_dev], [], []) for dev in readable_dev: input_ = dev.read_one() event = categorize(input_) if input_.type != ecodes.EV_KEY or event.keystate != 1: # pylint: disable=no-member continue key = event.keycode.replace('KEY_', '') if key.isdigit(): code += key elif key == 'ENTER': try: if dev == rfid_dev: # hacky state machine shortcut self.process_code_account(code) self.mode = Mode.ORDER else: self.process_code(code) except (UserError, BackendError, requests.exceptions.ConnectionError) as exc: self.log_and_speak(exc.args[0], level=logging.ERROR) self.play_status_sound( ScannerClient.PAYMENT_FAILED_AUDIO) self.reset() finally: code = '' else: self.logger.warning('got unexpected %s from %s', event.keycode, dev) finally: if not self.debug: scan_dev.ungrab() rfid_dev.ungrab()
def run_loop(button): for event in button.read_loop(): if event.type == evdev.ecodes.EV_KEY and event.value == evdev.KeyEvent.key_down: print(evdev.categorize(event)) if event.code == evdev.ecodes.KEY_VOLUMEUP: av_control.post_volume_up(url_base) elif event.code == evdev.ecodes.KEY_VOLUMEDOWN: av_control.post_volume_down(url_base) elif event.code == evdev.ecodes.KEY_PLAYPAUSE: playstate = av_control.get_playstate(url_base) if playstate == 'Stopped': av_control.radio_play(url_base) else: av_control.radio_stop(url_base)
def monitor(self, callfunct, key): # if the defice is a none type then just notify the user and return if (self.device == None): print("no device is connected") return # read keys, wait until desired key is found for event in self.device.read_loop(): if event.type == evdev.ecodes.EV_KEY: key_event = evdev.categorize(event) if (key_event.keystate == 1 and key_event.keycode == key): callfunct() # call the callback break
def get_key(self, key): keyed = False if (self.device == None): print("no device connected") return if (event.type == evdev.ecodes.EV_KEY): key_event = evdev.categorize(event) if (key_event.keystate == 1 and key_event.keycode == key): keyed = True return keyed
def read_barcode(self): """Wait for a barcode and return it""" out = '' for event in self.dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: # Save the event temporarily to introspect it data = evdev.categorize(event) if data.keystate == 1: # Down events only key_lookup = SCANCODES.get(data.scancode, '?') if key_lookup == 'CRLF': break else: out += key_lookup return out
def run(self): """The threaded run method""" read_so_far = '' for event in self.dev.read_loop(): if event.type == evdev.ecodes.EV_KEY: # Save the event temporarily to introspect it data = evdev.categorize(event) if data.keystate == 1: # Down events only key_lookup = SCANCODES.get(data.scancode, '?') if key_lookup == 'CRLF': self._barcode_queue.put(read_so_far) read_so_far = '' else: read_so_far += key_lookup
def read_events(hid): chars = [] while True: events = yield from hid.async_read() for event in events: if event.type == ecodes.EV_KEY: key = categorize(event) if key.keystate == key.key_down: if key.scancode == ecodes.KEY_ENTER: enter(chars) chars = [] else: char = characters.get(key.scancode, '�') chars.append(char)
async def async_monitor_input(self, dev): """Event monitoring loop. Monitor one device for new events using evdev with asyncio, start and stop key hold emulation tasks as needed. """ repeat_tasks = {} try: _LOGGER.debug("Start device monitoring") dev.grab() async for event in dev.async_read_loop(): if event.type is ecodes.EV_KEY: if event.value in self.key_values: _LOGGER.debug(categorize(event)) self.hass.bus.async_fire( KEYBOARD_REMOTE_COMMAND_RECEIVED, { KEY_CODE: event.code, DEVICE_DESCRIPTOR: dev.path, DEVICE_NAME: dev.name, }, ) if ( event.value == KEY_VALUE["key_down"] and self.emulate_key_hold ): repeat_tasks[event.code] = self.hass.async_create_task( self.async_keyrepeat( dev.path, dev.name, event.code, self.emulate_key_hold_delay, self.emulate_key_hold_repeat, ) ) elif event.value == KEY_VALUE["key_up"]: if event.code in repeat_tasks: repeat_tasks[event.code].cancel() del repeat_tasks[event.code] except (OSError, PermissionError, asyncio.CancelledError): # cancel key repeat tasks for task in repeat_tasks.values(): task.cancel() if repeat_tasks: await asyncio.wait(repeat_tasks.values())
def process_events(self, r): for re in r: for event in re.read(): # print '\nEvent Rxd: ',event,'\n',evdev.categorize(event) if event.type == evdev.ecodes.EV_KEY: # print 'Key Event Rxd: ',event key_event = evdev.categorize(event) #key_event.keycode=[key_event.keycode,'fred'] #print (key_event) if type(key_event.keycode) is list: for kc in key_event.keycode: self.process_event(kc, key_event.keystate) else: self.process_event(key_event.keycode, key_event.keystate)
def run(self): dev = evdev.InputDevice(str(sys.argv[1])) print(dev) while True: if self.done is True: print "Thread Abbruch.." break r, w, x = select.select([dev], [], []) for event in dev.read(): if event.type == evdev.ecodes.EV_KEY: input = evdev.categorize(event) if input.keystate: key = str(input.keycode).split('_', 1)[1] if key in string.ascii_uppercase: waitinglist.put(key)
def _read_code(self): for event in self.barcode_reader.read_loop(): if event.type == evdev.ecodes.EV_KEY: key_press_data = evdev.categorize(event) # print(key_press_data) if key_press_data.keystate == 1: # dow press only. key_code = key_press_data.keycode[4:] # print(key_press_data.keycode) if len(key_code) == 1: self.code = self.code + key_code if key_code == "ENTER": print("End of input") print("Code is : {0}".format(self.code)) self.post(self.code) self.code = ''