예제 #1
0
    def open(self):
        self._j = sdl2.SDL_JoystickOpen(self._index)
        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(btn_count + 4))
예제 #2
0
    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
예제 #3
0
    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()}"
                    )
예제 #4
0
import sdl2

last_pos1 = 0
last_pos2 = 0

sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
joystick = sdl2.SDL_JoystickOpen(0)

print(joystick)

while True:
    sdl2.SDL_PumpEvents()
    pos1 = sdl2.SDL_JoystickGetAxis(joystick, 1)
    pos2 = sdl2.SDL_JoystickGetAxis(joystick, 3)
    if (pos1 != last_pos1 or pos2 != last_pos2):
        print(str(pos1) + ',' + str(pos2))
        last_pos1, last_pos2 = pos1, pos2
예제 #5
0
 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
예제 #6
0
import sdl2

sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
joystick = sdl2.SDL_JoystickOpen(0)
joystick2 = sdl2.SDL_JoystickOpen(1)
player = {
    'gamepad': joystick2,
    'stick_range': 65536,  # max stick position - min stick position
    'stick_center': 0,
    'left_shoulder_btn': 8,
    'right_shoulder_btn': 9
}

while True:
    sdl2.SDL_PumpEvents()
    btns = {}
    for i in range(15):
        btns[i] = sdl2.SDL_JoystickGetButton(joystick2, i)

    joy_x = (sdl2.SDL_JoystickGetAxis(player['gamepad'], 0) -
             player['stick_center']) * 200 / player['stick_range']
    print(joy_x, (sdl2.SDL_JoystickGetAxis(joystick2, 0) - 0) * 200 / 65000,
          sdl2.SDL_JoystickGetAxis(joystick2, 1), btns)
    if sdl2.SDL_JoystickGetButton(player['gamepad'],
                                  player['left_shoulder_btn']):
        break
예제 #7
0
from jaraco.nxt import *
from jaraco.nxt.messages import *

import time
import sdl2
import math

# initialise joysticking
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)

# create configs
AntoBot = {
    'tty': '/dev/tty.NXT-DevB',
    'gamepad_num': 0,
    'gamepad': sdl2.SDL_JoystickOpen(0),
    'stick_range': 32768,  # max stick position - min stick position
    'stick_center': 17268,
    'left_shoulder_btn': 4,
    'right_shoulder_btn': 5,
    'invert_y': 1,
    'abort_btn': 3
}

AddyBot = {
    'tty': '/dev/tty.Addy-DevB',
    'gamepad_num': 1,
    'gamepad': sdl2.SDL_JoystickOpen(1),  # sixaxis
    'stick_range': 65536,  # max stick position - min stick position
    'stick_center': 0,
    'left_shoulder_btn': 8,
    def recordButtonClick(self):
        self.isRecording = not self.isRecording
        if (self.isRecording):
            self.recordTimeStarted = time.time()
            self.recordNTimesRecorded += 1
            self.recordSampleNumber = 1
            self.recordData = []
            if not os.path.exists(self.recordEntryText.get()):
                os.makedirs(self.recordEntryText.get())
            self.recordDirectory = self.recordEntryText.get() + '/' + str(
                self.recordNTimesRecorded)
            if not os.path.exists(self.recordDirectory):
                os.makedirs(self.recordDirectory)
            self.recordButtonText.set("Stop Recording")
        else:
            if (len(self.recordData) > 0):
                with open(
                        self.recordDirectory + '/' +
                        str(self.recordSampleNumber), 'wb') as self.handle:
                    pickle.dump(self.recordData, self.handle)
            self.recordButtonText.set("Start Recording")


if (__name__ == '__main__'):
    sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
    globalJoystick = sdl2.SDL_JoystickOpen(0)
    globalJoystickInput = JoystickInput_SDL(globalJoystick)
    app = App()
    app.root.mainloop()
    sdl2.SDL_Quit()
예제 #9
0
    def update(self, event):
        if event.type == sdl2.SDL_JOYDEVICEADDED:
            self.device = sdl2.SDL_JoystickOpen(event.jdevice.which)
            return ('info', 'The joystick is connected')
        elif event.type == sdl2.SDL_JOYDEVICEREMOVED:
            self.device = None
            return ('info', 'The joystick is removed')
        elif event.type == sdl2.SDL_JOYAXISMOTION:
            # print(self.axis_map[event.jaxis.axis], event.jaxis.value)
            # ignore left up button
            self.axis[self.axis_map[
                event.jaxis.axis]] = event.jaxis.value / AXISMAXVALUE
            # move the platform
            button_and_type = self.axis_map[event.jaxis.axis]
            con = None
            if button_and_type[0] == 'R':
                if self.con_right is not None:
                    con = self.con_right
            else:
                if self.con_left is not None:
                    con = self.con_left
            if con is not None:
                if button_and_type[-1] == 'H':
                    action = 'move_to_x'  
                elif button_and_type[-1] == 'V':
                    action = 'move_to_y'
                else:
                    if event.jaxis.value > 0:
                        con.spindle_up()
                    else:
                        con.spindle_down()
                    return 
                value = event.jaxis.value / AXISMAXVALUE * PLATFORM_LIMIT
                getattr(con, action)(value)
            else:
                return ('info', 'The servo platforms are not connected.')

        elif event.type == sdl2.SDL_JOYBUTTONDOWN:
            # print("Button down:", event.jbutton.button)
            self.button[self.button_map[event.jbutton.button]] = True
            btn = self.button_map[event.jbutton.button]
            if btn == 'A':
                self.current_con = self.con_left
            elif btn == 'B':
                self.current_con = self.con_right
            elif btn == 'X':
                if self.current_con is not None:
                    self.current_con.go_home()
                else:
                    return ('warning',
                            'Please select target you want to operate first.')
            elif btn == 'Y':
                if self.current_con is not None:
                    self.current_con.set_here_home()
                else:
                    return ('warning',
                            'Please select target you want to operate first.')

        elif event.type == sdl2.SDL_JOYBUTTONUP:
            # print("Button up:", event.jbutton.button)
            self.button[self.button_map[event.jbutton.button]] = False
        elif event.type == sdl2.SDL_JOYHATMOTION:
            # print("Hat motion",self.hat_map[event.jhat.value])
            hat_value = self.hat_map[event.jhat.value]
            if self.current_con is not None:
                sign = 1 if self.current_con is self.con_left else -1
                if hat_value == 'D':
                    self.current_con.move_y(1 * sign)
                elif hat_value == 'U':
                    self.current_con.move_y(-1 * sign)
                elif hat_value == 'L':
                    self.current_con.move_x(1 * sign)
                elif hat_value == 'R':
                    self.current_con.move_x(-1 * sign)
            else:
                return ('warning',
                        'Please select target you want to operate first.')
예제 #10
0
    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
gamepad['gp_object'] = gamepad_obj

# Robot configuration, bind sticks and buttons to motors
예제 #11
0
import os

"""
Importing SDL2 in Windows could lead to an ImportError if DLL is not found.
Let's force it to search in the current directory.
"""
if os.name == 'nt':
    os.environ['PYSDL2_DLL_PATH'] = os.curdir

import sdl2
import events

def onJoystickMotion(event, world):
    print('axis motion')

sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)

njoysticks = sdl2.SDL_NumJoysticks()
if njoysticks < 1:
    raise RuntimeError(f'No joysticks connected!')

print('Joysticks available:')
for i in range(njoysticks):
    joy = sdl2.SDL_JoystickOpen(i)
    print(f'  - {sdl2.SDL_JoystickName(joy).decode()}')

joy = sdl2.SDL_JoystickOpen(0)


예제 #12
0
 def open_joystick(self, id):
     self.joy = sdl2.SDL_JoystickOpen(id)
     self.check_SDL_Error()
예제 #13
0
def stamperChildFunction(qTo,
                         qFrom,
                         windowSize=[200, 200],
                         windowPosition=[0, 0],
                         windowColor=[255, 255, 255],
                         doBorder=True):
    import sdl2
    import sdl2.ext
    import sys
    import time
    try:
        import appnope
        appnope.nope()
    except:
        pass
    sdl2.SDL_Init(sdl2.SDL_INIT_TIMER)
    timeFreq = 1.0 / sdl2.SDL_GetPerformanceFrequency()
    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    if doBorder:
        flags = sdl2.SDL_WINDOW_SHOWN
    else:
        flags = sdl2.SDL_WINDOW_BORDERLESS | sdl2.SDL_WINDOW_SHOWN
    window = sdl2.ext.Window("pyStamper",
                             size=windowSize,
                             position=windowPosition,
                             flags=flags)
    windowID = sdl2.SDL_GetWindowID(window.window)
    windowSurf = sdl2.SDL_GetWindowSurface(window.window)
    red = sdl2.pixels.SDL_Color(r=255, g=0, b=0, a=255)
    green = sdl2.pixels.SDL_Color(r=0, g=255, b=0, a=255)
    black = sdl2.pixels.SDL_Color(r=0, g=0, b=0, a=255)
    white = sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255)
    if doBorder:
        sdl2.ext.fill(windowSurf.contents, green)
    else:
        sdl2.ext.fill(
            windowSurf.contents,
            sdl2.pixels.SDL_Color(r=windowColor[0],
                                  g=windowColor[1],
                                  b=windowColor[2],
                                  a=255))
    window.refresh()

    for i in range(10):
        sdl2.SDL_PumpEvents()  #to show the windows

    sdl2.SDL_Init(
        sdl2.SDL_INIT_JOYSTICK)  #uncomment if you want joystick input
    sdl2.SDL_JoystickOpen(0)  #uncomment if you want joystick input
    lostFocus = True
    lostColors = [red, black, red, white]
    lastRefreshTime = time.time()
    while True:
        if lostFocus and doBorder:
            if time.time() > (lastRefreshTime + (2.0 / 60)):
                sdl2.ext.fill(windowSurf.contents, lostColors[0])
                window.refresh()
                lostColors.append(lostColors.pop(0))
                lastRefreshTime = time.time()
        sdl2.SDL_PumpEvents()
        if not qTo.empty():
            message = qTo.get()
            if message == 'quit':
                sys.exit()
            elif message == 'raise':
                sdl2.SDL_RaiseWindow(window.window)
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_WINDOWEVENT:
                if event.window.windowID == windowID:
                    if (event.window.event == sdl2.SDL_WINDOWEVENT_CLOSE):
                        qFrom.put({
                            'type': 'key',
                            'time': event.window.timestamp * timeFreq,
                            'value': 'escape'
                        })
                        sys.exit()
                    elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_LOST:
                        lostFocus = True
                    elif event.window.event == sdl2.SDL_WINDOWEVENT_FOCUS_GAINED:
                        lostFocus = False
                        if doBorder:
                            sdl2.ext.fill(windowSurf.contents, green)
                            window.refresh()
            else:
                message = {}
                if event.type == sdl2.SDL_KEYDOWN:
                    message['type'] = 'key'
                    message['time'] = event.key.timestamp * timeFreq
                    message['value'] = sdl2.SDL_GetKeyName(
                        event.key.keysym.sym).lower()
                    message['keysym'] = event.key.keysym
                    qFrom.put(message)
                elif event.type == sdl2.SDL_JOYAXISMOTION:
                    message['type'] = 'axis'
                    message['axis'] = event.jaxis.axis
                    message['time'] = event.jaxis.timestamp * timeFreq
                    message['value'] = event.jaxis.value
                    qFrom.put(message)
                elif event.type == sdl2.SDL_JOYBUTTONDOWN:
                    message['type'] = 'button'
                    message['time'] = event.jbutton.timestamp * timeFreq
                    message['value'] = event.jbutton.button
                    qFrom.put(message)