Exemple #1
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)
        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)
Exemple #2
0
 def __init__(self, scope, device=0, warnings_enabled=False):
     """
     Parameters:
         scope: microscope client, instance of scope_client.ScopeClient.
         device: the numerical index or string name of the input device (from output of enumerate_devices()).
         warnings_enabled: if True, print debug information to stderr.
     """
     init_sdl()
     self.device, self.device_name, index, self.is_game_controller = open_device(device)
     if self.is_game_controller:
         self.jdevice = sdl2.SDL_GameControllerGetJoystick(self.device)
     else:
         self.jdevice = self.device
     self.device_id = sdl2.SDL_JoystickInstanceID(self.jdevice)
     self.num_axes = sdl2.SDL_JoystickNumAxes(self.jdevice)
     self.num_buttons = sdl2.SDL_JoystickNumButtons(self.jdevice)
     self.num_hats = sdl2.SDL_JoystickNumHats(self.jdevice)
     self.warnings_enabled = warnings_enabled
     self.scope = scope._clone()
     self.event_loop_is_running = False
     self.quit_event_posted = False
     self.throttle_delay_command_time_ratio = 1 - self.MAX_AXIS_COMMAND_WALLCLOCK_TIME_PORTION
     self.throttle_delay_command_time_ratio /= self.MAX_AXIS_COMMAND_WALLCLOCK_TIME_PORTION
     self._axes_throttle_delay_lock = threading.Lock()
     self._c_on_axes_throttle_delay_expired_timer_callback = SDL_TIMER_CALLBACK_TYPE(self._on_axes_throttle_delay_expired_timer_callback)
     self.handle_button_callback = None
Exemple #3
0
    def __init__(self):
        # init SDL2 and grab joystick
        sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
        self.js = sdl2.SDL_JoystickOpen(0)

        # grab info for display
        a = sdl2.SDL_JoystickNumAxes(self.js)
        b = sdl2.SDL_JoystickNumButtons(self.js)
        h = sdl2.SDL_JoystickNumHats(self.js)

        if a == -1:
            print('*** No Joystick found ***')
            self.valid = False
        else:
            print('==========================================')
            print(' PS4 Joystick ')
            print('   axes:', a, 'buttons:', b, 'hats:', h)
            print('==========================================')
            self.valid = True

        self.ps4 = {
            'num_axes': a,
            'num_buttons': b,
            'num_hats': h,
            'leftStick': [0, 0],
            'rightStick': [0, 0]
        }
Exemple #4
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
    def _init_hats(self):
        """Initializes the hats of the joystick.

        :return list of JoystickWrapper.Hat objects
        """
        hats = []
        for i in range(sdl2.SDL_JoystickNumHats(self._joystick)):
            hats.append(JoystickWrapper.Hat(self._joystick, i))
        return hats
Exemple #6
0
    def __init__(self):
        # init SDL2 and grab joystick
        sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
        self.js = sdl2.SDL_JoystickOpen(0)

        # grab info for display
        self.numAxes = sdl2.SDL_JoystickNumAxes(self.js)
        self.numButtons = sdl2.SDL_JoystickNumButtons(self.js)
        self.numHats = sdl2.SDL_JoystickNumHats(self.js)

        if self.numAxes <= 0:
            print('*** No Joystick found ***')
            self.valid = False
        else:
            self.valid = True
Exemple #7
0
	def __init__(self, host, port):
		self.pub = zmq.Pub((host, port))

		# init SDL2 and grab joystick
		sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
		self.js = sdl2.SDL_JoystickOpen(0)

		# grab info for display
		a = sdl2.SDL_JoystickNumAxes(self.js)
		b = sdl2.SDL_JoystickNumButtons(self.js)
		h = sdl2.SDL_JoystickNumHats(self.js)

		print('==========================================')
		print(' Joystick ')
		print('   axes:', a, 'buttons:', b, 'hats:', h)
		print('   publishing: {}:{}'.format(host, port))
		print('==========================================')
Exemple #8
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
Exemple #9
0
    def __init__(self):
        # init SDL2 and grab joystick
        sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
        self.js = sdl2.SDL_JoystickOpen(0)

        # grab info for display
        a = sdl2.SDL_JoystickNumAxes(self.js)
        b = sdl2.SDL_JoystickNumButtons(self.js)
        h = sdl2.SDL_JoystickNumHats(self.js)

        if a == -1:
            print('*** No Joystick found ***')
            self.valid = False
        else:
            print('==========================================')
            print(' PS4 Joystick ')
            print('   axes:', a)
            print('   buttons:', b)
            print('   hats:', h)
            print('==========================================')
            self.valid = True
Exemple #10
0
    def __init__(self, net, topic='cmd'):
        # mp.Process.__init__(self)
        self.pub = zmq.Pub(net)
        self.topic = topic

        # init SDL2 and grab joystick
        sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)
        self.js = sdl2.SDL_JoystickOpen(0)

        # grab info for display
        a = sdl2.SDL_JoystickNumAxes(self.js)
        b = sdl2.SDL_JoystickNumButtons(self.js)
        h = sdl2.SDL_JoystickNumHats(self.js)

        self.old_twist = Msg.Twist()

        print('==========================================')
        print(' Joystick ')
        print('   axes:', a, 'buttons:', b, 'hats:', h)
        print('   publishing: {}:{}'.format(net[0], net[1], topic))
        print('==========================================')
Exemple #11
0
    if joy is None:
        print("Joystick device at {} is invalid.".format(i))
    else:
        name_object = sdl2.SDL_JoystickName(joy)
        if name_object is None:
            name = "Unknown device"
            print("Encountered an invalid device name")
        else:
            name = name_object.decode("utf-8")
        hardware_id = struct.unpack(">4I", sdl2.SDL_JoystickGetGUID(joy))[0]
        windows_id = sdl2.SDL_JoystickInstanceID(joy)
        hardware_id = struct.unpack(">4I", sdl2.SDL_JoystickGetGUID(joy))[0]
        windows_id = sdl2.SDL_JoystickInstanceID(joy)
        axes = sdl2.SDL_JoystickNumAxes(joy)
        buttons = sdl2.SDL_JoystickNumButtons(joy)
        hats = sdl2.SDL_JoystickNumHats(joy)

        joystick = {
            "Name": name,
            "Res Name": None,
            "SCXML ID": None,
            "JGXML ID": None,
            "JGPYCON ID": None,
            "HW ID": hardware_id,
            "Win ID": windows_id,
            "Axes": axes,
            "Buttons": buttons,
            "Hats": hats,
            "Obj": joy,
        }
        joysticks.append(joystick)
Exemple #12
0
    print '    Y:',pro['Y']
    print '    X:',pro['X']
    print '    A:',pro['A']
    print '    B:',pro['B']
    print '---'
    print '  hat:',pro['hat']

# init stuff
sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)

js = sdl2.SDL_JoystickOpen(0)

# grab info
a = sdl2.SDL_JoystickNumAxes(js)
b = sdl2.SDL_JoystickNumButtons(js)
h = sdl2.SDL_JoystickNumHats(js)
print 'axes:',a,'buttons:',b,'hats:',h
# exit()
# Data structure holding the PRO info
pro = {
    'la': {'x': 0, 'y': 0},  # left axis
    'ra': {'x': 0, 'y': 0},
    'lt1': 0, # left trigger 1
    'rt1': 0,
    'lt2': 0, # left trigger 2
    'rt2': 0,
    'A': 0,  
    'X': 0,   
    'Y': 0,
    'B': 0,
    'hat': 0,
Exemple #13
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
Exemple #14
0
    def __init__(
            self,
            input_device_index=0,
            input_device_name=None,
            scope_server_host='127.0.0.1',
            zmq_context=None,
            maximum_portion_of_wallclock_time_allowed_for_axis_commands=DEFAULT_MAX_AXIS_COMMAND_WALLCLOCK_TIME_PORTION,
            maximum_axis_command_cool_off=DEFAULT_MAX_AXIS_COMMAND_COOL_OFF,
            warnings_enabled=False):
        """* input_device_index: The argument passed to SDL_JoystickOpen(index) or SDL_GameControllerOpen(index).
        Ignored if the value of input_device_name is not None.
        * input_device_name: If specified, input_device_name should be the exact string or UTF8-encoded bytearray by
        which SDL identifies the controller you wish to use, as reported by SDL_JoystickName(..).  For USB devices,
        this is USB iManufacturer + ' ' + iProduct.  (See example below.)
        * scope_server_host: IP address or hostname of scope server.
        * zmq_context: If None, one is created.
        * maximum_portion_of_wallclock_time_allowed_for_axis_commands: Limit the rate at which commands are sent to
        the scope in response to controller axis motion such that the scope such that the scope is busy processing
        those commands no more
        than this fraction of the time.
        * maximum_axis_command_cool_off: The maximum number of milliseconds to defer issuance of scope commands in
        response to controller axis motion (in order to enforce
        maximum_portion_of_wallclock_time_allowed_for_axis_commands).

        For example, a Sony PS4 controller with the following lsusb -v output would be known to SDL as 'Sony Computer
        Entertainment Wireless Controller':

        Bus 003 Device 041: ID 054c:05c4 Sony Corp.
        Device Descriptor:
          bLength                18
          bDescriptorType         1
          bcdUSB               2.00
          bDeviceClass            0
          bDeviceSubClass         0
          bDeviceProtocol         0
          bMaxPacketSize0        64
          idVendor           0x054c Sony Corp.
          idProduct          0x05c4
          bcdDevice            1.00
          iManufacturer           1 Sony Computer Entertainment
          iProduct                2 Wireless Controller
          iSerial                 0
          bNumConfigurations      1
        ...

        Additionally, sdl_control.enumerate_devices(), a module function, returns a list of the currently available
        SDL joystick and game controller input devices, in the order by which SDL knows them.  So, if you know that
        your input device is a Logilech something-or-other, and sdl_control.enumerate_devices() returns the following:
        [
            'Nintenbo Olympic Sport Mat v3.5',
            'MANUFACTURER NAME HERE. DONT FORGET TO SET THIS!!     Many Product Ltd. 1132 Guangzhou    $  !*llSN9_Q   ',
            'Duckhunt Defender Scanline-Detecting Plastic Gun That Sadly Does Not Work With LCDs',
            'Macrosoft ZBox-720 Controller Colossal-Hands Mondo Edition',
            'Logilech SixThousandAxis KiloButtonPad With Haptic Feedback Explosion',
            'Gametech Gameseries MegaGamer Excel Spreadsheet 3D-Orb For Executives, Doom3D Edition',
            'Gametech Gameseries MegaGamer Excel Spreadsheet 3D-Orb For Light Rail Transport, Doom3D Edition'
        ]
        You will therefore want to specify input_device_index=4 or
        input_device_name='Logilech SixThousandAxis KiloButtonPad With Haptic Feedback Explosion'
        """
        assert 0 < maximum_portion_of_wallclock_time_allowed_for_axis_commands <= 1
        init_sdl()
        self.device, self.device_is_game_controller = open_device(
            input_device_index, input_device_name)
        if self.device_is_game_controller:
            self.jdevice = sdl2.SDL_GameControllerGetJoystick(self.device)
        else:
            self.jdevice = self.device
        self.device_id = sdl2.SDL_JoystickInstanceID(self.jdevice)
        self.num_axes = sdl2.SDL_JoystickNumAxes(self.jdevice)
        self.num_buttons = sdl2.SDL_JoystickNumButtons(self.jdevice)
        self.num_hats = sdl2.SDL_JoystickNumHats(self.jdevice)
        self.warnings_enabled = warnings_enabled
        if warnings_enabled:
            print('JoypadInput is connecting to scope server...',
                  file=sys.stderr)
        self.scope, self.scope_properties = scope_client.client_main(
            scope_server_host, zmq_context)
        if warnings_enabled:
            print('JoypadInput successfully connected to scope server.',
                  file=sys.stderr)
        self.event_loop_is_running = False
        self.quit_event_posted = False
        self.throttle_delay_command_time_ratio = 1 - maximum_portion_of_wallclock_time_allowed_for_axis_commands
        self.throttle_delay_command_time_ratio /= maximum_portion_of_wallclock_time_allowed_for_axis_commands
        self.maximum_axis_command_cool_off = maximum_axis_command_cool_off
        self._axes_throttle_delay_lock = threading.Lock()
        self._c_on_axes_throttle_delay_expired_timer_callback = SDL_TIMER_CALLBACK_TYPE(
            self._on_axes_throttle_delay_expired_timer_callback)
        self.handle_button_callback = self.default_handle_button_callback