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 controller_states(controller_id): sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER) controller = get_controller(controller_id) try: print('Using "{:s}" for input.'.format( sdl2.SDL_JoystickName(sdl2.SDL_GameControllerGetJoystick(controller)).decode('utf8'))) except AttributeError: print('Using controller {:s} for input.'.format(controller_id)) while True: elaped_time = dt.datetime.now().timestamp() - start_dttm buttons = sum([sdl2.SDL_GameControllerGetButton(controller, b) << n for n, b in enumerate(buttonmapping)]) buttons |= (abs(sdl2.SDL_GameControllerGetAxis(controller, sdl2.SDL_CONTROLLER_AXIS_TRIGGERLEFT)) > trigger_deadzone) << 6 buttons |= (abs(sdl2.SDL_GameControllerGetAxis(controller, sdl2.SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) > trigger_deadzone) << 7 hat = hatcodes[sum([sdl2.SDL_GameControllerGetButton(controller, b) << n for n, b in enumerate(hatmapping)])] rawaxis = [sdl2.SDL_GameControllerGetAxis(controller, n) for n in axismapping] axis = [((0 if abs(x) < axis_deadzone else x) >> 8) + 128 for x in rawaxis] rawbytes = struct.pack('>BHBBBB', hat, buttons, *axis) message_stamp = ControllerStateTime(rawbytes, elaped_time) yield message_stamp
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, controller_id, axis_deadzone=10000, trigger_deadzone=0): # Make sure we get joystick events even if in window mode and not focused. sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1") sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER) # Mapping for X-box S Controller sdl2.SDL_GameControllerAddMapping( b"030000005e0400008902000021010000,Classic XBOX Controller," b"a:b0,b:b1,y:b4,x:b3,start:b7,guide:,back:b6,leftstick:b8," b"rightstick:b9,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2," b"leftx:a0,lefty:a1,rightx:a3,righty:a4,lefttrigger:a2," b"righttrigger:a5,leftshoulder:b5,rightshoulder:b2,") # Mapping for 8bitdo sdl2.SDL_GameControllerAddMapping( b"05000000c82d00002038000000010000,8Bitdo NES30 Pro," b"a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8," b"dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6," b"leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1," b"rightshoulder:b7,rightstick:b14,righttrigger:a4," b"rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,") self.controller = None self.name = 'controller {:s}'.format(controller_id) self.which = None try: n = int(controller_id, 10) if n < sdl2.SDL_NumJoysticks(): self.controller = sdl2.SDL_GameControllerOpen(n) self.which = n except ValueError: for n in range(sdl2.SDL_NumJoysticks()): name = sdl2.SDL_JoystickNameForIndex(n) if name is not None: name = name.decode('utf8') if name == controller_id: self.controller = sdl2.SDL_GameControllerOpen(n) self.which = n if self.controller is None: raise Exception('Controller not found: {:s}'.format(controller_id)) try: self.name = sdl2.SDL_JoystickName( sdl2.SDL_GameControllerGetJoystick( self.controller)).decode('utf8') except AttributeError: pass logger.info('Using {:s} for input.'.format(self.name)) self.axis_deadzone = axis_deadzone self.trigger_deadzone = trigger_deadzone self.previous_state = State()
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 __init__(self, joystick_index): self.game_controller = None self.joystick = None self.joystick_id = None if sdl2.SDL_IsGameController(joystick_index): self.game_controller = sdl2.SDL_GameControllerOpen(joystick_index) self.joystick = sdl2.SDL_GameControllerGetJoystick( self.game_controller) self.joystick_id = sdl2.SDL_JoystickInstanceID(self.joystick) self.name = sdl2.SDL_GameControllerName(self.game_controller) else: self.joystick = sdl2.SDL_JoystickOpen(joystick_index) self.joystick_id = sdl2.SDL_JoystickInstanceID(self.joystick) self.name = sdl2.SDL_JoystickName(self.joystick)
def __init__(self, controller_id: int, **kwargs): self.ser = serial.Serial(**kwargs) sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER) self.controller = sdl2.SDL_GameControllerOpen(int(controller_id)) try: print('Using "{:s}" for input.'.format( sdl2.SDL_JoystickName( sdl2.SDL_GameControllerGetJoystick( self.controller)).decode('utf8'))) except AttributeError: print(f'Using controller {controller_id} for input.') self.input_stack = [] self.recording = None self.start_dttm = None self.prev_msg_stamp = None
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 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__(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
import sdl2 # sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) count = sdl2.joystick.SDL_NumJoysticks() print('num juysticks: ', count) # for i in range(count): joystic = sdl2.SDL_JoystickOpen(i) name = sdl2.SDL_JoystickName(joystic) print('{}: {}'.format(i, name)) sdl2.SDL_JoystickClose(joystic) # joystick = sdl2.SDL_JoystickOpen(0) name = sdl2.SDL_JoystickName(joystick) print(name) num_axes = sdl2.SDL_JoystickNumAxes(joystick) print('num axes; ', num_axes) num_buttons = sdl2.SDL_JoystickNumButtons(joystick) print('num buttons: ', num_buttons) num_hats = sdl2.SDL_JoystickNumHats(joystick) print('num hats: ', num_hats) num_balls = sdl2.SDL_JoystickNumBalls(joystick) print('num balls: ', num_balls)
fileinput.close() if sdl2.SDL_NumJoysticks() < 1: print " OOPS: Can't find any joysticks." print " - Check they are connected." print " - Check they are listed in the \"USB Game Controllers\" utility." raw_input("\n Press Enter to Quit.") sys.exit(1) 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,
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
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
def poll_sdl_events(self): import ctypes as c sdl.SDL_JoystickEventState(sdl.SDL_ENABLE) self.num_gamepads = sdl.SDL_NumJoysticks() self.active_gamepads = {} while self.pending: event = sdl.SDL_Event() while sdl.SDL_PollEvent(c.byref(event)): if event.type == sdl.SDL_JOYBUTTONDOWN: button = event.jbutton self.gamepad_input = button.which self.gamepad_pressed = button.button self.gamepad_type = "button" elif event.type == sdl.SDL_JOYAXISMOTION: axis = event.jaxis if event.jaxis.value < -16000: self.gamepad_input = axis.which self.gamepad_pressed = axis.axis self.gamepad_type = "Naxis" elif event.jaxis.value > 16000: self.gamepad_input = axis.which self.gamepad_pressed = axis.axis self.gamepad_type = "Paxis" elif event.type == sdl.SDL_JOYDEVICEADDED: n = event.jdevice.which device = sdl.SDL_JoystickOpen(n) joy_id = sdl.SDL_JoystickInstanceID(device) self.active_gamepads[joy_id] = device name = sdl.SDL_JoystickName(device).decode("utf-8") page = 1 while page < 5: self.pages_list[page][1].insert( n, str(n), str(n) + ": " + name) if self.gamepads_stored[page][1] == name: self.pages_list[page][1].set_active_id( str(self.gamepads_stored[page][0])) page += 1 log.info(f"Controller added: {name}") log.info( f"Current active controllers: {sdl.SDL_NumJoysticks()}" ) elif event.type == sdl.SDL_JOYDEVICEREMOVED: joy_id = event.jdevice.which device = self.active_gamepads[joy_id] if sdl.SDL_JoystickGetAttached(device): sdl.SDL_JoystickClose(device) name = sdl.SDL_JoystickName(device).decode("utf-8") page = 1 while page < 5: if self.gamepads_stored[page][1] == name: self.pages_list[page][1].set_active_id("-1") self.pages_list[page][1].remove( self.gamepads_stored[page][0]) page += 1 log.info(f"Controller removed: {name}") self.active_gamepads.pop(joy_id) log.info( f"Current active controllers: {sdl.SDL_NumJoysticks()}" )
def getJoystickName(self): return sdl2.SDL_JoystickName(self.joystick)
def on_bind_key(self, widget, param, section, name, double): controller = None if self.parent.m64p_wrapper.ConfigGetParameter('name') == "Keyboard": device = "keyboard" else: device = "gamepad" stored_name = self.parent.m64p_wrapper.ConfigGetParameter('name') for joy_id, instance in self.active_gamepads.items(): this_name = sdl.SDL_JoystickName(instance).decode("utf-8") if this_name == stored_name: controller = self.active_gamepads[joy_id] # Now we start preparations for the dialog if double == True: # In case we have to bind twice in a single GUI button, e.g. for an axis of the controller if name == "X Axis": first_name = "X Axis (Left)" second_name = "X Axis (Right)" elif name == "Y Axis": first_name = "Y Axis (Up)" second_name = "Y Axis (Down)" first_value = self.binding(widget, param, device, first_name, controller, False) if first_value[1] != None: if first_value[0] != "" and first_value[1] != "empty": if first_value[1] == "Naxis" or first_value[1] == "Paxis": input_type = "axis" else: input_type = first_value[1] different = True while different: # We give some time to the user to reset the control stick to zero. time.sleep(0.2) second_value = self.binding(widget, param, device, second_name, controller, False) if second_value[1] == "Naxis" or second_value[ 1] == "Paxis": input_type2 = "axis" elif second_value[1] == None or second_value[ 1] == "empty": break else: input_type2 = second_value[1] if input_type == input_type2: different = False if second_value[1] != None: if second_value[0] != "" and second_value[1] != "empty": if input_type == "axis": store = input_type + "(" + first_value[0] + ("+" if first_value[1] == "Paxis" else "-") + "," + second_value[0] + \ ("+" if second_value[1] == "Paxis" else "-") + ")" widget.set_label(store) self.parent.m64p_wrapper.ConfigSetParameter( param, store) elif input_type == "button": store = input_type + "(" + first_value[ 0] + "," + second_value[0] + ")" widget.set_label(store) self.parent.m64p_wrapper.ConfigSetParameter( param, store) elif input_type == "key": widget.set_label( "(" + sdl.SDL_GetKeyName( int(first_value[0])).decode("utf-8") + ", " + sdl.SDL_GetKeyName( int(second_value[0])).decode("utf-8") + ")") else: widget.set_label("(empty)") self.parent.m64p_wrapper.ConfigSetParameter( param, second_value[0]) else: widget.set_label("(empty)") self.parent.m64p_wrapper.ConfigSetParameter( param, first_value[0]) else: self.binding(widget, param, device, name, controller, True)