def __init__(self, joystick_number=JOYSTICK_NUMBER): """ Makes a new joystick instance. :param joystick_number: use if there is more than one joystick :returns: the instance :raises RuntimeWarning if no joystick is found or it is unknown type """ self.joy: Optional[joystick.Joystick] = None self.numAxes: Optional[int] = None self.numButtons: Optional[int] = None self.axes = None self.buttons = None self.name: Optional[str] = None self.joystick_number: int = joystick_number self.lastTime = 0 self.lastActive = 0 self.run_user_model_pressed = False # only used to log changes to/from running user model self._rev_was_pressed = False # to go to reverse mode or toggle out of it self._auto_was_pressed = False # to toggle out of autodrive if we pressed Y on joy to enter it joystick.init() count = joystick.get_count() if count < 1: raise RuntimeWarning('no joystick(s) found') self.platform = platform.system() self.lastActive = time.time() try: self.joy = joystick.Joystick(self.joystick_number) except: if self.platform == 'Linux': # Linux list joysticks from 3 to 0 instead of 0 to 3 if self.joystick_number == 0: self.joy = joystick.Joystick(3) else: self.joy = joystick.Joystick(4 - self.joystick_number) self.joy.init() self.numAxes = self.joy.get_numaxes() self.numButtons = self.joy.get_numbuttons() self.name = self.joy.get_name() logger.info(f'joystick is named "{self.name}"') if not self.name == my_joystick.XBOX_ONE_BLUETOOTH_JOYSTICK \ and not self.name == my_joystick.XBOX_360_WIRELESS_RECEIVER \ and not self.name == my_joystick.XBOX_ELITE \ and not self.name == my_joystick.XBOX_WIRED \ and not self.name == my_joystick.PS4_WIRELESS_CONTROLLER \ and not self.name == my_joystick.PS4_DUALSHOCK4: logger.warning('Name: {}'.format(self.name)) logger.warning( 'Unknown joystick type {} found.' 'Add code to correctly map inputs by running my_joystick as main' .format(self.name)) raise RuntimeWarning('unknown joystick type "{}" found'.format( self.name)) logger.debug( 'joystick named "{}" found with {} axes and {} buttons'.format( self.name, self.numAxes, self.numButtons))
def main(argv=[]): display.init() joystick.init() if len(argv) > 1: for sz in argv[1:]: try: joystick.Joystick(int(sz)).init() except: pass else: for i in xrange(joystick.get_count()): joystick.Joystick(i).init() e = event.wait() while e.type != QUIT: if e.type == JOYAXISMOTION: print 'js', e.joy, 'axis', e.axis, round(e.value, P) elif e.type == JOYBALLMOTION: print 'js', e.joy, 'ball', e.ball, round(e.rel, P) elif e.type == JOYHATMOTION: print 'js', e.joy, 'hat', e.hat, h[e.value] elif e.type == JOYBUTTONUP: print 'js', e.joy, 'button', e.button, 'up' elif e.type == JOYBUTTONDOWN: print 'js', e.joy, 'button', e.button, 'down' e = event.wait()
def __init__(self): try: PJ.init() # initializes PJ module, NOT joystick itself self.names = [] self.joystick = PJ.Joystick(0) self.joystick.init() ##assuming just 1 joystick self.names.append(PJ.Joystick(0).get_name()) #A is attack (space) #B is pick up (s) #x is set trap (a) #y is drop (d) #r is eat (e) self.buttons = [ False for i in range(self.joystick.get_numbuttons()) ] ##test self.axishats = [False, False, False] # axis 0, 1; hat 0 self.button_pos = [(216, 74), (236, 92), (255, 74), (236, 56), (608, 88), (476, 104), (606, 118), (476, 136), (134, 56), (188, 56)] # self.buttons = ['up', 'down', 'left', 'right', 'start', 'attack', 'pickup', 'settrap', 'drop', 'eat'] # self.key_map = { # PG.K_UP : 'up', # PG.K_DOWN : 'down', # PG.K_LEFT : 'left', # PG.K_RIGHT : 'right', # PG.K_RETURN : 'start', # PG.K_a : 'attack', # PG.K_b : 'pickup', # PG.K_x : 'settrap', # PG.K_y : 'drop', # PG.K_l : 'eat' # } self.keys_pressed = {} for button in self.buttons: self.keys_pressed[button] = False self.joystick_config = {} self.quit_attempt = False except PG.error, err: pass
def __init__(self, logger: object, idx: int, name: str, ndigit: int = 2) -> None: """ Constructor. Params: dispatcher: The application event dispatcher. logger: The application logger. idx: The index of the controller from 0 to pygame.joystick.get_count(). name: The controller name. ndigit: The digit number for the axis precision. Default: 2. """ self._logger = logger.getLogger(f"CTRL_{idx}") self._idx = idx self._ndigit = ndigit self._isCalibrated = False self._logger.info(f"creating controller {name}") self._joystick = joystick.Joystick(idx) self._joystick.init() filename = f"{name.lower().replace(' ', '_')}.json" configFilePath = os.path.join(self.CONFIG_ROOT_DIR, filename) with open(configFilePath) as configFile: self._config = json.load(configFile)
def set_parameters(self, params): """Set joystick and its axes""" if self.i_j != params.i_j and \ params.i_j < joystick.get_count() and \ params.i_j >= 0: self.i_j = params.i_j self.joystick.quit() self.joystick = joystick.Joystick(self.i_j) self.joystick.init() if self.i_x != params.i_x and \ params.i_x < self.joystick.get_numaxes() and \ params.i_x >= 0: self.i_x = params.i_x if self.i_y != params.i_y and \ params.i_y < self.joystick.get_numaxes() and \ params.i_y >= 0 and \ params.i_y != self.i_x: self.i_y = params.i_y if self.i_x == self.i_y: if self.i_x + 1 >= self.joystick.get_numaxes(): self.i_y = self.i_x - 1 else: self.i_y = self.i_x + 1 self.inv_x = params.inv_x self.inv_y = params.inv_y
def __init__(self, id=0, deadzone=.2): ''' Creats controller object ''' display.init() joystick.init() self.joystick = joystick.Joystick(id) self.joystick.init() self.deadzone = deadzone # Controller Pressed Values self.A = 0 self.B = 0 self.X = 0 self.Y = 0 self.LB = 0 self.RB = 0 self.SELECT = 0 self.START = 0 self.XBOX = 0 self.LS = 0 self.RS = 0 self.LX = 0 self.LY = 0 self.LT = 0 self.RT = 0 self.RX = 0 self.RY = 0 self.DX = 0 self.DY = 0
def create_gamepad(device_index): stick = joystick.Joystick(device_index) instance = stick.get_instance_id() if instance in controllers: print("Duplicate", instance) return group = w2d.Group([ scene.layers[0].add_sprite('gamepad_base'), scene.layers[0].add_sprite( 'stick', pos=LSTICK_CENTER), scene.layers[0].add_sprite( 'stick', pos=RSTICK_CENTER), scene.layers[0].add_sprite( 'button', pos=(72, -19)), scene.layers[0].add_sprite( 'button', pos=(89, -36)), scene.layers[0].add_sprite( 'button', pos=(56, -36)), scene.layers[0].add_sprite('button', pos=(72, -52)), scene.layers[0].add_label(stick.get_name(), pos=(0, 80), color='black', fontsize=14, align="center") ], pos=(midline, len(controllers) * 200 + 100), scale=0.01) for button, color in zip(group[3:7], colors): button.color = darker(color) button.on_color = color w2d.animate(group, tween="out_elastic", scale=1.0) controllers[stick.get_instance_id()] = (stick, group)
def __init__(self): self.world = b2World(gravity=(0, 0)) for x, y, ex, ey in ( #50x80 field with 4 static objects (walls) TODO add 2; locations are in (cx,cy,w/2,h/2) (-27.5, 0, .5, 13.5), (27.5, 0, .5, 13.5), (0, -14, 27, .5), (0, 14, 27, .5), ): body = self.world.CreateStaticBody( position=(x, y), shapes=b2PolygonShape(box=(ex, ey)), ) #friction .2 self.robot = self.world.CreateDynamicBody(position=(-20, 0)) box = self.robot.CreatePolygonFixture( box=(3, 3), density=100, friction=.7 ) #TODO use right parameters; 100 kg? 3'x3f; friction does NOTHING for now self.robot.linearDamping = .7 self.robot.angularDamping = 1.4 self.joy = None if joystick.get_count() < 1: print "warning: no joystick" self.joy = None else: self.joy = joystick.Joystick(0) self.joy.init() print "joystick", self.joy.get_name()
def on_start(self): "Initialize joysticks" self.joystick = [] for x in range(joystick.get_count()): j = joystick.Joystick(x) j.init() if self.test_mode: print 'Joystick_Input enabled joystick #' + str(x) + \ ': ' + j.get_name() self.joystick.append(j) if not joystick.get_count(): if self.test_mode: print 'Joystick_Input: No Joysticks to Initialize' if self.test_mode: # create a mini component because we don't want to slow down # joystick response unless we're in test_mode class Joystick_Test_Component(Component): @component_method def handle_joybuttondown(self, event): print event @component_method def handle_joybuttonup(self, event): print event @component_method def handle_joyaxismotion(self, event): print event self.owner.components.add(Joystick_Test_Component())
def __init__(self, arbalet, runtime_control): """ Simple event manager duplicating the pygame events for the system (runtime hardware management) and the user (game control) The get() method and the system-reserved _get() both poll the pygame event list to keep the list up-to-date and also avoid the pygame internal queue to be full TODO: events pygame/touch to be merged into a unique format :param enable_system_events: enable the acquisition of system events, must be False if no Arbalink polls the system event queue :return: """ Thread.__init__(self) self.setDaemon(True) self._system_events = [] self._user_events = [] self._user_events_lock = RLock() self._arbalet = arbalet self._rate = Rate(self._arbalet.config['refresh_rate']) self._runtime_control = runtime_control self.running = False # All joysticks are enabled by default with self._arbalet.sdl_lock: display.init() joystick.init() for j in range(joystick.get_count()): joy = joystick.Joystick(j) joy.init() self.start()
def run(self): count = 0 TCP_IP = '192.168.1.7' TCP_PORT = 5005 BUFFER_SIZE = 1024 self.transmit = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.transmit.connect((TCP_IP, TCP_PORT)) joystick.init() pygame.display.init() if pygame.joystick.get_count() == 0: self.changeText.emit("No joystick detected") exit(0) self.j = joystick.Joystick(0) self.j.init() adx = 'a' ady = 'b' switch = True active = True try: while (1): pygame.event.pump() #self.changeText.emit(self.transmit.recv(1024)) on = self.j.get_button(1) if on: sleep(0.2) if self.j.get_button(1): if active == True: active = False self.changeText.emit('Idle') else: active = True self.changeText.emit('Active') if active: change = self.j.get_button(0) if change: sleep(0.2) if self.j.get_button(0): if switch == True: switch = False self.changeText.emit('Arm') else: switch = True self.changeText.emit('Motor') if switch: self.motorcode() else: self.arm() except KeyboardInterrupt: self.transmit.send('m4x4999y4999z')
def pygame(self): # obsolete, lags maybe due to graphical stuff needed from os import environ environ["SDL_VIDEODRIVER"] = "dummy" # no window needed from pygame import init, joystick, display init() display.set_mode((1,1)) # starts a mini widow joystick.init() count = joystick.get_count() for jno in range(0,count): # initialize them all js = joystick.Joystick(jno) js.init() # assign to multi player interfaces from pygame.event import get from pygame.locals import JOYAXISMOTION, JOYHATMOTION, JOYBUTTONDOWN, JOYBUTTONUP, QUIT self.running = True while self.running: for event in get(): if QUIT == event.type: self.kill() elif hasattr(event,'joy'): # not a gamepad interface = self.interfaces[event.joy] # stick actions # 0 == left stick x # 1 == left stick y # 2 == right stick x # 3 == right stick y # 5 == l2m # 4 == r2m if JOYAXISMOTION == event.type: # 7 self.running = interface.handler(event.type*10+event.axis,event.value) # cross actions # (-1,0) == left # ( 1,0) == right # (0, 1) == up # (0,-1) == down elif JOYHATMOTION == event.type: # 9 if((-1,0)== event.value):self.running = interface.handler(90,1) elif((1,0)== event.value):self.running = interface.handler(91,1) elif((0,-1)== event.value):self.running = interface.handler(92,1) elif((0,1)== event.value):self.running = interface.handler(93,1) else:self.running = interface.handler(94,0) # button actions # 0 == a # 1 == b # 3 == x # 4 == y # 6 == l1 # 7 == r1 # 8 == l2b # 9 == r2b # 10 == select # 11 == start # 13 == l3 # 14 == r3 elif JOYBUTTONUP == event.type: # 11 no value ! self.running = interface.handler(100+event.button,0) elif JOYBUTTONDOWN == event.type: # 10 no value ! self.running = interface.handler(100+event.button,1) self.display.quit()
def restart(): global joy_in, joystick_count joystick.init() joystick_count = joystick.get_count() if joystick_count > 0: joy_in = joystick.Joystick(0) joy_in.init()
def __init__(self, joystick_number=JOYSTICK_NUMBER): """ Makes a new joystick instance. :param joystick_number: use if there is more than one joystick :returns: the instance :raises RuntimeWarning if no joystick is found or it is unknown type """ self.joy:Optional[joystick.Joystick]=None self.car_command:car_command=car_command() self.user_input:user_input = user_input() self.default_car_command=car_command() self.default_user_input=user_input() self.numAxes:Optional[int]=None self.numButtons:Optional[int]=None self.axes=None self.buttons=None self.name:Optional[str]=None self.joystick_number:int=joystick_number self.lastTime = 0 self.lastActive = 0 self._rev_was_pressed=False # to go to reverse mode or toggle out of it joystick.init() count = joystick.get_count() if count<1: raise RuntimeWarning('no joystick(s) found') self.lastActive=time.time() if platform.system() == 'Linux': if self.joystick_number == 0: self.joy = joystick.Joystick(3) # TODO why? else: self.joy = joystick.Joystick(4 - self.joystick_number) # TODO why is this cryptic code needed? What does it do? else: self.joy = joystick.Joystick(self.joystick_number) self.joy.init() self.numAxes = self.joy.get_numaxes() self.numButtons = self.joy.get_numbuttons() self.name=self.joy.get_name() if not self.name==my_joystick.XBOX_ONE_BLUETOOTH_JOYSTICK and not self.name==my_joystick.XBOX_ELITE and not self.name==my_joystick.XBOX_WIRED: logger.warning('Name: {}'.format(self.name)) logger.warning('unknown joystick type {} found: add code to correctly map inputs by running my_joystick as main'.format(self.name)) raise RuntimeWarning('unknown joystick type {} found'.format(self.name)) logger.info('joystick named "{}" found with {} axes and {} buttons'.format(self.name, self.numAxes, self.numButtons))
def init_joystick(self): JoystickMgrBase.init_joystick(self) pygame.init() joystick.init() self.joysticks = [ joystick.Joystick(idx) for idx in range(joystick.get_count()) ] map(lambda joystick: joystick.init(), self.joysticks) eng.attach_obs(self.on_frame)
def __init__(self, id=0): if not joystick.get_init(): joystick.init() self.pygame_js = joystick.Joystick(id) self.pygame_js.init() # initialize all the buttons to False for i in range(self.pygame_js.get_numbuttons()): self.buttons[i] = Button(i, self.pygame_js.get_button)
def __init__(self): ''' Constructor ''' pygame.init() # Initialise all joysticks. for j in range(0, joystick.get_count()): stick = joystick.Joystick(j) stick.init() # Pre-fill _last_button_state with 0 self._last_button_state = [[ False for b in range(joystick.Joystick(j).get_numbuttons()) ] for j in range(joystick.get_count())] self._last_button_time = [[ 0 for b in range(joystick.Joystick(j).get_numbuttons()) ] for j in range(joystick.get_count())] QtCore.QThread.__init__(self) # Are we exiting the loop? self._exiting = False
def __init__(self, jnum): self.jnum = jnum self.j = joystick.Joystick(jnum) self.j.init() if self.j.get_numaxes() == 5: self.type = "XBOX" elif self.j.get_numaxes() == 4: self.type = "PS2" else: self.type = "CHEAP"
def app(list_joysticks, list_bluetooth, joy, device): if list_joysticks: joystick.init() print('Joysticks:') for i in range(joystick.get_count()): j = joystick.Joystick(i) print(j.get_id(), j.get_name()) if list_bluetooth: ble = Adafruit_BluefruitLE.get_provider() ble.initialize() ble.run_mainloop_with(lambda: list_bluetooth_devices(ble)) if device is not None: ble = Adafruit_BluefruitLE.get_provider() ble.initialize() ble.run_mainloop_with(lambda: get_device(ble, device)) return bluetooth = get_device(ble, device) bluetooth.connect() atexit.register(bluetooth.disconnect) UART.discover(bluetooth) uart = UART(bluetooth) if joy is not None: os.environ['SDL_VIDEODRIVER'] = 'dummy' pygame.init() joystick.init() j = joystick.Joystick(joy) j.init() print('Axes:', j.get_numaxes()) while True: pygame.event.get() for i in range(j.get_numaxes()): if bluetooth and uart: uart.write('{}{}\n'.format(i, j.get_axis(i))) print(' '.join( [str(j.get_axis(i)) for i in range(j.get_numaxes())]), end='\r') time.sleep(0.05)
def _init_controllers(self): """ Helper method: Setup available PS4 controllers """ if not joystick.get_init(): joystick.init() for joy_id in range(joystick.get_count()): js = joystick.Joystick(joy_id) if PS4C.is_ps4_controller(js.get_name()): js.init() ps4ctrl = PS4C(js) self._controllers.append(ps4ctrl)
def initialize(self, id): """Initializes the selected joystick""" try: if self.joystick: self.joystick.quit() self.joystick_id = id self.joystick = joystick.Joystick(id) self.joystick.init() except: self.joystick_id = -1 print("Invalid joystick num/ID,", id, "!")
def __init__(self, id=0): joystick.init() assert joystick.get_count() self.joystick = joystick.Joystick(id) self.id = id self.joystick.init() self.ctab = { (0, -1): IController.LEFT, (0, 1): IController.RIGHT, (1, 0): IController.DOWN, (-1, 0): IController.UP }
def readjoythread(): """Read joystick loop and pass result onto processor""" global channelsglb, trimglb output = [0, 0, 0, 0, 0, 0] trim = [0, 0, 0, 0, 0, 0] joystick.init() joystick.Joystick(0).init() time.sleep(1) for evt in pygame.event.get(): time.sleep(.02) for i in range(0, len(JOY_AXIES)): if JOY_AXIES[i] > -1: output[JOY_AXIES[i]] = round(joystick.Joystick(0).get_axis(i), 4) if output[JOY_AXIES[i]] is None: output[JOY_AXIES[i]] = 0 for chan in JOY_BUTTONS: output[chan] = -1 channelsglb = output[:] while RUNNING: haschanged = False evt = event.wait() if evt.type == JOYAXISMOTION: if evt.axis < len(JOY_AXIES) and JOY_AXIES[evt.axis] > -1: output[JOY_AXIES[evt.axis]] = round(evt.value, 4) haschanged = True if evt.type == JOYHATMOTION: trim[0] = trim[0] + round((evt.value[0] * .01), 4) trim[1] = trim[1] + 0 - (round((evt.value[1] * .01), 4)) haschanged = True elif evt.type == JOYBUTTONUP or evt.type == JOYBUTTONDOWN: if evt.button < len(JOY_BUTTONS) and JOY_BUTTONS[evt.button] > -1: output[JOY_BUTTONS[ evt.button]] = -1 if evt.type == JOYBUTTONUP else 1 haschanged = True if haschanged: channelsglb = output[:] trimglb = trim[:]
def get_joystick_list(self): """Get a list of connected joysticks. Returns: List of strings describing connected joysticks. """ joystick.init() joysticks = ['None'] for i in range(joystick.get_count()): stick = joystick.Joystick(i) joysticks.append("{0}: {1}".format(i, stick.get_name())) return joysticks
def create_players(self): level = self player1 = KnightController(level.spawn_pc()) if joystick.get_count() > 0: self.controllers.append( JoyController(player1, joystick.Joystick(0))) else: self.controllers.append(KeyboardController(player1.update)) self.controllers.append(player1) if joystick.get_count() > 1: print("2-player game") player1.knight.pos.x *= 0.5 player2 = KnightController(level.spawn_pc(color=(0.4, 0.9, 1.1, 1))) player2.knight.pos.x += player1.pos.x self.controllers.append( JoyController(player2, joystick.Joystick(1))) self.controllers.append(player2) else: print("1-player game")
def get_all_gamepads(self): """ Finds all connected joysticks Returns a dictionary with pygame id of joystick as key and name as value """ joysticks = {} for i in range(joystick.get_count()): stick = joystick.Joystick(i) stick.init() joysticks[i] = stick.get_name() stick.quit() return joysticks
def __init__(self, jnum): self.rstick = True self.jnum = jnum js[jnum] = joystick.Joystick(jnum) js[self.jnum].init() if js[self.jnum].get_numaxes() == 5: self.type = "XBOX" elif js[self.jnum].get_numaxes() == 4: self.type = "PS2" else: self.type = "CHEAP" self.rstick = False self.binarystick = self.type == "CHEAP"
def _listConnected(cls) -> tuple: """ List the connected controller. Params: logger: The logger. Returns: The list of connected controller. """ connected = [] for ctrlrId in range(joystick.get_count()): ctrlrName = joystick.Joystick(ctrlrId).get_name() connected.append(ctrlrName) return tuple(connected)
def initialize_controllers(self): """ Initialize Controllers/Joysticks """ joystick.init() if joystick.get_count(): self._log.info('%s Controllers found', joystick.get_count()) self.num_controllers = joystick.get_count() self.controllers = [ joystick.Joystick(x) for x in range(self.num_controllers) ] for c in self.controllers: self.vPosX.append(0) self.vPosY.append(0) c.init() self._log.info('Initialized controller %s', c.get_name()) self._log.info('Initialized all controllers')
def setup_joystick(): pygame.init() joystick.init() if joystick.get_count() == 1: stick = joystick.Joystick(0) stick.init() axisNum = stick.get_numaxes() buttonNum = stick.get_numbuttons() joystickMode = 'not active' # toggles to 'position' with 'j' key print('joystick found with ' + str(axisNum) + ' axes and ' + str(buttonNum) + ' buttons') else: stick = None joystickMode = None print('no joystick found, only PD control or no control possible') return stick, joystickMode