collab/igvc2018
git clone https://git.julia.blue/collab/igvc2018
22f4007
master
1""" Xbox 360 controller support for Python 211/9/13 - Steven Jacobs 3 4This class module supports reading a connected xbox controller. 5It requires that xboxdrv be installed first: 6 7sudo apt-get install xboxdrv 8 9See http://pingus.seul.org/~grumbel/xboxdrv/ for details on xboxdrv 10 11Example usage: 12 13import xbox 14joy = xbox.Joystick() #Initialize joystick 15 16if joy.A(): #Test state of the A button (1=pressed, 0=not pressed) 17print 'A button pressed' 18x_axis = joy.leftX() #X-axis of the left stick (values -1.0 to 1.0) 19(x,y) = joy.leftStick() #Returns tuple containing left X and Y axes (values -1.0 to 1.0) 20trigger = joy.rightTrigger() #Right trigger position (values 0 to 1.0) 21 22joy.close() #Cleanup before exit 23""" 24 25import subprocess 26import os 27import select 28import time 29 30 31class Joystick : 32"""Initializes the joystick/wireless receiver, launching 'xboxdrv' as a subprocess 33and checking that the wired joystick or wireless receiver is attached. 34The refreshRate determines the maximnum rate at which events are polled from xboxdrv. 35Calling any of the Joystick methods will cause a refresh to occur, if refreshTime has elapsed. 36Routinely call a Joystick method, at least once per second, to avoid overfilling the event buffer. 37 38Usage: 39joy = xbox.Joystick() 40""" 41 42def __init__ (self ,refreshRate = 30 ): 43self .proc = subprocess .Popen ( 44 ['xboxdrv' ,'--no-uinput' ,'--detach-kernel-driver' ], 45stdout = subprocess .PIPE ) 46self .pipe = self .proc .stdout 47# 48self .connectStatus = False #will be set to True once controller is detected and stays on 49self .reading = '0' * 140 #initialize stick readings to all zeros 50# 51self .refreshTime = 0 #absolute time when next refresh (read results from xboxdrv stdout pipe) is to occur 52self .refreshDelay = 1.0 / refreshRate #joystick refresh is to be performed 30 times per sec by default 53# 54# Read responses from 'xboxdrv' for upto 2 seconds, looking for controller/receiver to respond 55found = False 56waitTime = time .time ()+ 2 57while waitTime > time .time ()and not found : 58readable ,writeable ,exception = select .select ([self .pipe ], [], [], 590 ) 60if readable : 61response = self .pipe .readline () 62# Hard fail if we see this, so force an error 63if response [0 :7 ]== 'No Xbox' : 64raise IOError ('No Xbox controller/receiver found' ) 65# Success if we see the following 66if response [0 :12 ]== 'Press Ctrl-c' : 67found = True 68# If we see 140 char line, we are seeing valid input 69if len (response )== 140 : 70found = True 71self .connectStatus = True 72self .reading = response 73# if the controller wasn't found, then halt 74if not found : 75self .close () 76raise IOError ( 77'Unable to detect Xbox controller/receiver - Run python as sudo' 78 ) 79 80"""Used by all Joystick methods to read the most recent events from xboxdrv. 81The refreshRate determines the maximum frequency with which events are checked. 82If a valid event response is found, then the controller is flagged as 'connected'. 83""" 84 85def refresh (self ): 86# Refresh the joystick readings based on regular defined freq 87if self .refreshTime < time .time (): 88self .refreshTime = time .time ( 89 )+ self .refreshDelay #set next refresh time 90# If there is text available to read from xboxdrv, then read it. 91readable ,writeable ,exception = select .select ([self .pipe ], [], [], 920 ) 93if readable : 94# Read every line that is availabe. We only need to decode the last one. 95while readable : 96response = self .pipe .readline () 97# A zero length response means controller has been unplugged. 98if len (response )== 0 : 99raise IOError ('Xbox controller disconnected from USB' ) 100readable ,writeable ,exception = select .select ([self .pipe ], 101 [], [],0 ) 102# Valid controller response will be 140 chars. 103if len (response )== 140 : 104self .connectStatus = True 105self .reading = response 106else :#Any other response means we have lost wireless or controller battery 107self .connectStatus = False 108 109"""Return a status of True, when the controller is actively connected. 110Either loss of wireless signal or controller powering off will break connection. The 111controller inputs will stop updating, so the last readings will remain in effect. It is 112good practice to only act upon inputs if the controller is connected. For instance, for 113a robot, stop all motors if "not connected()". 114 115An inital controller input, stick movement or button press, may be required before the connection 116status goes True. If a connection is lost, the connection will resume automatically when the 117fault is corrected. 118""" 119 120def connected (self ): 121self .refresh () 122return self .connectStatus 123 124# Left stick X axis value scaled between -1.0 (left) and 1.0 (right) with deadzone tolerance correction 125def leftX (self ,deadzone = 4000 ): 126self .refresh () 127raw = int (self .reading [3 :9 ]) 128return self .axisScale (raw ,deadzone ) 129 130# Left stick Y axis value scaled between -1.0 (down) and 1.0 (up) 131def leftY (self ,deadzone = 4000 ): 132self .refresh () 133raw = int (self .reading [13 :19 ]) 134return self .axisScale (raw ,deadzone ) 135 136# Right stick X axis value scaled between -1.0 (left) and 1.0 (right) 137def rightX (self ,deadzone = 4000 ): 138self .refresh () 139raw = int (self .reading [24 :30 ]) 140return self .axisScale (raw ,deadzone ) 141 142# Right stick Y axis value scaled between -1.0 (down) and 1.0 (up) 143def rightY (self ,deadzone = 4000 ): 144self .refresh () 145raw = int (self .reading [34 :40 ]) 146return self .axisScale (raw ,deadzone ) 147 148# Scale raw (-32768 to +32767) axis with deadzone correcion 149# Deadzone is +/- range of values to consider to be center stick (ie. 0.0) 150def axisScale (self ,raw ,deadzone ): 151if abs (raw )< deadzone : 152return 0.0 153else : 154if raw < 0 : 155return (raw + deadzone )/ (32768.0 - deadzone ) 156else : 157return (raw - deadzone )/ (32767.0 - deadzone ) 158 159# Dpad Up status - returns 1 (pressed) or 0 (not pressed) 160def dpadUp (self ): 161self .refresh () 162return int (self .reading [45 :46 ]) 163 164# Dpad Down status - returns 1 (pressed) or 0 (not pressed) 165def dpadDown (self ): 166self .refresh () 167return int (self .reading [50 :51 ]) 168 169# Dpad Left status - returns 1 (pressed) or 0 (not pressed) 170def dpadLeft (self ): 171self .refresh () 172return int (self .reading [55 :56 ]) 173 174# Dpad Right status - returns 1 (pressed) or 0 (not pressed) 175def dpadRight (self ): 176self .refresh () 177return int (self .reading [60 :61 ]) 178 179# Back button status - returns 1 (pressed) or 0 (not pressed) 180def Back (self ): 181self .refresh () 182return int (self .reading [68 :69 ]) 183 184# Guide button status - returns 1 (pressed) or 0 (not pressed) 185def Guide (self ): 186self .refresh () 187return int (self .reading [76 :77 ]) 188 189# Start button status - returns 1 (pressed) or 0 (not pressed) 190def Start (self ): 191self .refresh () 192return int (self .reading [84 :85 ]) 193 194# Left Thumbstick button status - returns 1 (pressed) or 0 (not pressed) 195def leftThumbstick (self ): 196self .refresh () 197return int (self .reading [90 :91 ]) 198 199# Right Thumbstick button status - returns 1 (pressed) or 0 (not pressed) 200def rightThumbstick (self ): 201self .refresh () 202return int (self .reading [95 :96 ]) 203 204# A button status - returns 1 (pressed) or 0 (not pressed) 205def A (self ): 206self .refresh () 207return int (self .reading [100 :101 ]) 208 209# B button status - returns 1 (pressed) or 0 (not pressed) 210def B (self ): 211self .refresh () 212return int (self .reading [104 :105 ]) 213 214# X button status - returns 1 (pressed) or 0 (not pressed) 215def X (self ): 216self .refresh () 217return int (self .reading [108 :109 ]) 218 219# Y button status - returns 1 (pressed) or 0 (not pressed) 220def Y (self ): 221self .refresh () 222return int (self .reading [112 :113 ]) 223 224# Left Bumper button status - returns 1 (pressed) or 0 (not pressed) 225def leftBumper (self ): 226self .refresh () 227return int (self .reading [118 :119 ]) 228 229# Right Bumper button status - returns 1 (pressed) or 0 (not pressed) 230def rightBumper (self ): 231self .refresh () 232return int (self .reading [123 :124 ]) 233 234# Left Trigger value scaled between 0.0 to 1.0 235def leftTrigger (self ): 236self .refresh () 237return int (self .reading [129 :132 ])/ 255.0 238 239# Right trigger value scaled between 0.0 to 1.0 240def rightTrigger (self ): 241self .refresh () 242return int (self .reading [136 :139 ])/ 255.0 243 244# Returns tuple containing X and Y axis values for Left stick scaled between -1.0 to 1.0 245# Usage: 246# x,y = joy.leftStick() 247def leftStick (self ,deadzone = 4000 ): 248self .refresh () 249return (self .leftX (deadzone ),self .leftY (deadzone )) 250 251# Returns tuple containing X and Y axis values for Right stick scaled between -1.0 to 1.0 252# Usage: 253# x,y = joy.rightStick() 254def rightStick (self ,deadzone = 4000 ): 255self .refresh () 256return (self .rightX (deadzone ),self .rightY (deadzone )) 257 258# Cleanup by ending the xboxdrv subprocess 259def close (self ): 260os .system ('pkill xboxdrv' )