Giter Club home page Giter Club logo

inputs's Introduction

Inputs

https://raw.githubusercontent.com/zeth/inputs/master/devices.png

Inputs aims to provide cross-platform Python support for keyboards, mice and gamepads.

Install

Install through pypi:

pip install inputs

Or download the whole repository from github:

git clone https://github.com/zeth/inputs.git
cd inputs
python setup.py install

About

The inputs module provides an easy way for your Python program to listen for user input.

Currently supported platforms are Linux (including the Raspberry Pi and Chromebooks in developer mode), Windows and the Apple Mac.

Python versions supported are all versions of Python 3 and your granddad's Python 2.7.

To get started quickly, just use the following:

from inputs import devices

For more information, read the documentation at ReadTheDocs

(Also available in the docs directory of the repository)

To get involved with inputs, please visit the github project at:

https://github.com/zeth/inputs

inputs's People

Contributors

frastlin avatar zeth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

inputs's Issues

expand readthedocs

It would be nice for many of us to have a list of methods and properties of this excellent library

MacBook Keyboard BadPrototypeError

When I run the example Code

inputs import get_key
while 1:
    events = get_key()
    for event in events:
        print(event.ev_type, event.code, event.state)

on my MacBook Pro Late 2011 with macOS 10.12.3 I get the following error:

Process Process-1:
Traceback (most recent call last):
  File "//anaconda/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "//anaconda/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "//anaconda/lib/python2.7/site-packages/inputs.py", line 1913, in mac_keyboard_process
    class MacKeyboardSetup(NSObject):
BadPrototypeError: Objective-C expects 1 arguments, Python argument has 2 arguments for <unbound selector init_with_handler of MacKeyboardSetup at 0x106bca308>

Both, inputs and PyObjC has been installed with pip

AttributeError: 'Meu_Objeto' object has no attribute 'nome'

Hi, could you give a hand? I got this error msg in PyCharm console.
That,s my code:

class Meu_Objeto:
def int(self):
self.nome = 'Carlos'
self.idade = 45
print('Construtor criado com sucesso')

def imprime(self):
    print('Ola, meu nome eh {} e eu tenho {} anos', self.nome, self.idade)

Carlos = Meu_Objeto()
Carlos.imprime()

Thanks

High CPU consumption from game-pad demo

When running this simple game-pad demo provided in the docs the program consumes ~30% CPU on my computer using an intel i7 6500u, even if the console output is commented out. I tried adding a delay within the infinite loop, but this causes the events to lag behind the actual controller (xbox one) inputs.

Any thoughts? The CPU usage seems excessive for only receiving game-pad input.

Support Modifier Keys

I would like to know if one of the modifier keys are pressed at any point in time. I can track this myself, but it's so common, that I would like it to be done in inputs. Like in Javascript, it would be nice if there was a list of modifier keys added to each event object.

Can't "see" iPega PG-9077

I am running python 3.6.3 on windoze 10.
I have a bluetooth keyboard and mouse by Microsoft.
I have a iPega PG-9077 connected to windoze 10 by bluetooth.

from inputs import devices
devices.gamepads
[]

Keyboards and mice returns single (expected) connections so that'll be the microsoft pair.

So, is there something else I need to to get inputs to "see" the iPega gamepad please?

Try PS4 controller on Windows

There are two ways to use non-Microsoft controllers.

  1. Use the deprecated DirectInput API (we might support this sooner or later), however it is less full featured.
  2. Emulate a Microsoft Xinput controller, this is common approach in the gaming world.

For 2, there seems to be lots of provided drivers and programs. One of the popular options seems to be DS4Windows which supports the PS4 controller.

http://ds4windows.com/

Try this and see what happens on Windows, does inputs find the controller?

KeyError whenever I try to create a device manager

If I just import devices everything works fine, but I decided I wanted to loop trying over and over again if the joystick couldn't be found, and I was getting the same device list over and over again even after plugging in my device so I figured I needed to create my own device manager in order to get a refreshed device list. Then I discovered I can never construct my own DeviceManager, I always get this traceback.

Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/mandimus/joystick.py", line 110, in joystick_event_loop
Dec 20 15:12:56 eruv bash[11092]: device_manager = DeviceManager() # re-create every loop in case plugged in
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3188, in init
Dec 20 15:12:56 eruv bash[11092]: self._post_init()
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3200, in _post_init
Dec 20 15:12:56 eruv bash[11092]: self._find_leds()
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3359, in _find_leds
Dec 20 15:12:56 eruv bash[11092]: self._parse_led_path(path)
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3366, in _parse_led_path
Dec 20 15:12:56 eruv bash[11092]: self.leds.append(SystemLED(self, path, name))
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3082, in init
Dec 20 15:12:56 eruv bash[11092]: super(SystemLED, self).init(manager, path, name)
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3003, in init
Dec 20 15:12:56 eruv bash[11092]: self._post_init()
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3086, in _post_init
Dec 20 15:12:56 eruv bash[11092]: self._led_type_code = self.manager.get_typecode('LED')
Dec 20 15:12:56 eruv bash[11092]: File "/home/prophet/.local/lib/python2.7/site-packages/inputs.py", line 3421, in get_typecode
Dec 20 15:12:56 eruv bash[11092]: return self.codes['type_codes'][name]
Dec 20 15:12:56 eruv bash[11092]: KeyError: 'LED'

Generic Xbox 360 (Afterglow) not being detected

After finding the device id using lsusb, I can get my gamepad detected in jstest-gtk and the emulator I want to run using xboxdrv, but when I try to access it using get_gamepad() I get an error inputs.UnpluggedError: No gamepad found. I have a feeling it might be because inputs is looking for gamepads using the /dev/inputs/by-id/ entry, but my gamepad does not have a corresponding entry there (shows up as /dev/inputs/js3 and /dev/inputs/event8 however).

Seems like if it is detected by jstest and my emulator it should be able to work with inputs.

Any ideas?

could not find any tests

I am looking for a platform independent way to read keyboard input. I found inputs. Looking at your code it looks promising. I just discovered that it has no tests and consequently no test coverage. How do you make sure it works on one or even multiple platforms?

struct.error: unpack requires a string argument of length 16

It doesn't like the chunk size of 24 on Python 2.7, stops the error if set to 16.

Traceback (most recent call last):
  File "C:\Users\Peter\Python\MouseTrack\extensions\test.py", line 17, in <module>
    events = get_key()
  File "C:\Users\Peter\Python\MouseTrack\extensions\inputs.py", line 2698, in get_key
    return keyboard.read()
  File "C:\Users\Peter\Python\MouseTrack\extensions\inputs.py", line 2104, in read
    return next(iter(self))
  File "C:\Users\Peter\Python\MouseTrack\extensions\inputs.py", line 2064, in __iter__
    event = self._do_iter()
  File "C:\Users\Peter\Python\MouseTrack\extensions\inputs.py", line 2087, in _do_iter
    events = [self._make_event(*event) for event in evdev_objects]
  File "C:\Users\Peter\Python\MouseTrack\extensions\inputs.py", line 87, in chunks
    yield struct.unpack(EVENT_FORMAT, raw[i:i+24])
struct.error: unpack requires a string argument of length 16

PS3 not detected when on bluetooth

I'm on an RPi Zero W, running Raspbian Jessie, and an official PS3 controller.

I'm running the newest version of inputs from this git.

The controller shows up as a joystick under /dev/input/js0. I can run jstest /dev/input/js0 and see all axes and buttons.

Code I'm trying:

#!/usr/bin/env python3
from inputs import devices
print('List Devices')
for device in devices:
        print(device)
print('Done')

Output when using bluetooth:

Devices
Done

It works when plugged in via USB though:

Devices
Sony PLAYSTATION(R)3 Controller
Sony PLAYSTATION(R)3 Controller Motion Sensors
Done

freeze_support ERROR (keyboard)

I have this error when I use the keyboard key print example script.
If I work with the Gamepad listener everything works fine!
I'm new to programing so I dont' know what this means.

Win 10 x64

`An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.

    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.`

get_gamepad returns always only one event

get_gamepad always returns a single event.
The examples show a for loop to loop through the returned array which is a bit of a no brainer since its only one element.
Shouldnt the method return an array of all events which happened since the last call to get_gamepad?
Instead one has to call the method multiple times to get all "updates"

PS: Sorry for spamming issues!

We found a Gamepad

This message is printed whenever a gamepad is conntected.
It's very valuable for the first tests but I wonder if it starts interfering with other outputs.
I know that is not really an issue, but I would like to have the possibility to disable this message.
Any ideas?

Clean exit - BrokenPipeError

OS: Windows 10
Python: 3.6

Is there a way to have a clean exit from a program that uses the library Inputs?
I exit the while loop when the key ESC is pressed. However, the program does not terminate. If I press CTRL+C, the program does not terminate (s. image).
I even tried to attach a window to the main program (a pygame window) that when closed terminates it. It seems to work at first glance, but if I press any keyboard key after closing that window I get a BrokenPipeError (s. image).
Any ideas?

broken_pipe_error

get_gamepad seems to block

For my application it is crucial to check if there are new events but if not, proceed with the other code.
However: In order to check for new events I need to call get_gamepad which calls internal read on the device. This function seems to block until an event arrives.
It would be awesome to add a nonblocking read or an option to specify all reads as nonblocking!

As always: Thanks for your library!

Allow one to only get input when a spacific window is focused

Hello,
I don't want to log all key commands to my game when the user is not focused on the game window.
There should be an attribute of inputs that one can set to only capture input of a specific window.
Here is what I found:
The second answer claims to be cross-platform
Getting Window Title on Windows
OSX get active window

The problem is that all these require something like win32.
I know pygame can tell if the game window is focused without these dependencies. I wonder if the same process can let inputs know that the window has changed focus?
Thanks,

Rumble support?

Does inputs support the rumble functionality in most gamepads? I realize that's output rather than input but it still seems appropriate.

Thank you for the library! I'm using it to write a scratch 2.0 extension so our CoderDojo can have kids use the full functionality of the gamepads; currently we're limited to mapping buttons to keyboard keys and one of the sticks to the mouse with third party software.
All I'm missing is rumble functionality.

One question though, is there a list of what all the ev_types and codes mean? For example, I currently completely ignore SYN_DROPPED and others, only use events with types Key and Absolute actually. I'm not sure how robust this ๐Ÿ™ˆ approach is.

inputs does not recognise a Joystick device, UnpluggedError: No gamepad found.

My Joystick is connected but only devices seen are Mouse and Keyboard, and get_game pad fails.
(Winows10 Python3.6)
Traceback (most recent call last):
File "C:\Python\Python36\lib\site-packages\inputs.py", line 2711, in get_gamepad
gamepad = devices.gamepads[0]
IndexError: list index out of range
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Python/Dhruve and me/Pygame/device_inputs.py", line 22, in
events = get_gamepad()
File "C:\Python\Python36\lib\site-packages\inputs.py", line 2713, in get_gamepad
raise UnpluggedError("No gamepad found.")
inputs.UnpluggedError: No gamepad found.

Joystick Tophat input

How do you write something that does
`if joystick_tophat(an arbitrary name) == forward

//do something?
`

ERROR on import..

Just the simple act of importing imputs generates this error..

any ideas?

 Traceback (most recent call last):
  File "test.py", line 27, in <module>
    from inputs import devices
  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 3652, in <module>
    devices = DeviceManager()  # pylint: disable=invalid-name

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 3188, in __init__
    self._post_init()

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 3197, in _post_init
    self._find_devices()

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 3346, in _find_devices
    self._find_by('id')

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 3354, in _find_by
    self._parse_device_path(device_path)

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 3241, in _parse_device_path
    char_path_override))

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 2403, in __init__
    self._set_name()

  File "/home/koos/.local/lib/python3.6/site-packages/inputs.py", line 2417, in _set_name
    self.get_char_name()) as name_file:
FileNotFoundError: [Errno 2] No such file or directory: '/sys/class/input/event28/device/name'

Inputs Does Not Work on python 3.7 on Conda and Windows

Hello,
On Windows (I don't know about other platforms), create a new environment in conda, install inputs, and run the keyboard_example.py:

conda create --name test1 python=3.7
pip install inputs
python keyboard_example.py

press any key and nothing happens.
On python 3.5 and 3.6 the example works perfectly.
Here are the changes in python 3.7 Maybe "PEP 563: Postponed Evaluation of Annotations" is effecting the decorators? But I am just making a wild guess here. I don't see any async or await keywords used anywhere which looks to be the only breaking compatibility between 3.6 and 3.7.

catch KeyboardInterrupt

Hello,
Somewhere there needs to be a place that triggers an event for KeyboardInterrupt. This can be done by using a try statement:
try:
yield event
except KeyboardInterrupt:
yield KeyboardInterruptEvent

This will help in:
#23 (comment)
It is also useful to allow users to block KeyboardInterrupt if they really want (although it should not be default).

PS4 via Bluetooth?

Does not work with PS4 controller via bluetooth..

Controller works fine in jstest and in pygame..

any ideas?

i.e. this pygame code works perfectly.. But i would prefer to use inputs :)

image

"AttributeError: 'NoneType' object has no attribute 'get_char_device_path'"

I'm running a script for Anki Vector on a machine with Linux Mint Tessa 19.

When I don't have a gamepad plugged in, everything acts normally: it runs as far as it can without the lib and then throws an error when it can't find a gamepad. However, when the gamepad is plugged in, it immediately throws this long error message:

skye@skye-studio:~/Desktop/vector/controller$ python3 main.py
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from inputs import get_gamepad
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3652, in <module>
    devices = DeviceManager()  # pylint: disable=invalid-name
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3188, in __init__
    self._post_init()
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3200, in _post_init
    self._find_leds()
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3359, in _find_leds
    self._parse_led_path(path)
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3364, in _parse_led_path
    self.leds.append(GamepadLED(self, path, name))
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3133, in __init__
    super(GamepadLED, self).__init__(manager, path, name)
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3003, in __init__
    self._post_init()
  File "/home/skye/.local/lib/python3.6/site-packages/inputs.py", line 3137, in _post_init
    self._character_device_path = self.gamepad.get_char_device_path()
AttributeError: 'NoneType' object has no attribute 'get_char_device_path'```

I don't really know what this means and I don't know how to fix it. Any help is greatly appreciated.

do something when "events" are empty (no user input)

Is not an Issue but how can I do something when there was a interval without any user input?

for event in events:
do some stuff
if not events: #like if events are empty because there was no user input
do some other stuff

Rescanning OS for peripherals crashs when connecting xbox controller.

Using the following test code to try to enable "after launch" joystick connection:

# -*- coding: windows-1252 -*-

import inputs
from time import sleep
from traceback import print_exc

try:
  while 1:

    # Wait for a joystick to be connected
    print "Please connect a joystick..."
    while 1:
      try:
        inputs.devices = inputs.DeviceManager() # Rescan OS for joystick.
        inputs.get_gamepad()
        break

      except inputs.UnpluggedError:
        sleep(1.0 / 30.0)

    # Print connected device name
    print(inputs.devices.gamepads[0])

    # While joystick is connected
    try:
      while 1:
        try:
          events = inputs.get_gamepad()
          for event in events:
            print(event.ev_type, event.code, event.state)

        except inputs.UnknownEventType:
          pass

    except inputs.UnpluggedError:
      print("Joystick unplugged!")

except:
  print_exc()

I have the following crash when I connect a new xbox controller:

  File "D:\projets\tests\lib\site-packages\inputs.py", line 2713, in get_gamepad
    return gamepad.read()
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2101, in read
    return next(iter(self))
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2192, in __iter__
    self.__check_state()
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2205, in __check_state
    self.__handle_changed_state(state)
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2270, in __handle_changed_state
    events.extend(self.__get_axis_events(state, timeval))
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2304, in __get_axis_events
    events = self.__emulate_axis(axis_changes, timeval)
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2316, in __emulate_axis
    timeval=timeval)
  File "D:\projets\tests\lib\site-packages\inputs.py", line 2229, in create_event_object
    event_type)
UnknownEventType: ("We don't know what kind of event a %s is.", 'Absolute')

And indeed, inputs.DeviceManager.codes['type_codes'] is empty on consecutives calls to inputs.DeviceManager. constructors (it only contains values the first time constructor is called).

Keyboard devices dont show up in Docker / VM

It seems that for some reason the inputs.devices.keyboards is empty in Docker and in Virtual Machines. I have tried running xinput and can see that there are virtual devices but there are no /dev/inputs which is what the library relies on.

See screenshot here:
https://imgur.com/a/8z6cKev

Any ideas on how to fix this, or is it just not possible?
I know you can run xinputs and get the state of key presses on the virtual devices so I guess theres the chance of writing a different code path to poll this utility but that seems ugly.

Several Key Events Trigger 4 Times on one press and release

Hello,
The following keys trigger 4 times every press:
backspace
delete
home
end
pageup
pagedown
left
right
up
down

Here are the 4 events from delete:

{'device': inputs.Keyboard("/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"), 'timestamp': 1545442140.441741, 'code': 'KEY_DELETE', 'state': 1, 'ev_type': 'Key'}

{'device': inputs.Keyboard("/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"), 'timestamp': 1545442140.458181, 'code': 'KEY_DELETE', 'state': 1, 'ev_type': 'Key'}

{'device': inputs.Keyboard("/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"), 'timestamp': 1545442140.459182, 'code': 'KEY_DELETE', 'state': 0, 'ev_type': 'Key'}

{'device': inputs.Keyboard("/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"), 'timestamp': 1545442140.595211, 'code': 'KEY_DELETE', 'state': 0, 'ev_type': 'Key'}

Notice that the middle events are almost at the same time. None of the other keys do this, just the above keys I mentioned.

Laptop Keyboard not detected by get_key()

Hi

I'm just having a play with inputs on my Linux Laptop, when I run the example to look at the devices it gives me:

Logitech USB Optical Mouse
USB2.0 UVC HD Webcam
Atmel Atmel maXTouch Digitizer

But doesn't show the keyboard. When I run the simple keyboard example it crashes with:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/inputs.py", line 2692, in get_key
keyboard = devices.keyboards[0]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/amos/Projects/mech/myinputs.py", line 3, in
events = get_key()
File "/usr/local/lib/python3.5/site-packages/inputs.py", line 2694, in get_key
raise UnpluggedError("No keyboard found.")
inputs.UnpluggedError: No keyboard found.

Essentially I guess, because no keyboard is being recognised.

Plugging an external keyboard in removes this error but creates a new permissions related error.

MacOsX

Is your package is compatible with Mac ? Is thes is under active development ? do i need to install the pygames / piglet also ? what are the dependencies to connect it to the game and opencv ?

Do i require gamepad ? what are Gamepads alternatives for MacOSx ? as the mentioned game pads are not available for mac. Please guide

get_mouse blocks before first execution

Problem

def run():
	events = get_mouse()
	for event in events:
		print(event.__dict__)

	while True:
		run()
		print("new loop")

With the above code, "new loop" will not print until after the first event is triggered.

What should happen

"new loop" should print when the application starts and continue printing until the application stops. If one does get_key with the above code, the proper result happens.

Other Information

OS: Windows 10 64 bit
python 3.6

A simple fix for OLD code paths.

In iter_unpack The code is always checking OLD it would be better to change this to:

if OLD:
    def iter_unpack(raw):
        """Yield successive 24-sized chunks from message."""
            return chunks(raw)
else:
    def iter_unpack(raw):
        """Yield successive 24-sized chunks from message."""
            return struct.iter_unpack(EVENT_FORMAT, raw)

Now the OLD vs NEW check is only performed at file load, not on each function call.

Sorry for not making a pull request.

EOFError when there isn't main()

I tried to run the keyboard_example.py example and it works fine but when I removed def main() and if __name__ == "__main__"... there was EOFError. In other words, this:

"""Simple example showing how to get keyboard events."""

from __future__ import print_function

from inputs import get_key

"""Just print out some event infomation when keys are pressed."""
while 1:
    events = get_key()
    if events:
        for event in events:
            print (event.ev_type, event.code, event.state)

results in:

Traceback (most recent call last):
  File "C:/Python27/TEST_ENV/_my/inputs/test2.py", line 9, in <module>
    events = get_key()
  File "C:\Python27\TEST_ENV\lib\site-packages\inputs.py", line 3661, in get_key
    return keyboard.read()
  File "C:\Python27\TEST_ENV\lib\site-packages\inputs.py", line 2517, in read
    return next(iter(self))
  File "C:\Python27\TEST_ENV\lib\site-packages\inputs.py", line 2471, in __iter__
    event = self._do_iter()
  File "C:\Python27\TEST_ENV\lib\site-packages\inputs.py", line 2495, in _do_iter
    data = self._get_data(read_size)
  File "C:\Python27\TEST_ENV\lib\site-packages\inputs.py", line 2575, in _get_data
    return self._pipe.recv_bytes()
EOFError

NameError: global name 'XINPUT_ERROR_SUCCESS' is not defined

First of all: Great thx for this lib. It just works and is so easy to use. Thank you!

When I ran my program a while, I suddenly got this error:

NameError: global name 'XINPUT_ERROR_SUCCESS' is not defined

Since it happened out of nowhere I cant give you a debugging hint.
I run this lib on win7 with XBox One Controllers (works like a charm!)

Full traceback:

    events = get_gamepad()
  File "C:\Anaconda2\lib\site-packages\inputs.py", line 2713, in get_gamepad
    return gamepad.read()
  File "C:\Anaconda2\lib\site-packages\inputs.py", line 2101, in read
    return next(iter(self))
  File "C:\Anaconda2\lib\site-packages\inputs.py", line 2192, in __iter__
    self.__check_state()
  File "C:\Anaconda2\lib\site-packages\inputs.py", line 2199, in __check_state
    state = self.__read_device()
  File "C:\Anaconda2\lib\site-packages\inputs.py", line 2406, in __read_device
    if res == XINPUT_ERROR_SUCCESS:
NameError: global name 'XINPUT_ERROR_SUCCESS' is not defined
Segmentation fault

'Keyboard' object has no attribute 'name'

Using the example from the readme in a file called devices.py, I stumbled on an AttributeError.

from inputs import devices

for device in devices:
    print(device)
$ python devices.py
Traceback (most recent call last):
  File "devices.py", line 4, in <module>
    print(device)
  File "/Users/agestuds/python_projects/controller/.controller/lib/python3.5/site-packages/inputs.py", line 2031, in __str__
    return self.name
AttributeError: 'Keyboard' object has no attribute 'name'

Using macOS Sierra (10.12.3) and with inputs and pyobjc installed in a virtualenv with python version 3.5.2.

Create an all_events Function

Hello,
I would like to be able to grab mouse, keyboard, and gamepad events all at once.
Currently if I run get_mouse, get_key, get_gamepad one after another, the initial events of key and gamepad are not caught.
I would like a new function:
get_events
This should have all events and each event should have a new attribute of device_type that is either: "gamepad", "mouse", or "key".

Joystick found on boot but not usable

If a joystick is plugged into the computer on startup it does not appear to be usable until it is unplugged and plugged back in. The device is visible in dmesg and appears in the list of devices connected to the computer. Calling devices.gamepads[0].read() however blocks indefinitely and does not seem to get events.

Restarting udev or triggering it does not solve the problem.

Not 100% sure that this is a problem with inputs but it's between that and the OS.

Ubuntu 16.04 minimal install on Neousys 2510-VTC.

Max CPU usage on gamepad.read()

from inputs import devices
gamepad = devices.gamepads[0]
while True:
    print(gamepad.read())

^ with a 360 controller plugged in that uses 100% of 1 core.

Change the LEDs on a gamepad

Everything on the Xbox 360 Controller is fully supported in inputs in Linux and Windows, except changing the LEDs which appear like they could or should be programmable via the xpad driver but I haven't worked out how.

It would be cool to be able to change the LEDs on an Xbox 360 controller, then other gamepads too. To start with, I am just focusing on Linux.

What do we know?

We can send an event to /dev/input/eventN to change the caps lock led

import inputs
caps_lock = inputs.devices.keyboards[0].leds[0]
caps_lock.on()
caps_lock.off()

This sends an event in the normal evdev event format to the correct character device.

We can send an event to /dev/input/eventN to make the Gamepad rumble

import inputs
gamepad = inputs.devices.gamepads[0]
gamepad.set_vibration(1,1,1000)

On Linux, this does some interesting voodoo (in the method __get_vibration_code ) which creates a struct which is then encoded in hex and then sent as the code in the normal evdev event format to the correct character device.

We can get the current state of the gamepad led:

import inputs
gamepad_led = inputs.devices.gamepads[0].leds[0]
gamepad_led.status()

We cannot yet send an event to /dev/input/eventN to change the led,
either we don't know the right voodoo or there needs a tiny bit of
work in the linux driver.

We can (as root) bypass evdev and change brightness file and it will change the led. This is not the way.
Inputs runs as non-root and so we need to use /dev/input/eventN like with the caps lock light and rumble.

We have some info in the Linux source code.

We know all the brightness values ('commands'):

XBOX_STYLE_LED_CONTROL = {
    0: 'off',
    1: 'all blink, then previous setting',
    2: '1/top-left blink, then on',
    3: '2/top-right blink, then on',
    4: '3/bottom-left blink, then on',
    5: '4/bottom-right blink, then on',
    6: '1/top-left on',
    7: '2/top-right on',
    8: '3/bottom-left on',
    9: '4/bottom-right on',
    10: 'rotate',
    11: 'blink, based on previous setting',
    12: 'slow blink, based on previous setting',
    13: 'rotate with two lights',
    14: 'persistent slow all blink',
    15: 'blink once, then previous setting'
}

We know (based on this) that after the evdev phrase, the actual controller is expecting
0x01, 0x03 then the command.

Apparently, this also works on Max OS X

We seem to have all or most of the pieces, how do we put it together?

So in conclusion, I don't know what struct to write to the /dev/input/eventN character device to tell the kernel xpad driver that I want to change the led 'brightness' to the correct 'command' value.

And if this is not possible, I want to change the driver so it is.

Useful Links

Checking if the button is still pressed

I'm trying to make a script to controll my drone and I need to not if the button is still pressed. The event is being returned only on the first button press, but I need to know if the user is still holding the button. Probably there is a way to do this using the library, but I can't find anything in Docs

AttributeError: 'Keyboard' has no attribute 'name'

PS C:\Desktop\inputs-master\examples> py .\devices_example.py
we found a gamepad.
We have detected the following devices:

Traceback (most recent call last):
File ".\devices_example.py", line 18, in
main()
File ".\devices_example.py", line 14, in main
print(device)
File "C:\Desktop\inputs-master\examples\inputs.py", line 2033, in str
return self.name
AttributeError: 'Keyboard' object has no attribute 'name'
PS C:\Desktop\inputs-master\examples>

Finding this library was a spark of hope for me but sadly I couldn't make it function at python 3.6.1 Win10

analog stick coordinate reporting

So this entire issue is just trying to figure out how the coordinates for the analog sticks are reported. More specificity, what is the coordinate system? For instance, is the X- and Y-axis like this:

Y
|
|
|                 * - default orientation
|    origin
|  / 
------------------------------------- X

or are they like this:

                Y
                |   origin AND default orientation
                | / 
----------------*-------------------  X
                |
                |

also, knowing how far the X and Y axis go would be useful too. That way, a dev can convert from one of the above graphs to another with just some simple subtraction to both X and Y coordinates.

So, in a nutshell:

  1. What quadrants of the coordinate plane does this work with? Just one? Or all 4?
  2. How far do both axis go?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.