Exemplo n.º 1
0
    def __init__(self, joystick):
        self.joystick_current = None
        self.joystick_previous = None

        self.x_current = sdl2.SDL_JoystickGetAxis(joystick, 0)
        self.x_previous = sdl2.SDL_JoystickGetAxis(joystick, 0)

        self.y_current = sdl2.SDL_JoystickGetAxis(joystick, 1)
        self.y_previous = sdl2.SDL_JoystickGetAxis(joystick, 1)
Exemplo n.º 2
0
def getBrakeVal():
    sdl2.SDL_PumpEvents()
    joy_y = sdl2.SDL_JoystickGetAxis(joystick, 1)
    joy_y = (joy_y / 32767)
    if (joy_y < 0.001):
        joy_y = 0
    return joy_y
Exemplo n.º 3
0
    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 scaled_stick_value(gp, axis, invert, deadzone_pct=4):
    stick_value = scale(sdl2.SDL_JoystickGetAxis(gp['gp_object'], axis),
                        gp['stick_range'],
                        (-32768, 32768)
    ) * invert

    deadzone_range = tuple(n * deadzone_pct / 100.0 for n in (-32768, 32768))

    if min(deadzone_range) < stick_value < max(deadzone_range):
        return 0
    else:
        return int(stick_value)
Exemplo n.º 5
0
    def steer(self):
        angle = self.state.angle
        dist = self.state.trackPos

        steer = (angle - dist * 0.5) / self.steer_lock
        self.control.setSteer(steer)

        sdl2.SDL_PumpEvents()
        wheel = sdl2.SDL_JoystickGetAxis(self.joystick, 0)
        wheel = -wheel / 32767.0

        #print steer, wheel, steer-wheel

        self.generate_force(steer - wheel)
Exemplo n.º 6
0
    def getJoystickState(self):
        self.result = []

        for i in range(self.numAxes):
            self.axis = sdl2.SDL_JoystickGetAxis(self.joystick, i) 
            self.result.append(self.axis)

        for i in range(self.numButtons):
            self.button = sdl2.SDL_JoystickGetButton(self.joystick, i)
            self.result.append(self.button)

        self.result[0] = int(self.result[0] / SDL_AXIS_CONVERT) + 100
        self.result[1] = -int(self.result[1] / SDL_AXIS_CONVERT) + 100

        return self.result
Exemplo n.º 7
0
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
Exemplo n.º 8
0
    def read(self):
        """Read all the sticks and switches"""

        # Force an update of the joystick channels
        sdl2.SDL_PumpEvents()

        # Ensure that the Tx is connected
        if sdl2.SDL_NumJoysticks() == 0:
            if self.joystick:
                sdl2.SDL_JoystickClose(self.joystick)
                self.joystick = None
            return False
        elif not self.joystick:
            # Open the first joystick if necessary
            self.joystick = sdl2.SDL_JoystickOpen(0)

        # Read all the channels
        ret = []
        for channel in range(self.channels):
            val = sdl2.SDL_JoystickGetAxis(self.joystick, channel)
            ret.append(int(((val / 65536.0) + 0.5) * 800.0 + 1100.0))

        # Return the list of values
        return ret
Exemplo n.º 9
0
 def value(self):
     return sdl2.SDL_JoystickGetAxis(
         self._joystick, self._index
     ) / float(32768)
Exemplo n.º 10
0
joystick = sdl2.SDL_JoystickOpen(0)
 
# Open the NXT Bluetooth connection
conn = Connection('/dev/tty.NXT-DevB')

# Helper function to limit the range of a value 
def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)
 
# Main loop
while True:
    sdl2.SDL_PumpEvents()
 
    # Read controller stick Y-inputs and normalize the value
    # to a range of -100 to 100
    joy_1 = -sdl2.SDL_JoystickGetAxis(joystick, 1) / 327.67
    joy_3 = -sdl2.SDL_JoystickGetAxis(joystick, 3) / 327.67

    m1 = clamp(joy_1,-100,100)
    m2 = clamp(joy_3,-100,100)

    # Check left/right triggers (10,11) for 3rd motor control
    if sdl2.SDL_JoystickGetButton(joystick, 10): m0 = -30
    elif sdl2.SDL_JoystickGetButton(joystick, 11): m0 = 30
    else: m0 = 0
 
    # Print values to console (mostly for debugging)
    print('m0: %d' % m0)
    print('m1: %d' % m1)
    print('m2: %d' % m2)
Exemplo n.º 11
0
    'lt1': 0, # left trigger 1
    'rt1': 0,
    'lt2': 0, # left trigger 2
    'rt2': 0,
    'A': 0,  
    'X': 0,   
    'Y': 0,
    'B': 0,
    'hat': 0,
    }

while True:
    sdl2.SDL_JoystickUpdate()
    
    # left axis
    pro['la']['x'] = sdl2.SDL_JoystickGetAxis(js,0)
    pro['la']['y'] = sdl2.SDL_JoystickGetAxis(js,1)
    
    # right axis
    pro['ra']['x'] = sdl2.SDL_JoystickGetAxis(js,2)
    pro['ra']['y'] = sdl2.SDL_JoystickGetAxis(js,3)
    
    # left trigger axis
    # pro['lt2'] = sdl2.SDL_JoystickGetAxis(js,6)
    pro['lt2'] = sdl2.SDL_JoystickGetButton(js,6)
    
    # right trigger axis
    # pro['rt2'] = sdl2.SDL_JoystickGetAxis(js,7)
    pro['rt2'] = sdl2.SDL_JoystickGetButton(js,7)
    
    # get buttons
Exemplo n.º 12
0
    def get(self):
        if not self.valid:
            return None

        js = self.js

        sdl2.SDL_JoystickUpdate()

        share = sdl2.SDL_JoystickGetButton(js, 8)
        if share:
            exit(0)

        ls = Axis(sdl2.SDL_JoystickGetAxis(js, 0),
                  sdl2.SDL_JoystickGetAxis(js, 1))

        rs = Axis(sdl2.SDL_JoystickGetAxis(js, 2),
                  sdl2.SDL_JoystickGetAxis(js, 5))

        triggers = Trigger(sdl2.SDL_JoystickGetAxis(js, 3),
                           sdl2.SDL_JoystickGetAxis(js, 4))

        shoulder = [
            sdl2.SDL_JoystickGetButton(js, 4),
            sdl2.SDL_JoystickGetButton(js, 5)
        ]

        stick = [
            sdl2.SDL_JoystickGetButton(js, 10),
            sdl2.SDL_JoystickGetButton(js, 11)
        ]

        # I seem to have lost sensors
        # a = Sensors(
        # 	sdl2.SDL_JoystickGetAxis(js, 6),
        # 	sdl2.SDL_JoystickGetAxis(js, 7),
        # 	sdl2.SDL_JoystickGetAxis(js, 8)
        # )
        #
        # g = Sensors(
        # 	sdl2.SDL_JoystickGetAxis(js, 9),
        # 	sdl2.SDL_JoystickGetAxis(js, 10),
        # 	sdl2.SDL_JoystickGetAxis(js, 11)
        # )

        b = [
            sdl2.SDL_JoystickGetButton(js, 0),  # square
            sdl2.SDL_JoystickGetButton(js, 3),  # triangle
            sdl2.SDL_JoystickGetButton(js, 2),  # circle
            sdl2.SDL_JoystickGetButton(js, 1)  # x
        ]

        hat = sdl2.SDL_JoystickGetHat(js, 0)
        share = sdl2.SDL_JoystickGetButton(js, 8)
        options = sdl2.SDL_JoystickGetButton(js, 9)

        ps4 = PS4(ls, rs, triggers, hat, shoulder, stick, b, options, share)

        # left axis
        # x = sdl2.SDL_JoystickGetAxis(js, 0) / 32768
        # y = sdl2.SDL_JoystickGetAxis(js, 1) / 32768
        # ps4['leftStick'] = [x, y]
        #
        # # right axis
        # x = sdl2.SDL_JoystickGetAxis(js, 2) / 32768
        # y = sdl2.SDL_JoystickGetAxis(js, 5) / 32768
        # ps4['rightStick'] = [x, y]

        # # other axes
        # ps4.axes.L2 = sdl2.SDL_JoystickGetAxis(js, 3) / 32768
        # ps4.axes.R2 = sdl2.SDL_JoystickGetAxis(js, 4) / 32768
        #
        # # accels
        # x = sdl2.SDL_JoystickGetAxis(js, 6) / 32768
        # y = sdl2.SDL_JoystickGetAxis(js, 7) / 32768
        # z = sdl2.SDL_JoystickGetAxis(js, 8) / 32768
        # ps4.axes.accels = [x, y, z]
        #
        # # gyros
        # x = sdl2.SDL_JoystickGetAxis(js, 9) / 32768
        # y = sdl2.SDL_JoystickGetAxis(js, 10) / 32768
        # z = sdl2.SDL_JoystickGetAxis(js, 11) / 32768
        # ps4.axes.gyros = [x, y, z]
        #
        # # get buttons
        # ps4.buttons.s = sdl2.SDL_JoystickGetButton(js, 0)
        # ps4.buttons.x = sdl2.SDL_JoystickGetButton(js, 1)
        # ps4.buttons.o = sdl2.SDL_JoystickGetButton(js, 2)
        # ps4.buttons.t = sdl2.SDL_JoystickGetButton(js, 3)
        # ps4.buttons.L1 = sdl2.SDL_JoystickGetButton(js, 4)
        # ps4.buttons.R1 = sdl2.SDL_JoystickGetButton(js, 5)
        # ps4.buttons.L2 = sdl2.SDL_JoystickGetButton(js, 6)
        # ps4.buttons.R2 = sdl2.SDL_JoystickGetButton(js, 7)
        # ps4.buttons.share = sdl2.SDL_JoystickGetButton(js, 8)
        # ps4.buttons.options = sdl2.SDL_JoystickGetButton(js, 9)
        # ps4.buttons.L3 = sdl2.SDL_JoystickGetButton(js, 10)
        # ps4.buttons.R3 = sdl2.SDL_JoystickGetButton(js, 11)
        # ps4.buttons.ps = sdl2.SDL_JoystickGetButton(js, 12)
        # ps4.buttons.pad = sdl2.SDL_JoystickGetButton(js, 13)
        #
        # # get hat
        # # [up right down left] = [1 2 4 8]
        # ps4.buttons.hat = sdl2.SDL_JoystickGetHat(js, 0)

        # print('b 12', sdl2.SDL_JoystickGetButton(js, 12))
        # print('b 13', sdl2.SDL_JoystickGetButton(js, 13))

        return ps4
Exemplo n.º 13
0
# ______ 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 = {
    'motors': {
        'steer': {
            'port': "A",
Exemplo n.º 14
0
# ______ 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

for i in range(5):
    # update joystick info
    sdl2.SDL_PumpEvents()
    state = []
    for axis in range(4):
        state += [sdl2.SDL_JoystickGetAxis(gamepad_obj, axis)]
    print(state)
Exemplo n.º 15
0
 def axis(self, axis, mapping=LINEAR):
     reading = SDL.SDL_JoystickGetAxis(self.raw, axis)
     return mapping.evaluate(reading)
Exemplo n.º 16
0
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
""" For when we want to use multiple joysticks
self.joysticks = []
for i in range(0, sdl2.SDL_NumJoySticks()):
    joy = sdl2.SDL_JoystickOpen(i)
    self.joysticks.append(joy)
print("joystick initialized")
"""

joy = sdl2.SDL_JoystickOpen(0)

while True:
    sdl2.SDL_PumpEvents()
    data = []
    for i in range(0, 6):
        data.append(int(sdl2.SDL_JoystickGetAxis(joy, i)))
    for i in range(0, 11):
        data.append(int(sdl2.SDL_JoystickGetButton(joy, i)))
    data.append(int(sdl2.SDL_JoystickGetHat(joy, 0)))
    msg = json.dumps(data)
    jsnode.send("inputs-out", msg)
    time.sleep(0.05)
    print(data)

    # Data array format:
    ## 16 bit signed ints:
    # 0  | right joystick x
    # 1  | right joystick y
    # 2  | right trigger
    # 3  | left joystick x
    # 4  | left joystick y
Exemplo n.º 17
0
    def read(self, verbose=False):
        js = self.js
        dt = self.sleep
        ps4 = Msg.Joystick()
        twist = Msg.Twist()

        try:
            sdl2.SDL_JoystickUpdate()

            # left axis
            x = sdl2.SDL_JoystickGetAxis(js, 0) / 32768
            y = sdl2.SDL_JoystickGetAxis(js, 1) / 32768
            ps4.axes.leftStick = [x, y]

            # right axis
            x = sdl2.SDL_JoystickGetAxis(js, 2) / 32768
            y = sdl2.SDL_JoystickGetAxis(js, 5) / 32768
            ps4.axes.rightStick = [x, y]

            # other axes
            ps4.axes.L2 = sdl2.SDL_JoystickGetAxis(js, 3) / 32768
            ps4.axes.R2 = sdl2.SDL_JoystickGetAxis(js, 4) / 32768

            # accels
            x = sdl2.SDL_JoystickGetAxis(js, 6) / 32768
            y = sdl2.SDL_JoystickGetAxis(js, 7) / 32768
            z = sdl2.SDL_JoystickGetAxis(js, 8) / 32768
            ps4.axes.accels = [x, y, z]

            # gyros
            x = sdl2.SDL_JoystickGetAxis(js, 9) / 32768
            y = sdl2.SDL_JoystickGetAxis(js, 10) / 32768
            z = sdl2.SDL_JoystickGetAxis(js, 11) / 32768
            ps4.axes.gyros = [x, y, z]

            # get buttons
            ps4.buttons.s = sdl2.SDL_JoystickGetButton(js, 0)
            ps4.buttons.x = sdl2.SDL_JoystickGetButton(js, 1)
            ps4.buttons.o = sdl2.SDL_JoystickGetButton(js, 2)
            ps4.buttons.t = sdl2.SDL_JoystickGetButton(js, 3)
            ps4.buttons.L1 = sdl2.SDL_JoystickGetButton(js, 4)
            ps4.buttons.R1 = sdl2.SDL_JoystickGetButton(js, 5)
            ps4.buttons.L2 = sdl2.SDL_JoystickGetButton(js, 6)
            ps4.buttons.R2 = sdl2.SDL_JoystickGetButton(js, 7)
            ps4.buttons.share = sdl2.SDL_JoystickGetButton(js, 8)
            ps4.buttons.options = sdl2.SDL_JoystickGetButton(js, 9)
            ps4.buttons.L3 = sdl2.SDL_JoystickGetButton(js, 10)
            ps4.buttons.R3 = sdl2.SDL_JoystickGetButton(js, 11)
            ps4.buttons.ps = sdl2.SDL_JoystickGetButton(js, 12)
            ps4.buttons.pad = sdl2.SDL_JoystickGetButton(js, 13)

            # get hat
            # [up right down left] = [1 2 4 8]
            ps4.buttons.hat = sdl2.SDL_JoystickGetHat(js, 0)

            # print('b 12', sdl2.SDL_JoystickGetButton(js, 12))
            # print('b 13', sdl2.SDL_JoystickGetButton(js, 13))

            #self.pub.pub('js', ps4)

            x, y = ps4.axes.rightStick
            twist.linear.set(x, y, 0)
            x, y = ps4.axes.leftStick
            twist.angular.set(x, y, 0)

            # verbose = True
            if verbose:
                print(twist)

            if (self.old_twist.angular
                    == twist.angular) and (self.old_twist.linear
                                           == twist.linear):
                # print('js no msg')
                pass
            else:
                self.pub.pub(self.topic, twist)
                self.old_twist = twist
                # print('js message sent')

            time.sleep(dt)

        except (IOError, EOFError):
            print('[-] Connection gone .... bye')
Exemplo n.º 18
0
                        direction = 1
                    elif total_error > 0:
                        direction = -1
                    else:
                        direction = 0

                    haptic = sdl2.SDL_HapticOpen(0)
                    # sdl2.SDL_HapticStopAll(haptic)
                    sdl2.SDL_HapticSetAutocenter(haptic, 0)
                    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=(direction, 0, 0)), \
                                                length=lenght, level=int(hex(level), 16), attack_length=0, fade_length=0))
                    sdl2.SDL_HapticUpdateEffect(haptic, effect_id, efx)
                    sdl2.SDL_HapticRunEffect(haptic, effect_id, 1)
                    wheel_state = sdl2.SDL_JoystickGetAxis(
                        sdl2.SDL_JoystickOpen(0), 0)

                last_error = error
                last_total_error = total_error

    if is_wheel_connected and auto is False:
        joystick = sdl2.SDL_JoystickOpen(0)
        event = sdl2.SDL_Event()
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_JOYBUTTONDOWN:
                if event.jbutton.button == 15:
                    if gear == 0:
                        gear += 1
                        print(gear)
                elif event.jbutton.button == 14:
                    if gear == 0:
Exemplo n.º 19
0
    player['conn'] = Connection(player['tty'])

# open the connection. Get this string from preferences>bluetooth>NXT>edit serial ports


def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)


running = 1
while running:
    sdl2.SDL_PumpEvents()

    for player in players:
        # read joystick input and normalise it to a range of -100 to 100
        joy_x = (sdl2.SDL_JoystickGetAxis(player['gamepad'], 0) -
                 player['stick_center']) * 200 / player['stick_range']
        joy_y = (sdl2.SDL_JoystickGetAxis(player['gamepad'], 1) -
                 player['stick_center']
                 ) * 200 / player['stick_range'] * player['invert_y']

        # use shoulder buttons on the game pad to make the omnibot rotate around it's axis.
        turnpower = 0
        if sdl2.SDL_JoystickGetButton(player['gamepad'],
                                      player['right_shoulder_btn']):
            turnpower = 75
        if sdl2.SDL_JoystickGetButton(player['gamepad'],
                                      player['left_shoulder_btn']):
            turnpower = -75

        # end the fun if button 1 is pressed.
Exemplo n.º 20
0
    def read_axis(self, axis, smoothing):
        sdl2.SDL_JoystickUpdate()

        return sdl2.SDL_JoystickGetAxis(self.joy, axis) / smoothing
Exemplo n.º 21
0
 def UpdateDPad(self, joystick):
     self.x_previous = self.x_current
     self.x_current = sdl2.SDL_JoystickGetAxis(joystick, 0)
Exemplo n.º 22
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
Exemplo n.º 23
0
    def get(self):
        ps4 = self.ps4
        js = self.js

        sdl2.SDL_JoystickUpdate()

        # left axis
        x = sdl2.SDL_JoystickGetAxis(js, 0) / 32768
        y = sdl2.SDL_JoystickGetAxis(js, 1) / 32768
        ps4['leftStick'] = [-x, -y]

        # right axis
        x = sdl2.SDL_JoystickGetAxis(js, 2) / 32768
        y = sdl2.SDL_JoystickGetAxis(js, 5) / 32768
        ps4['rightStick'] = [-x, -y]

        # # other axes
        # ps4.axes.L2 = sdl2.SDL_JoystickGetAxis(js, 3) / 32768
        # ps4.axes.R2 = sdl2.SDL_JoystickGetAxis(js, 4) / 32768
        #
        # # accels
        # x = sdl2.SDL_JoystickGetAxis(js, 6) / 32768
        # y = sdl2.SDL_JoystickGetAxis(js, 7) / 32768
        # z = sdl2.SDL_JoystickGetAxis(js, 8) / 32768
        # ps4.axes.accels = [x, y, z]
        #
        # # gyros
        # x = sdl2.SDL_JoystickGetAxis(js, 9) / 32768
        # y = sdl2.SDL_JoystickGetAxis(js, 10) / 32768
        # z = sdl2.SDL_JoystickGetAxis(js, 11) / 32768
        # ps4.axes.gyros = [x, y, z]
        #
        # # get buttons
        # ps4.buttons.s = sdl2.SDL_JoystickGetButton(js, 0)
        # ps4.buttons.x = sdl2.SDL_JoystickGetButton(js, 1)
        # ps4.buttons.o = sdl2.SDL_JoystickGetButton(js, 2)
        # ps4.buttons.t = sdl2.SDL_JoystickGetButton(js, 3)
        # ps4.buttons.L1 = sdl2.SDL_JoystickGetButton(js, 4)
        # ps4.buttons.R1 = sdl2.SDL_JoystickGetButton(js, 5)
        # ps4.buttons.L2 = sdl2.SDL_JoystickGetButton(js, 6)
        # ps4.buttons.R2 = sdl2.SDL_JoystickGetButton(js, 7)
        # ps4.buttons.share = sdl2.SDL_JoystickGetButton(js, 8)
        # ps4.buttons.options = sdl2.SDL_JoystickGetButton(js, 9)
        # ps4.buttons.L3 = sdl2.SDL_JoystickGetButton(js, 10)
        # ps4.buttons.R3 = sdl2.SDL_JoystickGetButton(js, 11)
        # ps4.buttons.ps = sdl2.SDL_JoystickGetButton(js, 12)
        # ps4.buttons.pad = sdl2.SDL_JoystickGetButton(js, 13)
        #
        # # get hat
        # # [up right down left] = [1 2 4 8]
        # ps4.buttons.hat = sdl2.SDL_JoystickGetHat(js, 0)

        # print('b 12', sdl2.SDL_JoystickGetButton(js, 12))
        # print('b 13', sdl2.SDL_JoystickGetButton(js, 13))

        # if verbose:  # print(Msg.Joystick.screen(ps4))
        # 	print(ps4.axes.accels)

        # except (IOError, EOFError):
        # 	print('[-] Connection gone .... bye')
        # 	break
        #
        # except (KeyboardInterrupt, SystemExit):
        # 	print('js bye ...')
        # 	break
        # except Exception as e:
        # 	print('Ooops:', e)
        # else:
        # 	raise Exception('Joystick: Something bad happened!')
        return ps4
Exemplo n.º 24
0
    def handle_input(self):
        app = self.app
        # get and store mouse state
        # (store everything in parent app object so stuff can access it easily)
        mx, my = ctypes.c_int(0), ctypes.c_int(0)
        mouse = sdl2.mouse.SDL_GetMouseState(mx, my)
        app.left_mouse = bool(mouse & sdl2.SDL_BUTTON(sdl2.SDL_BUTTON_LEFT))
        app.middle_mouse = bool(mouse
                                & sdl2.SDL_BUTTON(sdl2.SDL_BUTTON_MIDDLE))
        app.right_mouse = bool(mouse & sdl2.SDL_BUTTON(sdl2.SDL_BUTTON_RIGHT))
        mx, my = int(mx.value), int(my.value)
        # if mouse hasn't moved since init, disregard SDL_GetMouseState
        if self.mouse_has_moved:
            app.mouse_x, app.mouse_y = mx, my
        elif mx != 0 or my != 0:
            self.mouse_has_moved = True
        # relative mouse move state
        mdx, mdy = ctypes.c_int(0), ctypes.c_int(0)
        sdl2.mouse.SDL_GetRelativeMouseState(mdx, mdy)
        if self.mouse_has_moved:
            app.mouse_dx, app.mouse_dy = int(mdx.value), int(mdy.value)
        if app.mouse_dx != 0 or app.mouse_dy != 0:
            app.keyboard_editing = False
            # dragging a dialog?
            if app.left_mouse and self.ui.active_dialog in self.ui.hovered_elements:
                self.ui.active_dialog.update_drag(app.mouse_dx, app.mouse_dy)
        # get keyboard state so later we can directly query keys
        ks = sdl2.SDL_GetKeyboardState(None)
        # get modifier states
        self.shift_pressed, self.alt_pressed, self.ctrl_pressed = False, False, False
        if ks[sdl2.SDL_SCANCODE_LSHIFT] or ks[sdl2.SDL_SCANCODE_RSHIFT]:
            self.shift_pressed = True
        if ks[sdl2.SDL_SCANCODE_LALT] or ks[sdl2.SDL_SCANCODE_RALT]:
            self.alt_pressed = True
        if ks[sdl2.SDL_SCANCODE_LCTRL] or ks[sdl2.SDL_SCANCODE_RCTRL]:
            self.ctrl_pressed = True
        # macOS: treat command as interchangeable with control, is this kosher?
        if platform.system() == 'Darwin' and (ks[sdl2.SDL_SCANCODE_LGUI]
                                              or ks[sdl2.SDL_SCANCODE_RGUI]):
            self.ctrl_pressed = True
        if app.capslock_is_ctrl and ks[sdl2.SDL_SCANCODE_CAPSLOCK]:
            self.ctrl_pressed = True
        # pack mods into a tuple to save listing em all out repeatedly
        mods = self.shift_pressed, self.alt_pressed, self.ctrl_pressed
        # get controller state
        if self.gamepad:
            self.gamepad_left_x = sdl2.SDL_JoystickGetAxis(
                self.gamepad, sdl2.SDL_CONTROLLER_AXIS_LEFTX) / 32768
            self.gamepad_left_y = sdl2.SDL_JoystickGetAxis(
                self.gamepad, sdl2.SDL_CONTROLLER_AXIS_LEFTY) / -32768
        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_QUIT:
                app.should_quit = True
            elif event.type == sdl2.SDL_WINDOWEVENT:
                if event.window.event == sdl2.SDL_WINDOWEVENT_RESIZED:
                    # test window we create on init to detect resolution makes
                    # SDL think we've resized main app window on first tick!
                    if app.updates > 0:
                        app.resize_window(event.window.data1,
                                          event.window.data2)
            elif event.type == sdl2.SDL_JOYBUTTONDOWN:
                if not app.gw.paused and app.gw.player:
                    app.gw.player.button_pressed(event.jbutton.button)
            elif event.type == sdl2.SDL_JOYBUTTONUP:
                if not app.gw.paused and app.gw.player:
                    self.app.gw.player.button_unpressed(event.jbutton.button)
            elif event.type == sdl2.SDL_KEYDOWN:
                keysym = self.get_keysym(event)
                # if console is up, pass input to it
                if self.ui.console.visible:
                    self.ui.console.handle_input(keysym, *mods)
                # same with dialog box
                elif self.ui.active_dialog and self.ui.active_dialog is self.ui.keyboard_focus_element:
                    self.ui.active_dialog.handle_input(keysym, *mods)
                    # bail, process no further input
                    #sdl2.SDL_PumpEvents()
                    #return
                # handle text input if text tool is active
                elif self.ui.selected_tool is self.ui.text_tool and self.ui.text_tool.input_active:
                    self.ui.text_tool.handle_keyboard_input(keysym, *mods)
                # see if there's a function for this bind and run it
                else:
                    flist = self.get_bind_functions(keysym, *mods)
                    for f in flist:
                        # don't run any command whose menu bar item's dimmed / not allowed (ie wrong mode)
                        if self.is_command_function_allowed(f):
                            f()
                    # if game mode active, pass to world as well as any binds
                    if self.app.game_mode:
                        self.app.gw.handle_input(event, *mods)
            # for key up events, use the same binds but handle them special case
            # TODO: once there are enough key up events, figure out a more
            # elegant way than this
            elif event.type == sdl2.SDL_KEYUP:
                keysym = self.get_keysym(event)
                if self.app.game_mode:
                    self.app.gw.handle_input(event, *mods)
                # dismiss selector popup
                flist = self.get_bind_functions(keysym, *mods)
                if not flist:
                    pass
                elif self.ui.active_dialog:
                    # keyup shouldn't have any special meaning in a dialog
                    pass
                elif self.BIND_game_grab in flist:
                    if self.app.game_mode and not self.ui.active_dialog and self.app.gw.player:
                        self.app.gw.player.button_unpressed(0)
                        return
                elif self.BIND_toggle_picker in flist:
                    # ..but only for default hold-to-show setting
                    if self.ui.popup_hold_to_show:
                        self.ui.popup.hide()
                elif self.BIND_select_or_paint in flist:
                    app.keyboard_editing = True
                    if not self.ui.selected_tool is self.ui.text_tool and not self.ui.text_tool.input_active:
                        self.app.cursor.finish_paint()
            #
            # mouse events aren't handled by bind table for now
            #
            elif event.type == sdl2.SDL_MOUSEWHEEL:
                ui_wheeled = self.ui.wheel_moved(event.wheel.y)
                if not ui_wheeled:
                    if self.app.can_edit:
                        if event.wheel.y > 0:
                            # only zoom in should track towards cursor
                            app.camera.zoom(-self.wheel_zoom_amount,
                                            towards_cursor=True)
                        elif event.wheel.y < 0:
                            app.camera.zoom(self.wheel_zoom_amount)
                    else:
                        self.app.gw.mouse_wheeled(event.wheel.y)
            elif event.type == sdl2.SDL_MOUSEBUTTONUP:
                # "consume" input if UI handled it
                ui_unclicked = self.ui.unclicked(event.button.button)
                if ui_unclicked:
                    sdl2.SDL_PumpEvents()
                    return
                if self.app.game_mode:
                    self.app.gw.unclicked(event.button.button)
                # LMB up: finish paint for most tools, end select drag
                if event.button.button == sdl2.SDL_BUTTON_LEFT:
                    if self.ui.selected_tool is self.ui.select_tool and self.ui.select_tool.selection_in_progress:
                        self.ui.select_tool.finish_select(
                            self.shift_pressed, self.ctrl_pressed)
                    elif not self.ui.selected_tool is self.ui.text_tool and not self.ui.text_tool.input_active:
                        app.cursor.finish_paint()
            elif event.type == sdl2.SDL_MOUSEBUTTONDOWN:
                ui_clicked = self.ui.clicked(event.button.button)
                # don't register edit commands if a menu is up
                if ui_clicked or self.ui.menu_bar.active_menu_name or self.ui.active_dialog:
                    sdl2.SDL_PumpEvents()
                    if self.app.game_mode:
                        self.app.gw.last_click_on_ui = True
                    return
                # pass clicks through to game world
                if self.app.game_mode:
                    if not ui_clicked:
                        self.app.gw.clicked(event.button.button)
                # LMB down: start text entry, start select drag, or paint
                elif event.button.button == sdl2.SDL_BUTTON_LEFT:
                    if not self.ui.active_art:
                        return
                    elif self.ui.selected_tool is self.ui.text_tool:
                        # text tool: only start entry if click is outside popup
                        if not self.ui.text_tool.input_active and \
                         not self.ui.popup in self.ui.hovered_elements:
                            self.ui.text_tool.start_entry()
                    elif self.ui.selected_tool is self.ui.select_tool:
                        # select tool: accept clicks if they're outside the popup
                        if not self.ui.select_tool.selection_in_progress and \
                            (not self.ui.keyboard_focus_element or \
                               (self.ui.keyboard_focus_element is self.ui.popup and \
                                not self.ui.popup in self.ui.hovered_elements)):
                            self.ui.select_tool.start_select()
                    else:
                        app.cursor.start_paint()
                elif event.button.button == sdl2.SDL_BUTTON_RIGHT:
                    if self.app.ui.active_art:
                        self.ui.quick_grab()
        # none of the below applies to cases where a dialog is up
        if self.ui.active_dialog:
            sdl2.SDL_PumpEvents()
            return
        # directly query keys we don't want affected by OS key repeat delay
        # TODO: these are hard-coded for the moment, think of a good way
        # to expose this functionality to the key bind system
        def pressing_up(ks):
            return ks[sdl2.SDL_SCANCODE_W] or ks[sdl2.SDL_SCANCODE_UP] or ks[
                sdl2.SDL_SCANCODE_KP_8]

        def pressing_down(ks):
            return ks[sdl2.SDL_SCANCODE_S] or ks[sdl2.SDL_SCANCODE_DOWN] or ks[
                sdl2.SDL_SCANCODE_KP_2]

        def pressing_left(ks):
            return ks[sdl2.SDL_SCANCODE_A] or ks[sdl2.SDL_SCANCODE_LEFT] or ks[
                sdl2.SDL_SCANCODE_KP_4]

        def pressing_right(ks):
            return ks[sdl2.SDL_SCANCODE_D] or ks[
                sdl2.SDL_SCANCODE_RIGHT] or ks[sdl2.SDL_SCANCODE_KP_6]

        # prevent camera move if: console is up, text input is active, editing
        # is not allowed
        if self.shift_pressed and not self.alt_pressed and not self.ctrl_pressed and not self.ui.console.visible and not self.ui.text_tool.input_active and self.app.can_edit and self.ui.keyboard_focus_element is None:
            if pressing_up(ks):
                app.camera.pan(0, 1, True)
            if pressing_down(ks):
                app.camera.pan(0, -1, True)
            if pressing_left(ks):
                app.camera.pan(-1, 0, True)
            if pressing_right(ks):
                app.camera.pan(1, 0, True)
            if ks[sdl2.SDL_SCANCODE_X]:
                app.camera.zoom(-self.keyboard_zoom_amount,
                                keyboard=True,
                                towards_cursor=True)
            if ks[sdl2.SDL_SCANCODE_Z]:
                app.camera.zoom(self.keyboard_zoom_amount, keyboard=True)
        if self.app.can_edit and app.middle_mouse and (app.mouse_dx != 0
                                                       or app.mouse_dy != 0):
            app.camera.mouse_pan(app.mouse_dx, app.mouse_dy)
        # game mode: arrow keys and left gamepad stick move player
        if self.app.game_mode and not self.ui.console.visible and not self.ui.active_dialog and self.ui.keyboard_focus_element is None:
            if pressing_up(ks):
                # shift = move selected
                if self.shift_pressed and self.app.can_edit:
                    app.gw.move_selected(0, 1, 0)
                elif not self.ctrl_pressed and app.gw.player:
                    app.gw.player.move(0, 1)
            if pressing_down(ks):
                if self.shift_pressed and self.app.can_edit:
                    app.gw.move_selected(0, -1, 0)
                elif not self.ctrl_pressed and app.gw.player:
                    app.gw.player.move(0, -1)
            if pressing_left(ks):
                if self.shift_pressed and self.app.can_edit:
                    app.gw.move_selected(-1, 0, 0)
                elif not self.ctrl_pressed and app.gw.player:
                    app.gw.player.move(-1, 0)
            if pressing_right(ks):
                if self.shift_pressed and self.app.can_edit:
                    app.gw.move_selected(1, 0, 0)
                elif not self.ctrl_pressed and app.gw.player:
                    app.gw.player.move(1, 0)
            if abs(self.gamepad_left_x) > 0.15 and app.gw.player:
                app.gw.player.move(self.gamepad_left_x, 0)
            if abs(self.gamepad_left_y) > 0.15 and app.gw.player:
                app.gw.player.move(0, self.gamepad_left_y)
        sdl2.SDL_PumpEvents()
Exemplo n.º 25
0
	def run(self, verbose, rate):
		js = self.js
		dt = 1.0/rate
		ps4 = Msg.Joystick()

		while True:
			try:
				sdl2.SDL_JoystickUpdate()

				# left axis
				x = sdl2.SDL_JoystickGetAxis(js, 0) / 32768
				y = sdl2.SDL_JoystickGetAxis(js, 1) / 32768
				ps4.axes.leftStick = [x, y]

				# right axis
				x = sdl2.SDL_JoystickGetAxis(js, 2) / 32768
				y = sdl2.SDL_JoystickGetAxis(js, 5) / 32768
				ps4.axes.rightStick = [x, y]

				# other axes
				ps4.axes.L2 = sdl2.SDL_JoystickGetAxis(js, 3) / 32768
				ps4.axes.R2 = sdl2.SDL_JoystickGetAxis(js, 4) / 32768

				# accels
				x = sdl2.SDL_JoystickGetAxis(js, 6) / 32768
				y = sdl2.SDL_JoystickGetAxis(js, 7) / 32768
				z = sdl2.SDL_JoystickGetAxis(js, 8) / 32768
				ps4.axes.accels = [x, y, z]

				# gyros
				x = sdl2.SDL_JoystickGetAxis(js, 9) / 32768
				y = sdl2.SDL_JoystickGetAxis(js, 10) / 32768
				z = sdl2.SDL_JoystickGetAxis(js, 11) / 32768
				ps4.axes.gyros = [x, y, z]

				# get buttons
				ps4.buttons.s = sdl2.SDL_JoystickGetButton(js, 0)
				ps4.buttons.x = sdl2.SDL_JoystickGetButton(js, 1)
				ps4.buttons.o = sdl2.SDL_JoystickGetButton(js, 2)
				ps4.buttons.t = sdl2.SDL_JoystickGetButton(js, 3)
				ps4.buttons.L1 = sdl2.SDL_JoystickGetButton(js, 4)
				ps4.buttons.R1 = sdl2.SDL_JoystickGetButton(js, 5)
				ps4.buttons.L2 = sdl2.SDL_JoystickGetButton(js, 6)
				ps4.buttons.R2 = sdl2.SDL_JoystickGetButton(js, 7)
				ps4.buttons.share = sdl2.SDL_JoystickGetButton(js, 8)
				ps4.buttons.options = sdl2.SDL_JoystickGetButton(js, 9)
				ps4.buttons.L3 = sdl2.SDL_JoystickGetButton(js, 10)
				ps4.buttons.R3 = sdl2.SDL_JoystickGetButton(js, 11)
				ps4.buttons.ps = sdl2.SDL_JoystickGetButton(js, 12)
				ps4.buttons.pad = sdl2.SDL_JoystickGetButton(js, 13)

				# get hat
				# [up right down left] = [1 2 4 8]
				ps4.buttons.hat = sdl2.SDL_JoystickGetHat(js, 0)

				# print('b 12', sdl2.SDL_JoystickGetButton(js, 12))
				# print('b 13', sdl2.SDL_JoystickGetButton(js, 13))

				if verbose: print(Msg.Joystick.screen(ps4))

				self.pub.pub('js', ps4)
				time.sleep(dt)

			except (IOError, EOFError):
				print('[-] Connection gone .... bye')
				break
			# except Exception as e:
			# 	print('Ooops:', e)
			# else:
			# 	raise Exception('Joystick: Something bad happened!')

		# clean-up
		sdl2.SDL_JoystickClose(js)
		print('Bye ...')
Exemplo n.º 26
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
Exemplo n.º 27
0
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
joystick = sdl2.SDL_JoystickOpen(0)

# open the connection. Get this string from preferences>bluetooth>NXT>edit serial ports
conn = Connection('/dev/tty.Addy-DevB')  # antons NXT


def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)


while True:
    sdl2.SDL_PumpEvents()

    # read joystick input and normalise it to a range of -100 to 100
    joy_x = (sdl2.SDL_JoystickGetAxis(joystick, 0) - 17268) / 172.68
    joy_y = (sdl2.SDL_JoystickGetAxis(joystick, 1) - 17268) / 172.68

    # use shoulder buttons on the game pad to make the omnibot rotate around it's axis.
    turnpower = 0
    if sdl2.SDL_JoystickGetButton(joystick, 5): turnpower = 75
    if sdl2.SDL_JoystickGetButton(joystick, 4): turnpower = -75

    # convert joystick x and y to a direction and power (deviation from the centre)
    joy_direction = math.atan2(joy_y, joy_x)  # in radians
    joy_power = (joy_x**2 + joy_y**2)**0.5  # pythagoras

    # building a list of three motor commands to send over
    cmds = []
    for i in range(3):
        # for each motor the angle has a different offset (0, 120 and 240 degrees)
Exemplo n.º 28
0
Arquivo: js.py Projeto: DFEC-R2D2/r2d2
    def get(self):
        if not self.valid:
            return None

        js = self.js

        sdl2.SDL_JoystickUpdate()

        ls = Axis(sdl2.SDL_JoystickGetAxis(js, 0),
                  sdl2.SDL_JoystickGetAxis(js, 1))

        rs = Axis(
            sdl2.SDL_JoystickGetAxis(js, 3),  # 2
            sdl2.SDL_JoystickGetAxis(js, 4)  # 5
        )

        triggers = Trigger(
            sdl2.SDL_JoystickGetAxis(js, 2),  # 3
            sdl2.SDL_JoystickGetAxis(js, 5)  # 4
        )

        # shoulder = [
        # 	sdl2.SDL_JoystickGetButton(js, 4),
        # 	sdl2.SDL_JoystickGetButton(js, 5)
        # ]

        # stick = [
        # 	sdl2.SDL_JoystickGetButton(js, 10),
        # 	sdl2.SDL_JoystickGetButton(js, 11)
        # ]

        b = (
            sdl2.SDL_JoystickGetButton(js, 0),  # square
            sdl2.SDL_JoystickGetButton(js, 3),  # triangle
            sdl2.SDL_JoystickGetButton(js, 2),  # circle
            sdl2.SDL_JoystickGetButton(js, 1)  # x
        )

        # print("6", sdl2.SDL_JoystickGetButton(js, 6))  # left trigger T/F
        # print("7", sdl2.SDL_JoystickGetButton(js, 7))  # right trigger T/F
        # for n in [10,11,12]:
        # 	print(n, sdl2.SDL_JoystickGetButton(js, n))
        #
        # b_triggers = (
        # 	sdl2.SDL_JoystickGetButton(js, 6)),
        # 	sdl2.SDL_JoystickGetButton(js, 7)),
        # )

        ps = sdl2.SDL_JoystickGetButton(js, 10)

        lb = (
            sdl2.SDL_JoystickGetButton(js, 4),  # L1
            sdl2.SDL_JoystickGetButton(js, 6),  # L2
            sdl2.SDL_JoystickGetButton(js, 11)  # L3
        )

        rb = (
            sdl2.SDL_JoystickGetButton(js, 5),  # R1
            sdl2.SDL_JoystickGetButton(js, 7),  # R2
            sdl2.SDL_JoystickGetButton(js, 12)  # R3
        )

        hat = sdl2.SDL_JoystickGetHat(js, 0)
        share = sdl2.SDL_JoystickGetButton(js, 8)
        option = sdl2.SDL_JoystickGetButton(js, 9)

        # 'leftStick rightStick triggers leftButtons rightButtons hat buttons option share ps'
        ps4 = PS4(ls, rs, triggers, lb, rb, hat, b, option, share, ps)
        return ps4