Skip to content

Instantly share code, notes, and snippets.

@dcoles
Forked from anonymous/xinput.py
Created Dec 26, 2012
Embed
What would you like to do?
# 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...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment