Skip to content

Instantly share code, notes, and snippets.

Created December 26, 2012 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4378307 to your computer and use it in GitHub Desktop.
Save anonymous/4378307 to your computer and use it in GitHub Desktop.
Simple Wrapper around XInput API
# Simple Wrapper around XInput API
#
# Author: David Coles <coles.david@gmail.com>
import ctypes
from ctypes.wintypes import BYTE, WORD, SHORT, DWORD
class XInputGamepad(ctypes.Structure):
_fields_ = [
("buttons", WORD),
("leftTrigger", BYTE),
("rightTrigger", BYTE),
("thumbLX", SHORT),
("thumbLY", SHORT),
("thumbRX", SHORT),
("thumbRY", SHORT),
]
def __repr__(self):
return "XInputGamepad(thumbLX={0}, thumbRX={1}, ...)".format(self.thumbLX, self.thumbRX)
class XInputState(ctypes.Structure):
_fields_ = [
("packetNumber", DWORD),
("gamepad", XInputGamepad),
]
def __repr__(self):
return "XInputState(packetNumber={0})".format(self.packetNumber)
class XInputVibration(ctypes.Structure):
_fields_ = [
("leftMotorSpeed", WORD),
("rightMotorSpeed", WORD),
]
def __init__(self, leftSpeed, rightSpeed):
self.leftMotorSpeed = leftSpeed
self.rightMotorSpeed = rightSpeed
xinput = ctypes.windll.xinput9_1_0
def getstate(index):
state = XInputState(0)
res = xinput.XInputGetState(index, ctypes.byref(state))
if res != 0:
raise ctypes.WinError(res)
return state.gamepad
def setstate(index, state):
res = xinput.XInputSetState(index, ctypes.byref(state))
if res != 0:
raise ctypes.WinError(res)
if __name__ == "__main__":
print("Attempting to use first gamepad")
setstate(0, XInputVibration(65535, 0))
raw_input("Left motor. Press any key to continue...")
setstate(0, XInputVibration(0 , 65535))
raw_input("Right motor. Press any key to continue...")
@martburg
Copy link

Imprecise !!
use:

class XInputGamepad(ctypes.Structure):
fields = [
('buttons', ctypes.c_ushort),
('left_trigger', ctypes.c_ubyte),
('right_trigger', ctypes.c_ubyte),
('l_thumb_x', ctypes.c_short),
('l_thumb_y', ctypes.c_short),
('r_thumb_x', ctypes.c_short),
('r_thumb_y', ctypes.c_short),
]

https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinput_gamepad(v=vs.85).aspx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment