Beispiel #1
0
def open_device(device):
    """Device should either be the index of a valid SDL device or its joystick name. The list of
    attached devices and names can be retrieved with enumerate_devices()."""
    if not SDL_INITED:
        raise RuntimeError('SDL not initialized. Call init_sdl() from the the thread that will run the event loop.')
    input_device_count = sdl2.SDL_NumJoysticks()
    if input_device_count == 0:
        raise RuntimeError('No joysticks/game controllers attached.')
    if isinstance(device, int):
        if not 0 <= device < input_device_count:
            raise ValueError('Invalid device index {}; there are only {} available devices.'.format(device, input_device_count))
        index = device
        name = sdl2.SDL_JoystickNameForIndex(index).decode('utf-8')
    else:
        name = device
        namebytes = device.encode('utf-8')
        for index in range(sdl2.SDL_NumJoysticks()):
            if sdl2.SDL_JoystickNameForIndex(index) == namebytes:
                break
        else:
            raise ValueError('No device recognized by SDL has the name "{}".'.format(name))
    is_game_controller = bool(sdl2.SDL_IsGameController(index))
    device = (sdl2.SDL_GameControllerOpen if is_game_controller else sdl2.SDL_JoystickOpen)(index)
    if not device:
        raise RuntimeError('Failed to open {} at device index {} with name "{}".'.format(
            'game controller' if is_game_controller else 'joystick', index, name))
    return device, name, index, is_game_controller
Beispiel #2
0
def open_device(input_device_index=0,
                input_device_name=None,
                _used_idx_and_name=None):
    if input_device_name is None and int(
            input_device_index) != input_device_index:
        raise ValueError(
            'If input_device_name is not specified, the value supplied for input_device_index must be an integer.'
        )
    input_device_count = sdl2.SDL_NumJoysticks()
    if input_device_count == 0:
        raise RuntimeError(
            'According to SDL, there are no joysticks/game controllers attached.'
        )
    if input_device_name is None:
        if not 0 <= input_device_index < input_device_count:
            isare, ssuffix = ('is', '') if input_device_count == 1 else ('are',
                                                                         's')
            e = (
                'According to SDL, there {0} {1} joystick{2}/game controller{2} attached.  Therefore, input_device_index must be '
                'an integer in the closed interval [0, {3}], which the supplied value, {4}, is not.'
            )
            raise ValueError(
                e.format(isare, input_device_count, ssuffix,
                         input_device_count - 1, input_device_index))
        input_device_name = sdl2.SDL_JoystickNameForIndex(input_device_index)
    else:
        if isinstance(input_device_name, str):
            input_device_name = input_device_name.encode('utf-8')
        else:
            input_device_name = bytes(input_device_name)
        for sdl_dev_idx in range(sdl2.SDL_NumJoysticks()):
            if sdl2.SDL_JoystickNameForIndex(sdl_dev_idx) == input_device_name:
                input_device_index = sdl_dev_idx
                break
        else:
            raise ValueError(
                'No connected joystick or game controller device recognized by SDL has the name "{}".'
                .format(input_device_name.decode('utf-8')))
    device_is_game_controller = bool(
        sdl2.SDL_IsGameController(input_device_index))
    device = (sdl2.SDL_GameControllerOpen if device_is_game_controller else
              sdl2.SDL_JoystickOpen)(input_device_index)
    if not device:
        raise RuntimeError(
            'Failed to open {} at device index {} with name "{}".'.format(
                'game controller' if device_is_game_controller else 'joystick',
                input_device_index, input_device_name.decode('utf-8')))
    if _used_idx_and_name is not None:
        _used_idx_and_name[0] = input_device_index
        _used_idx_and_name[1] = input_device_name
    return device, device_is_game_controller
Beispiel #3
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
Beispiel #4
0
def enumerate_devices():
    with contextlib.ExitStack() as estack:
        # We may be called from a different thread than the one that will run the SDL event loop.  In case that
        # will happen, if SDL is not already initialized, we do not leave it initialized (if we did, it would be
        # bound to our current thread, which may not be desired).
        if not SDL_INITED:
            if sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK
                             | sdl2.SDL_INIT_GAMECONTROLLER) < 0:
                sdl_e = sdl2.SDL_GetError()
                sdl_e = sdl_e.decode('utf-8') if sdl_e else 'UNKNOWN ERROR'
                sdl2.SDL_Quit()
                raise RuntimeError(
                    'Failed to initialize SDL ("{}").'.format(sdl_e))
            estack.callback(lambda: sdl2.SDL_QuitSubSystem(
                sdl2.SDL_INIT_JOYSTICK | sdl2.SDL_INIT_GAMECONTROLLER))
            estack.callback(sdl2.SDL_Quit)
        rows = []
        for sdl_dev_idx in range(sdl2.SDL_NumJoysticks()):
            device_is_game_controller = bool(
                sdl2.SDL_IsGameController(sdl_dev_idx))
            device_type = 'game controller' if device_is_game_controller else 'joystick'
            cols = [
                sdl_dev_idx, device_type,
                sdl2.SDL_JoystickNameForIndex(sdl_dev_idx).decode('utf-8')
            ]
            if device_is_game_controller:
                cols.append(
                    sdl2.SDL_GameControllerNameForIndex(sdl_dev_idx).decode(
                        'utf-8'))
            rows.append(cols)
    return rows
Beispiel #5
0
def enumerate_controllers():
    print('Controllers connected to this system:')
    for n in range(sdl2.SDL_NumJoysticks()):
        name = sdl2.SDL_JoystickNameForIndex(n)
        if name is not None:
            name = name.decode('utf8')
        print(n, ':', name)
    print('Note: These are numbered by connection order. Numbers will change if you unplug a controller.')
    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()
Beispiel #7
0
 def list_joysticks(self):
     # Read Number of joysticks and
     # print the name and index to console
     number_of_sticks = sdl2.SDL_NumJoysticks()
     if number_of_sticks > 0:
         for i in range(number_of_sticks):
             print("Joystick %d : %s" %
                   (i + 1, sdl2.SDL_JoystickNameForIndex(i)))
     else:
         print("No Joysticks connected")
Beispiel #8
0
def get_controller(c):
    try:
        n = int(c, 10)
        return sdl2.SDL_GameControllerOpen(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 == c:
                    return sdl2.SDL_GameControllerOpen(n)
        raise Exception('Controller not found: %s'.format(c))
Beispiel #9
0
def main():
    parser = argparse.ArgumentParser(description=SHORT_DESCRIPTION)
    parser.add_argument('server', help='Server address')
    parser.add_argument('port',
                        help='Server port',
                        type=int,
                        default=2010,
                        nargs='?')
    parser.add_argument('ship',
                        help='Selected ship',
                        type=int,
                        default=0,
                        nargs='?')
    parser.add_argument('--enable-pitch',
                        help='Turn on pitch control',
                        action='store_true')
    parser.add_argument('--enable-warp',
                        help='Turn on warp lever',
                        action='store_true')
    args = parser.parse_args()

    SDL.SDL_Init(SDL.SDL_INIT_JOYSTICK)
    for joy in range(SDL.SDL_NumJoysticks()):
        name = SDL.SDL_JoystickNameForIndex(joy)
        if name == b'CH FLIGHT SIM YOKE USB':
            joystick = Joystick(SDL.SDL_JoystickOpen(joy))
            break
    else:
        print('Could not find yoke.')
        exit(1)

    tx, rx = connect(args.server, args.port)
    track = Tracker()

    def handle_input():
        for packet in rx:
            if isinstance(packet, diana.packet.WelcomePacket):
                print("Connected.")
                tx(diana.packet.SetShipPacket(args.ship))
                tx(
                    diana.packet.SetConsolePacket(diana.packet.Console.data,
                                                  True))
                tx(diana.packet.ReadyPacket())
            track.rx(packet)

    launch_thread(handle_input)

    while True:
        process_frame(joystick, tx, lambda: track.player_ship, args)
Beispiel #10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--list-controllers', action='store_true', help='Display a list of controllers attached to the system.')
    parser.add_argument('-c', '--controller', type=str, default='0', help='Controller to use. Default: 0.')
    parser.add_argument('-m', '--macro-controller', metavar='CONTROLLER:RECORD_BUTTON:PLAY_BUTTON', type=str, default=None, help='Controller and buttons to use for macro control. Default: None.')
    parser.add_argument('-p', '--port', type=str, default='/dev/ttyUSB0', help='Serial port or "functionfs" for direct USB mode. Default: /dev/ttyUSB0.')
    parser.add_argument('-b', '--baud-rate', type=int, default=115200, help='Baud rate. Default: 115200.')
    parser.add_argument('-u', '--udc', type=str, default='dummy_udc.0', help='UDC for direct USB mode. Default: dummy_udc.0 (loopback mode).')
    parser.add_argument('-R', '--record', type=str, default=None, help='Record events to file.')
    parser.add_argument('-P', '--playback', type=str, default=None, help='Play back events from file.')
    parser.add_argument('-d', '--dontexit', action='store_true', help='Switch to live input when playback finishes, instead of exiting. Default: False.')
    parser.add_argument('-q', '--quiet', action='store_true', help='Disable speed meter. Default: False.')
    parser.add_argument('-M', '--macros-dir', type=str, default='.', help='Directory to save macros. Default: current directory.')
    parser.add_argument('-f', '--function', type=str, nargs='*', default=[], help='Map a macro function to a button.')
    parser.add_argument('-D', '--log-level', type=str, default='INFO', help='Debugging level. CRITICAL, ERROR, WARNING, INFO, DEBUG. Default=INFO')

    args = parser.parse_args()

    numeric_level = getattr(logging, args.log_level.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % args.log_level)
    root_logger.setLevel(numeric_level)

    if args.list_controllers:
        Controller.enumerate()
        exit(0)

    states = []

    if args.playback is None or args.dontexit:
        if args.controller == 'fake':
            states = fakeinput()
        else:
            states = Controller(args.controller)
    if args.playback is not None:
        states = itertools.chain(replay_states(args.playback), states)

    macro_controller = None
    macro_record = None
    macro_play = None

    if args.macro_controller is not None:
        try:
            macro_controller, macro_record, macro_play = args.macro_controller.rsplit(':', maxsplit=3)
            macro_record = int(macro_record, 10)
            macro_play = int(macro_play, 10)
        except ValueError:
            logger.critical('Macro controller must be <controller number or name>:<record button>:<play button>')
            exit(-1)

        try:
            n = int(macro_controller, 10)
            if n < sdl2.SDL_NumJoysticks():
                sdl2.SDL_JoystickOpen(n)
                macro_controller = 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 == macro_controller:
                        sdl2.SDL_JoystickOpen(n)
                        macro_controller = n

    window = None
    try:
        window = Window()
    except sdl2.ext.common.SDLError:
        logger.warning('Could not create a window with SDL. Keyboard input will not be available.')
        pass

    function_macros = {}
    for arg in args.function:
        try:
            b,f = arg.split(':')
            function_macros[int(b, 10)] = macros_dict[f]
        except ValueError:
            logger.error('Invalid function macro ignored.')
        except KeyError:
            logger.error('Invalid function macro ignored.')

    with MacroManager(states, macros_dir=args.macros_dir, record_button=macro_record, play_button=macro_play, function_macros=function_macros) as mm:
        with Recorder(args.record) as record:
            with HAL(args.port, args.baud_rate, args.udc) as hal:
                with tqdm(unit=' updates', disable=args.quiet, dynamic_ncols=True) as pbar:

                    try:

                        while True:

                            for event in sdl2.ext.get_events():
                                # we have to fetch the events from SDL in order for the controller
                                # state to be updated.
                                if event.type == sdl2.SDL_WINDOWEVENT:
                                    if event.window.event == sdl2.SDL_WINDOWEVENT_CLOSE:
                                        raise WindowClosed
                                else:
                                    if event.type == sdl2.SDL_KEYDOWN and event.key.repeat == 0:
                                        logger.debug('Key down: {:s}'.format(sdl2.SDL_GetKeyName(event.key.keysym.sym).decode('utf8')))
                                        mm.key_event(event.key.keysym.sym, True)
                                    elif event.type == sdl2.SDL_KEYUP:
                                        logger.debug('Key up: {:s}'.format(sdl2.SDL_GetKeyName(event.key.keysym.sym).decode('utf8')))
                                        mm.key_event(event.key.keysym.sym, False)
                                    elif event.jdevice.which == macro_controller:
                                        if event.type == sdl2.SDL_JOYBUTTONDOWN:
                                            logger.debug('Macro controller button down: {:d}'.format(event.jbutton.button))
                                            mm.button_event(event.jbutton.button, True)
                                        elif event.type == sdl2.SDL_JOYBUTTONUP:
                                            mm.button_event(event.jbutton.button, False)

                            # wait for the arduino to request another state.
                            if hal.poll():
                                state = next(mm)
                                hal.write(state)
                                record.write(state)
                                pbar.set_description('Sent {:s}'.format(state.hexstr))
                                pbar.update()
                                if window is not None:
                                    window.update(state)

                    except StopIteration:
                        logger.info('Exiting because replay finished.')
                    except KeyboardInterrupt:
                        logger.info('Exiting due to keyboard interrupt.')
                    except WindowClosed:
                        logger.info('Exiting because input window was closed.')
Beispiel #11
0
 def on_joydeviceaddedevent(event):
     return 'idx: {} j_name: {}'.format(event.jdevice.which, sdl2.SDL_JoystickNameForIndex(event.jdevice.which).decode('utf-8'))
    SIXAXIS

try:
    import cPickle as pickle
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