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
def controller_states(controller_id): sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER) controller = get_controller(controller_id) try: print('Using "{:s}" for input.'.format( sdl2.SDL_JoystickName(sdl2.SDL_GameControllerGetJoystick(controller)).decode('utf8'))) except AttributeError: print('Using controller {:s} for input.'.format(controller_id)) while True: elaped_time = dt.datetime.now().timestamp() - start_dttm buttons = sum([sdl2.SDL_GameControllerGetButton(controller, b) << n for n, b in enumerate(buttonmapping)]) buttons |= (abs(sdl2.SDL_GameControllerGetAxis(controller, sdl2.SDL_CONTROLLER_AXIS_TRIGGERLEFT)) > trigger_deadzone) << 6 buttons |= (abs(sdl2.SDL_GameControllerGetAxis(controller, sdl2.SDL_CONTROLLER_AXIS_TRIGGERRIGHT)) > trigger_deadzone) << 7 hat = hatcodes[sum([sdl2.SDL_GameControllerGetButton(controller, b) << n for n, b in enumerate(hatmapping)])] rawaxis = [sdl2.SDL_GameControllerGetAxis(controller, n) for n in axismapping] axis = [((0 if abs(x) < axis_deadzone else x) >> 8) + 128 for x in rawaxis] rawbytes = struct.pack('>BHBBBB', hat, buttons, *axis) message_stamp = ControllerStateTime(rawbytes, elaped_time) yield message_stamp
def __init__(self, controller_id, axis_deadzone=10000, trigger_deadzone=0): # Make sure we get joystick events even if in window mode and not focused. sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1") sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER) # Mapping for X-box S Controller sdl2.SDL_GameControllerAddMapping( b"030000005e0400008902000021010000,Classic XBOX Controller," b"a:b0,b:b1,y:b4,x:b3,start:b7,guide:,back:b6,leftstick:b8," b"rightstick:b9,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2," b"leftx:a0,lefty:a1,rightx:a3,righty:a4,lefttrigger:a2," b"righttrigger:a5,leftshoulder:b5,rightshoulder:b2,") # Mapping for 8bitdo sdl2.SDL_GameControllerAddMapping( b"05000000c82d00002038000000010000,8Bitdo NES30 Pro," b"a:b1,b:b0,back:b10,dpdown:h0.4,dpleft:h0.8," b"dpright:h0.2,dpup:h0.1,guide:b2,leftshoulder:b6," b"leftstick:b13,lefttrigger:a5,leftx:a0,lefty:a1," b"rightshoulder:b7,rightstick:b14,righttrigger:a4," b"rightx:a2,righty:a3,start:b11,x:b4,y:b3,platform:Linux,") self.controller = None self.name = 'controller {:s}'.format(controller_id) self.which = None try: n = int(controller_id, 10) if n < sdl2.SDL_NumJoysticks(): self.controller = sdl2.SDL_GameControllerOpen(n) self.which = n except ValueError: for n in range(sdl2.SDL_NumJoysticks()): name = sdl2.SDL_JoystickNameForIndex(n) if name is not None: name = name.decode('utf8') if name == controller_id: self.controller = sdl2.SDL_GameControllerOpen(n) self.which = n if self.controller is None: raise Exception('Controller not found: {:s}'.format(controller_id)) try: self.name = sdl2.SDL_JoystickName( sdl2.SDL_GameControllerGetJoystick( self.controller)).decode('utf8') except AttributeError: pass logger.info('Using {:s} for input.'.format(self.name)) self.axis_deadzone = axis_deadzone self.trigger_deadzone = trigger_deadzone self.previous_state = State()
def __init__(self, sdl_controller_id): self.sdl_controller_id = sdl_controller_id self.sdl_controller = sdl2.SDL_GameControllerOpen(sdl_controller_id) self.sdl_joy = sdl2.SDL_GameControllerGetJoystick(self.sdl_controller) self.sdl_joy_id = sdl2.SDL_JoystickInstanceID(self.sdl_joy) guid = sdl2.SDL_JoystickGetDeviceGUID(self.sdl_joy_id) logging.log(logging.INFO, "Joystick GUID: %s " % guid) logging.log( logging.INFO, "Mapping: %s" % sdl2.SDL_GameControllerMappingForGUID(guid))
def __init__(self, joystick_index): self.game_controller = None self.joystick = None self.joystick_id = None if sdl2.SDL_IsGameController(joystick_index): self.game_controller = sdl2.SDL_GameControllerOpen(joystick_index) self.joystick = sdl2.SDL_GameControllerGetJoystick( self.game_controller) self.joystick_id = sdl2.SDL_JoystickInstanceID(self.joystick) self.name = sdl2.SDL_GameControllerName(self.game_controller) else: self.joystick = sdl2.SDL_JoystickOpen(joystick_index) self.joystick_id = sdl2.SDL_JoystickInstanceID(self.joystick) self.name = sdl2.SDL_JoystickName(self.joystick)
def open(self, device_index): self._sdl_controller = sdl2.SDL_GameControllerOpen(device_index) self._sdl_joystick = sdl2.SDL_GameControllerGetJoystick(self._sdl_controller) self._sdl_joystick_id = sdl2.SDL_JoystickInstanceID(self._sdl_joystick) self._controller_name = sdl2.SDL_JoystickName(self._sdl_joystick) self._num_axis = sdl2.SDL_JoystickNumAxes(self._sdl_joystick), self._num_buttons = sdl2.SDL_JoystickNumButtons(self._sdl_joystick) self._num_balls = sdl2.SDL_JoystickNumBalls(self._sdl_joystick) for btn_index in range(0, self.MAX_BUTTONS): self._button_down[btn_index] = 0 self._button_pressed[btn_index] = 0 self._button_released[btn_index] = 0 if self._sdl_joystick_id != -1: self._connected = True
def __init__(self, controller_id: int, **kwargs): self.ser = serial.Serial(**kwargs) sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER) self.controller = sdl2.SDL_GameControllerOpen(int(controller_id)) try: print('Using "{:s}" for input.'.format( sdl2.SDL_JoystickName( sdl2.SDL_GameControllerGetJoystick( self.controller)).decode('utf8'))) except AttributeError: print(f'Using controller {controller_id} for input.') self.input_stack = [] self.recording = None self.start_dttm = None self.prev_msg_stamp = None
def dump_input(device): init_sdl() device, name, index, is_game_controller = open_device(device) device_id = sdl2.SDL_JoystickInstanceID(sdl2.SDL_GameControllerGetJoystick(device) if is_game_controller else device) if is_game_controller: controller_name = sdl2.SDL_GameControllerName(device).decode('utf-8') print('Opened game controller, c_name "{}", j_name "{}", idx {}, j_id {}'.format(controller_name, name, index, device_id)) else: print('Opened joystick, j_name "{}", idx {}, j_id {}'.format(name, index, device_id)) def on_joydeviceaddedevent(event): return 'idx: {} j_name: {}'.format(event.jdevice.which, sdl2.SDL_JoystickNameForIndex(event.jdevice.which).decode('utf-8')) def on_joydeviceremovedevent(event): return 'j_id: {}'.format(event.jdevice.which) def on_joyaxismotionevent(event): return 'j_id: {} axis: {} pos: {}'.format(event.jaxis.which, event.jaxis.axis, event.jaxis.value) def on_joyballmotionevent(event): return 'j_id: {} ball: {} xdelta: {} ydelta: {}'.format(event.jball.which, event.jball.ball, event.jball.xrel, event.jball.yrel) def on_joyhatmotionevent(event): return 'j_id: {} hat: {} pos: {}'.format(event.jhat.which, event.jhat.hat, SDL_HAT_DIRECTION_NAMES.get(event.jhat.value, event.jhat.value)) def on_joybuttonevent(event): return 'j_id: {} button: {} state: {}'.format( event.jbutton.which, event.jbutton.button, 'is_pressed' if bool(event.jbutton.state) else 'is_not_pressed' ) def on_controllerdeviceaddedevent(event): return 'idx: {} c_name: {}'.format(event.cdevice.which, sdl2.SDL_GameControllerNameForIndex(event.cdevice.which).decode('utf-8')) def on_controllerdeviceremovedevent(event): return 'c_id: {}'.format(event.cdevice.which) def on_controlleraxismotionevent(event): return 'c_id: {} axis: {} pos: {}'.format( event.caxis.which, SDL_CONTROLLER_AXIS_NAMES.get(event.caxis.axis, event.caxis.axis), event.caxis.value ) def on_controllerbuttonevent(event): return 'c_id: {} button: {} state: {}'.format( event.cbutton.which, SDL_CONTROLLER_BUTTON_NAMES.get(event.cbutton.button, event.cbutton.button), 'is_pressed' if bool(event.cbutton.state) else 'is_not_pressed' ) event_handlers = { sdl2.SDL_JOYDEVICEADDED: on_joydeviceaddedevent, sdl2.SDL_JOYDEVICEREMOVED: on_joydeviceremovedevent, sdl2.SDL_JOYAXISMOTION: on_joyaxismotionevent, sdl2.SDL_JOYBALLMOTION: on_joyballmotionevent, sdl2.SDL_JOYHATMOTION: on_joyhatmotionevent, sdl2.SDL_JOYBUTTONDOWN: on_joybuttonevent, sdl2.SDL_JOYBUTTONUP: on_joybuttonevent, sdl2.SDL_CONTROLLERDEVICEADDED: on_controllerdeviceaddedevent, sdl2.SDL_CONTROLLERDEVICEREMOVED: on_controllerdeviceremovedevent, sdl2.SDL_CONTROLLERAXISMOTION: on_controlleraxismotionevent, sdl2.SDL_CONTROLLERBUTTONDOWN: on_controllerbuttonevent, sdl2.SDL_CONTROLLERBUTTONUP: on_controllerbuttonevent } print('# milliseconds since SDL initialization, SDL_EventType, some event-type-specific information (not necessarily exhaustive)') try: while 1: event = sdl2.SDL_Event() # If there is no event for an entire second, we iterate, giving CPython an opportunity to # raise KeyboardInterrupt. if sdl2.SDL_WaitEventTimeout(ctypes.byref(event), 1000): if hasattr(event, 'generic'): s = '{}, {}'.format(event.generic.timestamp, SDL_EVENT_NAMES.get(event.type, "UNKNOWN")) else: s = '{}, {}'.format(event.common.timestamp, SDL_EVENT_NAMES.get(event.type, "UNKNOWN")) try: s += ', {}'.format(event_handlers[event.type](event)) except KeyError: pass print(s) if event.type == sdl2.SDL_QUIT: print('# SDL_QUIT received. Exiting dump_input(..) ...') break if event.type == sdl2.SDL_JOYDEVICEREMOVED and event.jdevice.which == device_id: print('# Our SDL input device has been disconnected. Exiting dump_input(..) ...') break except KeyboardInterrupt: print('\n# ctrl-c received. Exiting dump_input(..) ...')
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