def __init__(self, scope, device=0, warnings_enabled=False): """ Parameters: scope: microscope client, instance of scope_client.ScopeClient. device: the numerical index or string name of the input device (from output of enumerate_devices()). warnings_enabled: if True, print debug information to stderr. """ init_sdl() self.device, self.device_name, index, self.is_game_controller = open_device(device) if self.is_game_controller: self.jdevice = sdl2.SDL_GameControllerGetJoystick(self.device) else: self.jdevice = self.device self.device_id = sdl2.SDL_JoystickInstanceID(self.jdevice) self.num_axes = sdl2.SDL_JoystickNumAxes(self.jdevice) self.num_buttons = sdl2.SDL_JoystickNumButtons(self.jdevice) self.num_hats = sdl2.SDL_JoystickNumHats(self.jdevice) self.warnings_enabled = warnings_enabled self.scope = scope._clone() self.event_loop_is_running = False self.quit_event_posted = False self.throttle_delay_command_time_ratio = 1 - self.MAX_AXIS_COMMAND_WALLCLOCK_TIME_PORTION self.throttle_delay_command_time_ratio /= self.MAX_AXIS_COMMAND_WALLCLOCK_TIME_PORTION self._axes_throttle_delay_lock = threading.Lock() self._c_on_axes_throttle_delay_expired_timer_callback = SDL_TIMER_CALLBACK_TYPE(self._on_axes_throttle_delay_expired_timer_callback) self.handle_button_callback = None
def update(self): # sdl2.SDL_PumpEvents() # Pump, retreive events so they clear sdl2.SDL_JoystickUpdate() # Read all the joystick values axisScale = 1 / 2**15 self.axis = [ sdl2.SDL_JoystickGetAxis(self.joy, i) for i in range(sdl2.SDL_JoystickNumAxes(self.joy)) ] self.button = [ sdl2.SDL_JoystickGetButton(self.joy, i) for i in range(sdl2.SDL_JoystickNumButtons(self.joy)) ] self.roll = axisScale * self.axis[0] self.pitch = axisScale * self.axis[1] self.throttle = axisScale * self.axis[2] self.yaw = axisScale * self.axis[3] self.flap = 0.0 self.autoEngage = 2 * self.button[0] - 1 # "Soc-Engage-Switch" self.testMode = axisScale * self.axis[4] # "Test-Mode-Switch" self.testSel = axisScale * self.axis[5] # "Test-Select-Switch" self.trig = 2 * self.button[1] - 1 # "Trigger-Switch" self.thrSafe = 2 * self.button[2] - 1 # "Throttle-Safety-Switch" self.baseSel = axisScale * self.axis[ -1] # "Baseline-Select-Switch" (On Windows it came up as 6, on Linux 7...)
def open(self): self._j = sdl2.SDL_JoystickOpen(self._id) self._btn_count = sdl2.SDL_JoystickNumButtons(self._j) self.axes = list(0 for i in range(sdl2.SDL_JoystickNumAxes(self._j))) self.buttons = list( 0 for i in range(sdl2.SDL_JoystickNumButtons(self._j) + 4))
def __init__(self): # init SDL2 and grab joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) self.js = sdl2.SDL_JoystickOpen(0) # grab info for display a = sdl2.SDL_JoystickNumAxes(self.js) b = sdl2.SDL_JoystickNumButtons(self.js) h = sdl2.SDL_JoystickNumHats(self.js) if a == -1: print('*** No Joystick found ***') self.valid = False else: print('==========================================') print(' PS4 Joystick ') print(' axes:', a, 'buttons:', b, 'hats:', h) print('==========================================') self.valid = True self.ps4 = { 'num_axes': a, 'num_buttons': b, 'num_hats': h, 'leftStick': [0, 0], 'rightStick': [0, 0] }
def __init__(self, joyName=b'FrSky Taranis Joystick'): # Set up the joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) # Enumerate joysticks joyList = [] for i in range(0, sdl2.SDL_NumJoysticks()): joyList.append(sdl2.SDL_JoystickNameForIndex(i)) print(joyList) # By default, load the first available joystick or joyName. if (len(joyList) > 0): indxJoy = 0 try: indxJoy = joyList.index(joyName) except: pass self.joy = sdl2.SDL_JoystickOpen(indxJoy) else: print("Joystick Fail!") print("Joystick Name:", sdl2.SDL_JoystickName(self.joy)) print("Joystick NumAxes", sdl2.SDL_JoystickNumAxes(self.joy)) # print( "Joystick NumTrackballs:", sdl2.SDL_JoystickNumBalls(self.joy)) print("Joystick Buttons:", sdl2.SDL_JoystickNumButtons(self.joy)) # print( "Joystick NumHats:", sdl2.SDL_JoystickNumHats(self.joy)) self.axis = [] self.button = [] self.msg = [0.0] * 16
def __init__(self, device): """Initializes the device data based on the given device. :param device pyGame joystick object """ self._hardware_id = get_device_guid(device) self._windows_id = sdl2.SDL_JoystickInstanceID(device) self._vendor_id = sdl2.SDL_JoystickGetVendor(device) self._product_id = sdl2.SDL_JoystickGetProduct(device) name_object = sdl2.SDL_JoystickName(device) if name_object is None: self._name = "Unknown device" logging.getLogger("system").error( "Encountered an invalid device name for device {:d}".format( self._windows_id)) else: self._name = name_object.decode("utf-8") self._is_virtual = self._name == "vJoy Device" # Default mapping from axis id to physical axis number. This defaults # to a linear 1:1 mapping but for vJoy devices can change self._axes = [] for i in range(sdl2.SDL_JoystickNumAxes(device)): self._axes.append((i + 1, i + 1)) self._buttons = sdl2.SDL_JoystickNumButtons(device) self._hats = sdl2.SDL_JoystickNumHats(device) self._vjoy_id = 0 self._device_id = common.DeviceIdentifier(self._hardware_id, self._windows_id)
def run(): sdl2.ext.init() sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) window = sdl2.ext.Window("Controller test", size=(640, 480)) window.show() running = True if sdl2.joystick.SDL_NumJoysticks() < 1: print("No joysticks plugged in") return 0 joystick = sdl2.SDL_JoystickOpen(0) print("Name:", sdl2.SDL_JoystickName(joystick)) print("NumAxes", sdl2.SDL_JoystickNumAxes(joystick)) print("Trackballs:", sdl2.SDL_JoystickNumBalls(joystick)) print("Buttons:", sdl2.SDL_JoystickNumButtons(joystick)) print("Hats:", sdl2.SDL_JoystickNumHats(joystick)) print("Haptic?:", sdl2.SDL_JoystickIsHaptic(joystick)) #sdl2.SDL_JoystickClose(joystick) #return 0 while (running): events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_JOYAXISMOTION: print("=======================") for axis in range(sdl2.SDL_JoystickNumAxes(joystick)): print("Axis: %i, value: %i" % (axis, sdl2.SDL_JoystickGetAxis(joystick, axis))) if event.type == sdl2.SDL_JOYBUTTONDOWN: print("=======================") for button in range(sdl2.SDL_JoystickNumButtons(joystick)): print( "Button: %i, value: %i" % (button, sdl2.SDL_JoystickGetButton(joystick, button))) if event.type == sdl2.SDL_JOYHATMOTION: print("=======================") for hat in range(sdl2.SDL_JoystickNumHats(joystick)): print("Hat: %i, value: %i" % (hat, sdl2.SDL_JoystickGetHat(joystick, hat))) if event.type == sdl2.SDL_QUIT: running = False break window.refresh() return 0
def _init_axes(self): """Initializes the axes of the joystick. :return list of JoystickWrapper.Axis objects """ axes = [] for i in range(sdl2.SDL_JoystickNumAxes(self._joystick)): axes.append(JoystickWrapper.Axis(self._joystick, i)) return axes
def main(): init() joy = sdl2.SDL_JoystickOpen(0) print('Name: {}'.format(sdl2.SDL_JoystickName(joy))) print('Axes: {}'.format(sdl2.SDL_JoystickNumAxes(joy))) state = ControllerState() evt = sdl2.SDL_Event() running = True conn = SerialConnection( sys.argv[1] if len(sys.argv) >= 2 else '/dev/ttyACM0') # set to mode 1 so it will not attack conn.call(MD49_MODE, (0x00, 0x34, 0x01)) while running: while sdl2.SDL_PollEvent(ctypes.byref(evt)) != 0: if evt.type == sdl2.SDL_QUIT: running = False break elif evt.type == sdl2.SDL_JOYAXISMOTION: jaxis = evt.jaxis # print(state, jaxis.axis, jaxis.value) state.axis_state[jaxis.axis] = jaxis.value handle_axis_motion(conn, state, jaxis.axis, jaxis.value) elif evt.type == sdl2.SDL_JOYBUTTONUP: button = evt.jbutton if button.button == 0: # A: toggle independent state.ind = not state.ind print('Independent: {}'.format(state.ind)) elif button.button == 8: # B: log encoders print(conn.md49_get_encoders()) log_encoders(conn) elif button.button == 3: # Y: reset encoders conn.call(MD49_MODE, ( 0x00, 0x35, )) elif button.button == 4: # left shoulder: reverse state.r_rev = not state.r_rev print('Right reverse: {}'.format(state.r_rev)) elif button.button == 5: # right shoulder: reverse state.l_rev = not state.l_rev print('Left reverse: {}'.format(state.l_rev)) else: print('Button', button.button) time.sleep(0.01) sdl2.SDL_Quit()
def _load_calibrations(self, joy): """Loads the calibration data for the given joystick. :param joy SDL joystick instance """ cfg = config.Configuration() dev_id = util.device_identifier_from_sdl(joy) for i in range(sdl2.SDL_JoystickNumAxes(joy)): limits = cfg.get_calibration(dev_id, i + 1) self._calibrations[(dev_id, i+1)] = \ util.create_calibration_function( limits[0], limits[1], limits[2] )
def __init__(self): # init SDL2 and grab joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) self.js = sdl2.SDL_JoystickOpen(0) # grab info for display self.numAxes = sdl2.SDL_JoystickNumAxes(self.js) self.numButtons = sdl2.SDL_JoystickNumButtons(self.js) self.numHats = sdl2.SDL_JoystickNumHats(self.js) if self.numAxes <= 0: print('*** No Joystick found ***') self.valid = False else: self.valid = True
def __init__(self, host, port): self.pub = zmq.Pub((host, port)) # init SDL2 and grab joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) self.js = sdl2.SDL_JoystickOpen(0) # grab info for display a = sdl2.SDL_JoystickNumAxes(self.js) b = sdl2.SDL_JoystickNumButtons(self.js) h = sdl2.SDL_JoystickNumHats(self.js) print('==========================================') print(' Joystick ') print(' axes:', a, 'buttons:', b, 'hats:', h) print(' publishing: {}:{}'.format(host, port)) print('==========================================')
def open(self, device_index): self._sdl_controller = sdl2.SDL_GameControllerOpen(device_index) self._sdl_joystick = sdl2.SDL_GameControllerGetJoystick(self._sdl_controller) self._sdl_joystick_id = sdl2.SDL_JoystickInstanceID(self._sdl_joystick) self._controller_name = sdl2.SDL_JoystickName(self._sdl_joystick) self._num_axis = sdl2.SDL_JoystickNumAxes(self._sdl_joystick), self._num_buttons = sdl2.SDL_JoystickNumButtons(self._sdl_joystick) self._num_balls = sdl2.SDL_JoystickNumBalls(self._sdl_joystick) for btn_index in range(0, self.MAX_BUTTONS): self._button_down[btn_index] = 0 self._button_pressed[btn_index] = 0 self._button_released[btn_index] = 0 if self._sdl_joystick_id != -1: self._connected = True
def _load_calibrations(self, guid): """Loads the calibration data for the given joystick. :param guid the id of the joystick to load the calibration data for """ cfg = config.Configuration() for i in range(sdl2.SDL_JoystickNumAxes(self._joysticks[guid])): device = joystick_handling.JoystickDeviceData( self._joysticks[guid]) limits = cfg.get_calibration(util.device_id(device), i + 1) self._calibrations[(guid, i+1)] = \ util.create_calibration_function( limits[0], limits[1], limits[2] )
def __init__(self, net, topic='cmd'): # mp.Process.__init__(self) self.pub = zmq.Pub(net) self.topic = topic # init SDL2 and grab joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) self.js = sdl2.SDL_JoystickOpen(0) # grab info for display a = sdl2.SDL_JoystickNumAxes(self.js) b = sdl2.SDL_JoystickNumButtons(self.js) h = sdl2.SDL_JoystickNumHats(self.js) self.old_twist = Msg.Twist() print('==========================================') print(' Joystick ') print(' axes:', a, 'buttons:', b, 'hats:', h) print(' publishing: {}:{}'.format(net[0], net[1], topic)) print('==========================================')
def __init__(self, device): """Initializes the device data based on the given device. :param device pyGame joystick object """ self._hardware_id = get_device_guid(device) self._windows_id = sdl2.SDL_JoystickInstanceID(device) name_object = sdl2.SDL_JoystickName(device) if name_object is None: self._name = "Unknown device" logging.getLogger("system").error( "Encountered an invalid device name") else: self._name = name_object.decode("utf-8") self._is_virtual = self._name == "vJoy Device" self._axes = [] for i in range(sdl2.SDL_JoystickNumAxes(device)): self._axes.append((i + 1, i + 1)) self._buttons = sdl2.SDL_JoystickNumButtons(device) self._hats = sdl2.SDL_JoystickNumHats(device) self._vjoy_id = 0
def __init__(self): # init SDL2 and grab joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) self.js = sdl2.SDL_JoystickOpen(0) # grab info for display a = sdl2.SDL_JoystickNumAxes(self.js) b = sdl2.SDL_JoystickNumButtons(self.js) h = sdl2.SDL_JoystickNumHats(self.js) if a == -1: print('*** No Joystick found ***') self.valid = False else: print('==========================================') print(' PS4 Joystick ') print(' axes:', a) print(' buttons:', b) print(' hats:', h) print('==========================================') self.valid = True
def __init__(self, stage): '''Constructor''' self.WARM_UP = 0 self.QUALIFYING = 1 self.RACE = 2 self.UNKNOWN = 3 self.stage = stage self.parser = msgParser.MsgParser() self.state = carState.CarState() self.control = carControl.CarControl() self.steer_lock = 0.785398 self.max_speed = 100 self.prev_rpm = None # Initialize the joysticks sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK | sdl2.SDL_INIT_HAPTIC) assert sdl2.SDL_NumJoysticks() > 0 assert sdl2.SDL_NumHaptics() > 0 self.joystick = sdl2.SDL_JoystickOpen(0) self.haptic = sdl2.SDL_HapticOpen(0) assert sdl2.SDL_JoystickNumAxes(self.joystick) == 3 assert sdl2.SDL_HapticQuery(self.haptic) & sdl2.SDL_HAPTIC_CONSTANT # Initialize force feedback efx = sdl2.SDL_HapticEffect(type=sdl2.SDL_HAPTIC_CONSTANT, constant= \ sdl2.SDL_HapticConstant(type=sdl2.SDL_HAPTIC_CONSTANT, direction= \ sdl2.SDL_HapticDirection(type=sdl2.SDL_HAPTIC_CARTESIAN, dir=(0,0,0)), \ length=sdl2.SDL_HAPTIC_INFINITY, level=0, attack_length=0, fade_length=0)) self.effect_id = sdl2.SDL_HapticNewEffect(self.haptic, efx) sdl2.SDL_HapticRunEffect(self.haptic, self.effect_id, 1) sdl2.SDL_HapticSetAutocenter(self.haptic, 0) sdl2.SDL_HapticSetGain(self.haptic, 100) self.stats = sensorstats.Stats(inevery=8)
def __init__(self, app): self.app = app self.ui = self.app.ui # read from binds.cfg file or create it from template # exec results in edit_binds, a dict whose keys are keys+mods # and whose values are bound functions self.edit_bind_src = None # bad probs if a command isn't in binds.cfg, so just blow it away # if the template is newer than it # TODO: better solution is find any binds in template but not binds.cfg # and add em binds_filename = self.app.config_dir + BINDS_FILENAME binds_outdated = not os.path.exists( binds_filename) or os.path.getmtime( binds_filename) < os.path.getmtime(BINDS_TEMPLATE_FILENAME) if not binds_outdated and os.path.exists(binds_filename): exec(open(binds_filename).read()) self.app.log('Loaded key binds from %s' % binds_filename) else: default_data = open(BINDS_TEMPLATE_FILENAME).readlines()[1:] new_binds = open(binds_filename, 'w') new_binds.writelines(default_data) new_binds.close() self.app.log('Created new key binds file %s' % binds_filename) exec(''.join(default_data)) if not self.edit_bind_src: self.app.log('No bind data found, Is binds.cfg.default present?') exit() # associate key + mod combos with methods self.edit_binds = {} for bind_string in self.edit_bind_src: bind = self.parse_key_bind(bind_string) if not bind: continue # bind data could be a single item (string) or a list/tuple bind_data = self.edit_bind_src[bind_string] if type(bind_data) is str: bind_fnames = ['BIND_%s' % bind_data] else: bind_fnames = ['BIND_%s' % s for s in bind_data] bind_functions = [] for bind_fname in bind_fnames: if not hasattr(self, bind_fname): continue bind_functions.append(getattr(self, bind_fname)) self.edit_binds[bind] = bind_functions # get controller(s) # TODO: use kewl SDL2 gamepad system js_init = sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_JOYSTICK) if js_init != 0: self.app.log( "SDL2: Couldn't initialize joystick subsystem, code %s" % js_init) return sticks = sdl2.SDL_NumJoysticks() #self.app.log('%s gamepads found' % sticks) self.gamepad = None self.gamepad_left_x, self.gamepad_left_y = 0, 0 # for now, just grab first pad if sticks > 0: pad = sdl2.SDL_JoystickOpen(0) pad_name = sdl2.SDL_JoystickName(pad).decode('utf-8') pad_axes = sdl2.SDL_JoystickNumAxes(pad) pad_buttons = sdl2.SDL_JoystickNumButtons(pad) self.app.log('Gamepad found: %s with %s axes, %s buttons' % (pad_name, pad_axes, pad_buttons)) self.gamepad = pad # before main loop begins, set initial mouse position - # SDL_GetMouseState returns 0,0 if the mouse hasn't yet moved # in the new window! wx, wy = ctypes.c_int(0), ctypes.c_int(0) sdl2.SDL_GetWindowPosition(self.app.window, wx, wy) wx, wy = int(wx.value), int(wy.value) mx, my = ctypes.c_int(0), ctypes.c_int(0) sdl2.mouse.SDL_GetGlobalMouseState(mx, my) mx, my = int(mx.value), int(my.value) self.app.mouse_x, self.app.mouse_y = mx - wx, my - wy # set flag so we know whether handle_input's SDL_GetMouseState result # is accurate :/ self.mouse_has_moved = False
for i in range(sdl2.SDL_NumJoysticks()): joy = sdl2.SDL_JoystickOpen(i) if joy is None: print("Joystick device at {} is invalid.".format(i)) else: name_object = sdl2.SDL_JoystickName(joy) if name_object is None: name = "Unknown device" print("Encountered an invalid device name") else: name = name_object.decode("utf-8") hardware_id = struct.unpack(">4I", sdl2.SDL_JoystickGetGUID(joy))[0] windows_id = sdl2.SDL_JoystickInstanceID(joy) hardware_id = struct.unpack(">4I", sdl2.SDL_JoystickGetGUID(joy))[0] windows_id = sdl2.SDL_JoystickInstanceID(joy) axes = sdl2.SDL_JoystickNumAxes(joy) buttons = sdl2.SDL_JoystickNumButtons(joy) hats = sdl2.SDL_JoystickNumHats(joy) joystick = { "Name": name, "Res Name": None, "SCXML ID": None, "JGXML ID": None, "JGPYCON ID": None, "HW ID": hardware_id, "Win ID": windows_id, "Axes": axes, "Buttons": buttons, "Hats": hats, "Obj": joy,
def axis_count(self): """Returns the number of axis of the joystick. :return number of axes """ return sdl2.SDL_JoystickNumAxes(self._joystick)
print ' left trigger2:',pro['lt2'],'\t\t','right trigger2:',pro['rt2'] print '---' print ' Y:',pro['Y'] print ' X:',pro['X'] print ' A:',pro['A'] print ' B:',pro['B'] print '---' print ' hat:',pro['hat'] # init stuff sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) js = sdl2.SDL_JoystickOpen(0) # grab info a = sdl2.SDL_JoystickNumAxes(js) b = sdl2.SDL_JoystickNumButtons(js) h = sdl2.SDL_JoystickNumHats(js) print 'axes:',a,'buttons:',b,'hats:',h # exit() # Data structure holding the PRO info pro = { 'la': {'x': 0, 'y': 0}, # left axis 'ra': {'x': 0, 'y': 0}, 'lt1': 0, # left trigger 1 'rt1': 0, 'lt2': 0, # left trigger 2 'rt2': 0, 'A': 0, 'X': 0, 'Y': 0,
def __init__( self, input_device_index=0, input_device_name=None, scope_server_host='127.0.0.1', zmq_context=None, maximum_portion_of_wallclock_time_allowed_for_axis_commands=DEFAULT_MAX_AXIS_COMMAND_WALLCLOCK_TIME_PORTION, maximum_axis_command_cool_off=DEFAULT_MAX_AXIS_COMMAND_COOL_OFF, warnings_enabled=False): """* input_device_index: The argument passed to SDL_JoystickOpen(index) or SDL_GameControllerOpen(index). Ignored if the value of input_device_name is not None. * input_device_name: If specified, input_device_name should be the exact string or UTF8-encoded bytearray by which SDL identifies the controller you wish to use, as reported by SDL_JoystickName(..). For USB devices, this is USB iManufacturer + ' ' + iProduct. (See example below.) * scope_server_host: IP address or hostname of scope server. * zmq_context: If None, one is created. * maximum_portion_of_wallclock_time_allowed_for_axis_commands: Limit the rate at which commands are sent to the scope in response to controller axis motion such that the scope such that the scope is busy processing those commands no more than this fraction of the time. * maximum_axis_command_cool_off: The maximum number of milliseconds to defer issuance of scope commands in response to controller axis motion (in order to enforce maximum_portion_of_wallclock_time_allowed_for_axis_commands). For example, a Sony PS4 controller with the following lsusb -v output would be known to SDL as 'Sony Computer Entertainment Wireless Controller': Bus 003 Device 041: ID 054c:05c4 Sony Corp. Device Descriptor: bLength 18 bDescriptorType 1 bcdUSB 2.00 bDeviceClass 0 bDeviceSubClass 0 bDeviceProtocol 0 bMaxPacketSize0 64 idVendor 0x054c Sony Corp. idProduct 0x05c4 bcdDevice 1.00 iManufacturer 1 Sony Computer Entertainment iProduct 2 Wireless Controller iSerial 0 bNumConfigurations 1 ... Additionally, sdl_control.enumerate_devices(), a module function, returns a list of the currently available SDL joystick and game controller input devices, in the order by which SDL knows them. So, if you know that your input device is a Logilech something-or-other, and sdl_control.enumerate_devices() returns the following: [ 'Nintenbo Olympic Sport Mat v3.5', 'MANUFACTURER NAME HERE. DONT FORGET TO SET THIS!! Many Product Ltd. 1132 Guangzhou $ !*llSN9_Q ', 'Duckhunt Defender Scanline-Detecting Plastic Gun That Sadly Does Not Work With LCDs', 'Macrosoft ZBox-720 Controller Colossal-Hands Mondo Edition', 'Logilech SixThousandAxis KiloButtonPad With Haptic Feedback Explosion', 'Gametech Gameseries MegaGamer Excel Spreadsheet 3D-Orb For Executives, Doom3D Edition', 'Gametech Gameseries MegaGamer Excel Spreadsheet 3D-Orb For Light Rail Transport, Doom3D Edition' ] You will therefore want to specify input_device_index=4 or input_device_name='Logilech SixThousandAxis KiloButtonPad With Haptic Feedback Explosion' """ assert 0 < maximum_portion_of_wallclock_time_allowed_for_axis_commands <= 1 init_sdl() self.device, self.device_is_game_controller = open_device( input_device_index, input_device_name) if self.device_is_game_controller: self.jdevice = sdl2.SDL_GameControllerGetJoystick(self.device) else: self.jdevice = self.device self.device_id = sdl2.SDL_JoystickInstanceID(self.jdevice) self.num_axes = sdl2.SDL_JoystickNumAxes(self.jdevice) self.num_buttons = sdl2.SDL_JoystickNumButtons(self.jdevice) self.num_hats = sdl2.SDL_JoystickNumHats(self.jdevice) self.warnings_enabled = warnings_enabled if warnings_enabled: print('JoypadInput is connecting to scope server...', file=sys.stderr) self.scope, self.scope_properties = scope_client.client_main( scope_server_host, zmq_context) if warnings_enabled: print('JoypadInput successfully connected to scope server.', file=sys.stderr) self.event_loop_is_running = False self.quit_event_posted = False self.throttle_delay_command_time_ratio = 1 - maximum_portion_of_wallclock_time_allowed_for_axis_commands self.throttle_delay_command_time_ratio /= maximum_portion_of_wallclock_time_allowed_for_axis_commands self.maximum_axis_command_cool_off = maximum_axis_command_cool_off self._axes_throttle_delay_lock = threading.Lock() self._c_on_axes_throttle_delay_expired_timer_callback = SDL_TIMER_CALLBACK_TYPE( self._on_axes_throttle_delay_expired_timer_callback) self.handle_button_callback = self.default_handle_button_callback
except: import pickle # ______ Constants & configuration ______ # # initialise joysticking error = sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) numsticks = sdl2.SDL_NumJoysticks() print("{} Sticks found".format(numsticks+1)) for stick in range(numsticks): name = sdl2.SDL_JoystickNameForIndex(stick) print("Name of stick {} is {}".format(stick, name)) if name == b"PLAYSTATION(R)3 Controller": gamepad_obj = sdl2.SDL_JoystickOpen(stick) if sdl2.SDL_JoystickNumAxes(gamepad_obj) == 4: # Let's do a test read sdl2.SDL_PumpEvents() result = sdl2.SDL_JoystickGetAxis(gamepad_obj, 0) if result < -30000: print("Stick {} disconnected".format(stick)) else: print("Selected stick {}".format(stick)) break # Gamepad config gamepad = SIXAXIS.copy() # Copy dict from settings gamepad['gp_object'] = gamepad_obj # Robot configuration, bind sticks and buttons to motors robot_config = {
def __new__(cls, identifier=None, instance_id=None, *args, **kwargs): # Check init if not get_init(): init() # Create the object joy = super().__new__(cls) if instance_id is not None: # Create the underlying joystick from the instance id. # SDL_JOYDEVICEREMOVED and all other SDL_JOY#### events give the instance id joy.joystick = sdl2.SDL_JoystickFromInstanceID(instance_id) # print('Instance ID:', raw_joystick, SDL_JoystickGetAttached(raw_joystick)) else: # Create the underlying joystick from the enumerated identifier # SDL_JOYDEVICEADDED and SDL_NumJoysticks use open if identifier is None: identifier = 0 if isinstance(identifier, str): # Get the joystick from the name or None if not found! for i in range(sdl2.SDL_NumJoysticks()): raw_joystick = sdl2.SDL_JoystickOpen(i) try: if sdl2.SDL_JoystickName(raw_joystick).decode( 'utf-8') == identifier: joy.joystick = raw_joystick break except: pass else: joy.joystick = sdl2.SDL_JoystickOpen(identifier) # print('ID:', raw_joystick, SDL_JoystickGetAttached(raw_joystick)) try: joy.identifier = sdl2.SDL_JoystickID( sdl2.SDL_JoystickInstanceID(joy.joystick)).value # joy.identifier = SDL_JoystickInstanceID(raw_joystick) joy.name = sdl2.SDL_JoystickName(joy.joystick).decode('utf-8') joy.numaxes = sdl2.SDL_JoystickNumAxes(joy.joystick) joy.numbuttons = sdl2.SDL_JoystickNumButtons(joy.joystick) joy.numhats = sdl2.SDL_JoystickNumHats(joy.joystick) joy.numballs = sdl2.SDL_JoystickNumBalls(joy.joystick) joy.init_keys() except: pass # Try to get the gamepad object try: joy.gamecontroller = sdl2.SDL_GameControllerOpen(joy.identifier) # FromInstanceId does not Attach! # joy.gamecontroller = SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(joy.joystick) # print('ID:', SDL_GameControllerGetAttached(joy.gamecontroller)) except: joy.gamecontroller = None try: joy.guid = get_guid( joy.joystick ) # Using this is more reliable for the GameController stuff except: pass return joy