I have been working on a program that uses the PyGame joystick interface. It is a wx widgets program. The wx widgets implementation of joystick access leaves much to be desired. I cannot tell if there is a way to access all the inputs that are available on a device. It looks like it may be limited to 6 axes. So I have been using PyGame as it detects everything on the joystick and makes it available.
One problem I encountered with the PyGame joystick interface (which is SDL 1.2 under the hood) is the inability to detect if a joystick disconnected. The application I am developing is for controlling some robotic hardware. So it is important that if I lose a joystick that it stop the motion of the robot and notify the user that the hardware failed or was unplugged. This is not a feature of the library however.
I searched around and did not find any other suitable Python libraries for joystick access, but I found one obscure piece of code that did something really interesting. It disabled the joystick submodule of PyGame and then re-enabled it. Then it checked to see if the number of joysticks had changed. If it did then it would take some action. I was curious and tried it. It works, sort of. Once you disable the joystick module you have to re-enable and re-init all the joysticks. You also cannot use the values that output for some amount of time. My guess is the submodule has to finish doing something before you get valid output values from the devices.
I ended up creating some code that does this:
- Disables the joystick sub module every 1 second.
- It immediately re-enables the sub module and re-inits all the joysticks.
- It waits 50mS or more before it starts regarding joystick data as valid.
I don’t know how long you really need to wait, or if you just need to give the event system a chance to trickle joy events through the system before the data is valid again. I am not sure. What I do know is that I am able to reliably detect when a joystick is disconnected within 1 second using this technique. I also get no glitching whatsoever by not taking joy data right away. The 50mS is how often I trigger the joystick polling in my application and it not calculated or tested for any kind of minimum wait. I suspect actually leaving the function that resets the joystick module may be what is need rather than waiting any amount of time.