本文整理汇总了Python中evdev.InputDevice类的典型用法代码示例。如果您正苦于以下问题:Python InputDevice类的具体用法?Python InputDevice怎么用?Python InputDevice使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InputDevice类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_handler
def register_handler(self, handler):
if handler.device_fn in self.devices_by_fn:
device = self.devices_by_fn[handler.device_fn]
else:
device = InputDevice(handler.device_fn)
self.devices_by_fn[handler.device_fn] = device
self.devices_by_fd[device.fd] = device
self.handlers_by_fd[device.fd] = set()
# Check if device has needed event
capabilities = device.capabilities()
if handler.event_type in capabilities:
for event_code in handler.event_codes:
if event_code in capabilities[handler.event_type]:
self.handlers_by_fd[device.fd].add(handler)
else:
logger.warning('Event {0} not found in input device "{1}"'.format(
ecodes.bytype[handler.event_type][handler.event_code], device.name))
return False
else:
logger.warning(
'Input device "{1}" has no capability {0}'.format(ecodes.EV[handler.event_type], device.name))
return False
return True
示例2: KeyboardRemote
class KeyboardRemote(threading.Thread):
"""This interfaces with the inputdevice using evdev."""
def __init__(self, hass, device_descriptor, key_value):
"""Construct a KeyboardRemote interface object."""
from evdev import InputDevice
self.dev = InputDevice(device_descriptor)
threading.Thread.__init__(self)
self.stopped = threading.Event()
self.hass = hass
self.key_value = key_value
def run(self):
"""Main loop of the KeyboardRemote."""
from evdev import categorize, ecodes
_LOGGER.debug('KeyboardRemote interface started for %s', self.dev)
self.dev.grab()
while not self.stopped.isSet():
event = self.dev.read_one()
if not event:
continue
# pylint: disable=no-member
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}
)
示例3: run
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")
示例4: run
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]
示例5: listen_key
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)
示例6: touchLoop
def touchLoop():
dev = InputDevice('/dev/input/event0')
while True:
for event in dev.read_loop():
# match BTN_LEFT DOWN
if event.type == ecodes.EV_KEY and event.value == 1:
demoCycle();
示例7: run
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()
示例8: initiate_gesture_find
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()
示例9: evdev_live_monitor
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))
示例10: run
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 ()
示例11: detectInputKey
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'
示例12: event_stream
def event_stream(deadzone=0,scale=32768):
#_data = None
old_value=None
x=0
#Start up xboxdrv driver
subprocess = os.popen('sudo xboxdrv -d -D -v --dbus session','r',65536)
time.sleep(2)
#Get the xbox controller as a device
devicesNow = glob.glob('/dev/input/event*')
found = False
for dev in devicesNow:
device = InputDevice(dev)
if 'Xbox' in device.name:
print 'Found:',device.name,'on',dev
found = True;
break
if not found:
print 'XBOX READ ERROR: could not find xbox controller'
return
time.sleep(1)
#Setup for evdev
while True:
line = subprocess.readline()
# Turn off controller status light if controller is disconnected
if 'failed' in line:
raise ValueError(line)
#Run loop for each new evdev event
for evdev_event in device.read_loop():
value = None
#Convert evdev event code into xbox key
key=code2key(evdev_event.code)
#Special condition for X1 because it sends every other value as 0
if evdev_event.code == 0:
if evdev_event.value != 0:
value = apply_deadzone(evdev_event.value,deadzone,scale)
#Special conditions for joysticks
elif evdev_event.code == 1 or evdev_event.code == 3 or evdev_event.code == 4:
value = apply_deadzone(evdev_event.value,deadzone,scale)
#Special conditions for RT and LT
elif evdev_event.code == 9 or evdev_event.code == 10:
#Adds trigger deadzone of 125 (out of 255)
if evdev_event.value >= 125:
value=1
else:
value=0
else:
value=evdev_event.value
#Returns event data if different
if value != None:
event = Event(key,value,old_value)
#print(value)
yield event
old_value = value
示例13: setup_keyboard
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)))
示例14: HidrawDS4Device
class HidrawDS4Device(DS4Device):
def __init__(self, name, addr, type, hidraw_device, event_device):
try:
self.report_fd = os.open(hidraw_device, os.O_RDWR | os.O_NONBLOCK)
self.fd = FileIO(self.report_fd, "rb+", closefd=False)
self.input_device = InputDevice(event_device)
self.input_device.grab()
except (OSError, IOError) as err:
raise DeviceError(err)
self.buf = bytearray(self.report_size)
super(HidrawDS4Device, self).__init__(name, addr, type)
def read_report(self):
try:
ret = self.fd.readinto(self.buf)
except IOError:
return
# Disconnection
if ret == 0:
return
# Invalid report size or id, just ignore it
if ret < self.report_size or self.buf[0] != self.valid_report_id:
return False
if self.type == "bluetooth":
# Cut off bluetooth data
buf = zero_copy_slice(self.buf, 2)
else:
buf = self.buf
return self.parse_report(buf)
def read_feature_report(self, report_id, size):
op = HIDIOCGFEATURE(size + 1)
buf = bytearray(size + 1)
buf[0] = report_id
return fcntl.ioctl(self.fd, op, bytes(buf))
def write_report(self, report_id, data):
if self.type == "bluetooth":
# TODO: Add a check for a kernel that supports writing
# output reports when such a kernel has been released.
return
hid = bytearray((report_id,))
self.fd.write(hid + data)
def close(self):
try:
self.fd.close()
self.input_device.ungrab()
except IOError:
pass
示例15: premain
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))