from time import sleep import pyglet import evdev # 0 axis = aileron # 1 axis = elevator # 2 axis = throttle # 3 axis = rudder from Joystick import Joystick if __name__ == '__main__': devices = [evdev.InputDevice(path) for path in evdev.list_devices()] joystick = evdev.InputDevice(devices[0].path) print(joystick) while True: for event in joystick.read_loop(): print(event)
# print(ex) # abs_y = abs_y + mov_y*scaling # abs_x = abs_x + mov_x*scaling #odom.header.stamp = rospy.Time.now() #odom.header.frame_id = "mouse_rear" ## since all odometry is 6DOF we'll need a quaternion created from yaw #odom_quat = tf.transformations.quaternion_from_euler(0, 0, 0) #odom.pose.pose = Pose(Point(abs_x, abs_y, 0.), Quaternion(*odom_quat)) #odom.child_frame_id = "base_link" #odom.twist.twist = Twist(Vector3(mov_x, mov_y, 0), Vector3(0, 0, 0)) #odom_pub.publish(odom) #mov_x = 0 #mov_y = 0 device = evdev.InputDevice("/dev/input/event1") rospy.init_node('mouse_rear') tfBuffer = tf2_ros.Buffer() tf2_ros.TransformListener(tfBuffer) print(device) pub = rospy.Publisher('/mouse/rear/rel', Vector3Stamped, queue_size=3) odom_pub = rospy.Publisher("/mouse/rear/odom", Odometry, queue_size=3) r = rospy.Rate(10) # 10hz rospy.Timer(rospy.Duration(0.1), my_callback) for event in device.read_loop(): # print(event) if event.type == evdev.ecodes.EV_REL: if event.code == 1: mov_x -= event.value if event.code == 0: mov_y -= event.value
exit(0) if not config['inputs']: print("No keyboard/mouse in config [inputs] section.") exit(0) current_mode = "host" # read capabilities and grab input devices input_devices = {} capabilities = {} for device in config['inputs']: p = '/var/lib/libvirt-evdev/' + device + '.p' # use capabilities from real device if connected if os.path.exists(config['inputs'][device]): input_devices[device] = evdev.InputDevice(config['inputs'][device]) input_devices[device].grab() capabilities[device] = input_devices[device].capabilities() del capabilities[device][0] pickle.dump(capabilities[device], open(p, 'wb')) # read stored capabilities otherwise elif os.path.exists(p): with open(p, 'rb') as fp: capabilities[device] = pickle.load(open(p, 'rb')) if not capabilities: exit(0) # create host devices host_devices = { key: evdev.UInput(cap)
def find_all_touchpads() -> Generator[tuple[str, str], None, None]: for device in [evdev.InputDevice(d) for d in evdev.list_devices()]: if evdev.ecodes.EV_ABS in device.capabilities(): yield (device.name, device.path) device.close()
def find_devices(self): self._devices = [evdev.InputDevice(fd) for fd in evdev.list_devices()]
def __init__(self): self.devices = [evdev.InputDevice(hid_path) for hid_path in evdev.list_devices()] self.input_devices = self.get_all_input_devices()
def main(): """ Main program loop """ #Start Program print "" print(date_for_log()) print('-----------------------') print('Welcome to the photo booth!') print('Use shutdown.sh to exit') print('-----------------------') print "" #Setup any required folders (if missing) health_test_required_folders() #Start camera preview CAMERA.start_preview(resolution=(SCREEN_W, SCREEN_H)) #Display intro screen intro_image_1 = REAL_PATH + '/assets/00_intro_1.png' intro_image_2 = REAL_PATH + '/assets/00_intro_2.png' overlay_1 = overlay_image(intro_image_1, 0, 3) overlay_2 = overlay_image(intro_image_2, 0, 4) i = 0 blink_speed = 10 # Finds BT remote controller devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] if len(devices) == 0: print(date_for_log()) print "ERROR ! No devices found, try bluetoothctl ? Is the remote turned on ?" print "Stopping program." sys.exit(1) # Search for remoteDevice remoteDevice = None for device in devices: if device.name == 'AB Shutter3': print(date_for_log()) print(device) print "Connection set !" remoteDevice = device if remoteDevice != None: remoteDevice.grab() print(date_for_log()) print "Waiting for button to be pressed." # Event listener loop while True: photo_button_is_pressed = None try: event = remoteDevice.read_one() except BaseException as errr: # If the remote disconnected... if "[Errno 19] No such device" == str(errr): # We wait for a device reconnection print(date_for_log()) print "Remote is disconnected ! Please plug it back on !!!" remoteDevice = waitForDeviceToReconnect() remoteDevice.grab() # Start while loop again print(date_for_log()) print "Waiting for button to be pressed." continue else: print(date_for_log()) print "ERROR ! Something very wrong happened !!!" print str(errr) print "Stopping program." sys.exit(1) if event != None and event.type == evdev.ecodes.EV_KEY and event.code == 115 and event.value == 01: photo_button_is_pressed = True #Stay inside loop, until button is pressed if photo_button_is_pressed is None: #After every 10 cycles, alternate the overlay i = i + 1 if i == blink_speed: overlay_2.alpha = 255 elif i == (2 * blink_speed): overlay_2.alpha = 0 i = 0 #Regardless, restart loop sleep(0.1) continue #Button has been pressed! print(date_for_log() + ' : Button pressed!') #Get filenames for images filename_prefix = get_base_filename_for_images() remove_overlay(overlay_2) remove_overlay(overlay_1) photo_filenames = [] # Takes 4 photos for photo_number in range(1, TOTAL_PICS + 1): prep_for_photo_screen(photo_number) fname = taking_photo(photo_number, filename_prefix) photo_filenames.append(fname) #thanks for playing playback_screen(filename_prefix) # Display intro screen again overlay_1 = overlay_image(intro_image_1, 0, 3) overlay_2 = overlay_image(intro_image_2, 0, 4) #Remove pending button presses cleanPending = True while cleanPending == True: try: pendingEvent = remoteDevice.read_one() if pendingEvent == None: cleanPending = False except BaseException as errr: # If the remote disconnected, we'll handle that later if "[Errno 19] No such device" == str(errr): break else: print(date_for_log()) print "ERROR ! Something very wrong happened !!!" print str(errr) print "Stopping program." sys.exit(1) print(date_for_log()) print "Waiting for button to be pressed."
#!/usr/bin/env python3 import evdev import asyncio import time from subprocess import check_output pwrkey = evdev.InputDevice("/dev/input/event0") odroidgo2_joypad = evdev.InputDevice("/dev/input/by-path/platform-odroidgo2-joypad-event-joystick") need_to_swallow_pwr_key = False # After a resume, we swallow the pwr input that triggered the resume class Power: pwr = 116 class Joypad: l1 = 310 r1 = 311 up = 544 down = 545 left = 546 right = 547 f1 = 704 f2 = 705 f5 = 708 def runcmd(cmd, *args, **kw): print(f">>> {cmd}") check_output(cmd, *args, **kw)
Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple example: print scale(99, (0.0, 99.0), (-1.0, +1.0)) """ return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0] def scalestick(value): return scale(value, (0, 255), (-700, 700)) print("Finding ps3 controller...") devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: if device.name == 'PLAYSTATION(R)3 Controller': ps3dev = device.fn gamepad = evdev.InputDevice(ps3dev) side_speed = 0 turn_speed = 0 fwd_speed = 0 triangle_pressed_time = 0 medium_motor_speed = -500 shooting = 0 running = True
refresh() ## # Everything that follows is for handling the touchscreen touch events via evdev ## # Used to map touch event from the screen hardware to the pygame surface pixels. # (Those values have been found empirically, but I'm working on a simple interactive calibration tool tftOrig = (3750, 180) tftEnd = (150, 3750) tftDelta = (tftEnd[0] - tftOrig[0], tftEnd[1] - tftOrig[1]) tftAbsDelta = (abs(tftEnd[0] - tftOrig[0]), abs(tftEnd[1] - tftOrig[1])) # We use evdev to read events from our touchscreen # (The device must exist and be properly installed for this to work) touch = evdev.InputDevice('/dev/input/touchscreen') # We make sure the events from the touchscreen will be handled only by this program # (so the mouse pointer won't move on X when we touch the TFT screen) touch.grab() # Prints some info on how evdev sees our input device print(touch) # Even more info for curious people #print(touch.capabilities()) # Here we convert the evdev "hardware" touch coordinates into pygame surface pixel coordinates def getPixelsFromCoordinates(coords): # TODO check divide by 0! if tftDelta[0] < 0:
ecodes.KEY_2: "2", ecodes.KEY_3: "3", ecodes.KEY_4: "4", ecodes.KEY_5: "5", ecodes.KEY_6: "6", ecodes.KEY_7: "7", ecodes.KEY_8: "8", ecodes.KEY_9: "9", } rfidReaderName = sys.argv[1] rfidReaderPath = '' devices = evdev.list_devices() for device in devices: inputDevice = evdev.InputDevice(device) if inputDevice.name == rfidReaderName: rfidReaderPath = inputDevice.path inputDevice.close() if rfidReaderPath == '': sys.exit() rfidDevice = evdev.InputDevice(rfidReaderPath) for event in rfidDevice.read_loop(): # event.value contains the key events (https://python-evdev.readthedocs.io/en/latest/apidoc.html#evdev.events.KeyEvent) if event.type == evdev.ecodes.EV_KEY and event.value == 1: #print(evdev.categorize(event)) #print(event) if event.code == evdev.ecodes.KEY_ENTER: break
def find_device(self, name): for ev_path in evdev.list_devices(): device = evdev.InputDevice(ev_path) if device.name == name: return device return None
def run_remap(ui, device_name, jog_multiplier): # Open the input device. device = None for n in range(10): for d in [evdev.InputDevice(path) for path in evdev.list_devices()]: if d.name == device_name: device = d break if device: break else: print(f"Device '{device_name}' not found, retrying...") time.sleep(1) if not device: fatal(f"Device '{device_name}' not found.") device.grab() current_wheel = 0 left_right_keys = [e.KEY_LEFT, e.KEY_RIGHT, 'Left/Right'] volume_keys = [e.KEY_VOLUMEDOWN, e.KEY_VOLUMEUP, 'VolUp/Down'] up_down_keys = [e.KEY_UP, e.KEY_DOWN, 'Up/Down'] key_modes = [left_right_keys, up_down_keys, volume_keys] button1_pressed = False jog_mode = 0 dial_mode = 1 def print_help(): global last_notification key4 = 'KEY_F' if button1_pressed else 'KEY_F11' key2 = 'Toggle Dial' if button1_pressed else 'Toggle Jog' help = (f'[ALT] [{key2}] [KEY_SPACE] [{key4}] [KEY_MUTE]\n' + f' Jog mode : {key_modes[jog_mode][2]}\n' + f' Dial mode: {key_modes[dial_mode][2]}') global quiet if not quiet: print(help) if last_notification: n = last_notification n.update(notification_summary, help) else: n = notify2.Notification(notification_summary, help) last_notification = n n.set_urgency(notify2.URGENCY_NORMAL) n.set_timeout(3000) n.show() print_help() async def read_loop(): nonlocal button1_pressed nonlocal jog_mode nonlocal dial_mode last_dial = 0 async for ev in device.async_read_loop(): if debug: print(f'Input: {ev}') if ev.type == e.EV_KEY: key = None value = 0 # Remap the buttons. if ev.code == e.BTN_4: # button 1 pressed button1_pressed = ev.value == 1 print_help() if ev.code == e.BTN_5 and ev.value == 0: # toggle jog/dial mode if button1_pressed: dial_mode = (dial_mode + 1) % len(key_modes) else: jog_mode = (jog_mode + 1) % len(key_modes) print_help() elif ev.code == e.BTN_6 and ev.value == 0: # button 2 -> space key = e.KEY_SPACE elif ev.code == e.BTN_7 and ev.value == 0: # button 4 -> F11 if button1_pressed: key = e.KEY_F else: key = e.KEY_F11 elif ev.code == e.BTN_8 and ev.value == 0: # button 5 -> mute key = e.KEY_MUTE if key: ui.write(e.EV_KEY, key, 1) ui.write(e.EV_KEY, key, 0) ui.syn() continue # Handle the dial if ev.type == e.EV_REL and ev.code == e.REL_DIAL: now_dial = ev.value delta = now_dial - last_dial last_dial = now_dial key = 0 if delta < 0: key = key_modes[dial_mode][0] if delta > 0: key = key_modes[dial_mode][1] if key != 0: ui.write(e.EV_KEY, key, 1) ui.write(e.EV_KEY, key, 0) ui.syn() # Handle the jog if ev.type == e.EV_REL and ev.code == e.REL_WHEEL: nonlocal current_wheel current_wheel = ev.value # Monitor the jog dial (reported as a wheel), and as long as the jog is rotated, # send the left or right keys repeatedly. The rotation angle decides the repeat frequency. async def periodic(): sleep_duration = 0.1 while True: nonlocal current_wheel nonlocal jog_mode await asyncio.sleep(sleep_duration) sleep_duration = 0.1 # -7 <= current_wheel <= 7 is the range. if -1 <= current_wheel <= 1: continue if debug: print(f'Wheel={current_wheel}') key = 0 count = 0 if current_wheel < 0: key = key_modes[jog_mode][0] count = -current_wheel elif current_wheel > 0: key = key_modes[jog_mode][1] count = current_wheel # Special case the small angles. Always make a single key event, and # don't repeat too fast. # range will be [1 - 7] * multiplier count = count - 1 speed = math.pow(count, 2) + 1 # range 2 - sleep_duration = 0.8 / (jog_multiplier * speed) # print(f'{count}, {sleep_duration}') ui.write(e.EV_KEY, key, 1) ui.write(e.EV_KEY, key, 0) ui.syn() def exception_handler(loop, context): print(f'Exception detected: {context}') if context['exception'].__class__ == OSError: print('Device disconnected.') os._exit(4) else: os._exit(1) try: asyncio.ensure_future(read_loop()) asyncio.ensure_future(periodic()) loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) loop.run_forever() finally: if device: try: device.ungrab() except: pass # Ignore exceptions.
ecodes.KEY_LEFT, 0, ecodes.KEY_RIGHT, ecodes.KEY_HOME, ecodes.KEY_UP, ecodes.KEY_PAGEUP ] #OLD: replaced by key from file #key = [1, 2, 7, 8] #Get key from file and convert to ecodes with open('key', 'r') as file: key_str = file.readline().strip() key = [int(i) for i in list(key_str)] key_num = [btns_num[i] for i in key] key_alt = [btns_alt[i] for i in key] #Startup debug info devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: print(device.fn, device.name, device.phys) device = evdev.InputDevice('/dev/input/event0') print(device) #Actual reading loop print("Reading input") for event in device.read_loop(): if event.type == ecodes.EV_KEY and event.value == KEY_PRESSED: #print(evdev.categorize(event)) if event.code in btns_num + btns_alt: #print("Number pressed") pressed.append(event.code) elif event.code == ecodes.KEY_KPENTER:
# The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) print("Version %s" % (PROGRAM_VERSION)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("bluereplay.local", 1883, 60) client.loop_start() devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] devices = {dev.fd: dev for dev in devices} value = 1 print("Value: {0}".format(value)) done = False while not done: r, w, x = select.select(devices, [], []) for fd in r: for event in devices[fd].read(): event = evdev.util.categorize(event) if isinstance(event, evdev.events.RelEvent): if event.event.value==-1: client.publish("table_soccer/" + socket.gethostname() + "/input","left") if event.event.value==1:
def __init__(self, path): self.evdev = evdev.InputDevice(path) self.evdev.grab() self.barcode = [] self.shift = False
help='list all available input devices', action='store_true') parser.add_argument('-e', '--event-device', help='event device to be used for input', type=str) parser.add_argument('hostname', help='hostname of VDR-server', nargs=1) args = parser.parse_args() if args.list_event_devices: eprint( 'available input devices (make sure adding your user to the input-group' ) for device in [ evdev.InputDevice(path) for path in evdev.list_devices() ]: eprint(' ', device.path, device.name, device.phys) sys.exit(0) osd = OSD() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((args.hostname[0], 37890)) s.send('CONTROL\r\n'.encode('utf-8')) data = s.recv(1024).decode('utf-8').split('\r\n') if not data[0].startswith('VDR') and data[0].endswith('READY'): eprint('error READY') client_id = int(data[1].split(' ')[1])
def __init__(self, device_node): self.device_node = device_node self.device = evdev.InputDevice(device_node) self.device.grab() info("Connected %s", self)
def open_device(path): device = evdev.InputDevice(path) logger.info("Opened device %s (%s)", device.fn, device.name) return device
def get_all_devices(self): self.all_devices = [] devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: self.all_devices.append([device.name, device.path])
#!/usr/bin/env python3 import evdev import asyncio import time from subprocess import check_output pwrkey = evdev.InputDevice("/dev/input/event0") odroidgo2_joypad = evdev.InputDevice("/dev/input/event2") sound = evdev.InputDevice("/dev/input/event2") brightness_path = "/sys/devices/platform/backlight/backlight/backlight/brightness" max_brightness = int( open("/sys/devices/platform/backlight/backlight/backlight/max_brightness", "r").read()) class Power: pwr = 116 class Joypad: l1 = 310 r1 = 311 up = 544 down = 545 left = 546 right = 547 f1 = 704
import evdev device = evdev.InputDevice('/dev/input/event0') print(device) for event in device.read_loop(): if event.type == evdev.ecodes.EV_KEY: print(evdev.categorize(event))
from evdev import InputDevice, categorize, ecodes import time, json from multiprocessing import Process from multiprocessing import Queue import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import socket print("Start") print(evdev.list_devices()) dev = None devices = [evdev.InputDevice(path) for path in evdev.list_devices()] for device in devices: print(device.info, device.name, '#', device.phys) print(device.leds(verbose=True)) if '1400g' in device.name: dev = InputDevice(device) print("selected>>>>>") if not dev: print("Device must by set manually...") dev = InputDevice('/dev/input/event0') print("Selected device is", dev) dev.grab()
'Hit a key to indicate macro to unprotect') setCapsLock(device, 'on') unprotect = True elif unprotect and event.value == 1: if ecodes.KEY[event.code] in macros: unprotectKey(ecodes.KEY[event.code], macros) notifySend( 'Keyboard Macros', 'Macro <b>{}</b> is no more protected'.format( ecodes.KEY[event.code])) else: notifySend('Keyboard Macros', 'Macro not found') setCapsLock(device, 'off') unprotect = False # Execute macros else: for keysym, action in macros.items(): if event.code == ecodes.ecodes[keysym] and event.value == 1: pressKeys(action['key_down'], ui) if __name__ == '__main__': dev = getDevice() device = evdev.InputDevice(dev) resetLeds(device) notifySend('Keyboard Macros', 'Running and connected to <b>{}</b>'.format(dev)) ui = UInput() readKeyboard(device, ui)