Esempio n. 1
0
    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))
Esempio n. 2
0
    def __init__( self, port=65001, rate=10 ):
        """
        Initialize pygame based joystick interface
        
        INPUTS: 
          port -- int -- udp port for communication
          mode -- string -- either 0 which pushes events out
                                or 1 which polls at a given rate
          rate -- float -- polling frequency 
        """
	self.DEBUG = []	

        self.port = port
        self.rate = rate
    
        # Initialize socket
        self.sock = socket(AF_INET, SOCK_DGRAM)
        
        display.init()
        # Initialize joystick object
        joystick.init()
        num_joys = joystick.get_count()
        if num_joys < 1:
            print "No joysticks detected"
            exit
        self.j = joystick.Joystick(0)
        self.j.init()
        self.t0 = now()
Esempio n. 3
0
def init(mapping, **kwargs):
    global axis_mapping, extreme_values, imperfection_offsets, joystick, DO_CALIBRATE
    choice = 0

    if "joystick" in kwargs.iteritems():
        choice = kwargs.iteritems()["joystick"]

    pygame.init()
    pygame.joystick.init()
    if pygame.joystick.get_count() == 0:
        return None

    print "Number of joysticks:" + str(pygame.joystick.get_count())
    #Copy axis mapping
    axis_mapping = mapping

    #init joystick
    joystick = pygame.joystick.Joystick(choice)
    joystick.init()

    #initialise final values
    for i in range(joystick.get_numaxes()):
        extreme_values.append([0, 0])
        imperfection_offsets.append(0.0)

    if "calibration" in kwargs.iteritems() and kwargs.iteritems(
    )["calibration"]:
        extreme_values = kwargs.iteritems()["calibration"]["boundaries"]
        imperfection_offsets = kwargs.iteritems()["calibration"]["offsets"]
        DO_CALIBRATE = False

    print "Axis count:" + str(joystick.get_numaxes())
    print "Joystick name:" + str(joystick.get_name())
    return joystick
Esempio n. 4
0
	def _load_joysticks( self, *args ):
		#Clear existing state graphics
		for i in xrange( self.num_joysticks ):
			self.states[i].clear()

		#Clear current list of joysticks
		self.joysticks		  = []
		self.states			  = []
		self.active_joysticks = [False] * 4
		self.active_players   = [False] * 4

		#Reinitialize pygame.joystick to update joystick information
		js.quit()
		js.init()

		self.num_joysticks = js.get_count()

		#Create Joystick instance for each physical joystick
		for i in xrange( self.num_joysticks ):
			self.joysticks.append( js.Joystick( i ) )
			self.joysticks[i].init()

		#Draw state information
		for i in xrange( self.num_joysticks ):
			self.states.append( ControllerState( i, self.graphics ) )
			self.states[i].update(self.active_joysticks[i], self.active_players[i] )
Esempio n. 5
0
    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()
Esempio n. 6
0
    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 __init__(self):
     joystick.init()
     self.count = joystick.get_count()
     self.joysticks = []
     for i in xrange(self.count):
         controller = XboxController(i)
         self.joysticks.append(controller)
Esempio n. 8
0
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()
Esempio n. 9
0
def initialize():
    global joystick
    print(f'Detected {pygame.joystick.get_count()} joysticks')
    if pygame.joystick.get_count() > 0:
        joystick = pygame.joystick.Joystick(0)
        print(f'Initializing joystick {joystick.get_name()}')
        joystick.init()
Esempio n. 10
0
 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()
Esempio n. 11
0
    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')
Esempio n. 12
0
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()
Esempio n. 13
0
 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)
Esempio n. 14
0
    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)
Esempio n. 15
0
def dualshock_handler():
    joystick = Joystick(wii_joy_index)
    joystick.init()

    joy_x1 = joystick.get_axis(0)
    joy_y1 = joystick.get_axis(1)
    joy_x2 = joystick.get_axis(2)
    joy_y2 = joystick.get_axis(3)
    axes = [joy_x1, joy_y1, joy_x2, joy_y2]
    for axis in axes:
        print(axis)
Esempio n. 16
0
def manual():
    global manual_init
    global joystick
    if manual_init:
        manual_init = False
        joystick = pygame.joystick.Joystick(0)
        joystick.init()
    try:
        jesses_handler(pygame.event.get(), joystick)
    except KeyboardInterrupt:
        motor_off()
Esempio n. 17
0
 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
     }
Esempio n. 18
0
 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
     }
Esempio n. 19
0
 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)
Esempio n. 20
0
    def __init__(self):
        super(PS4manager, self).__init__()
        self._controllers = []
        self._listen = False

        # print("Initializing pygame")
        pygame.init()
        pygame.display.init()

        joystick.init()

        self._init_controllers()
Esempio n. 21
0
    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
Esempio n. 22
0
	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')
Esempio n. 23
0
 def __init__(self):
     # Get controllers
     joystick.init()
     joys = [joystick.Joystick(x) for x in range(joystick.get_count())]
     [js.init() for js in joys if not js.get_init()]
     joy_gen = (js for js in joys if is_valid(js))
     # Set attributes
     self.controllers = [Controller(i, next(joy_gen, None)) for i in (1,2)]
     self.players = [None,None]
     self.buffers = [Input(), Input()]
     self.triggered = [Input(), Input()]
     self.zipable = self.players, self.controllers, \
                    self.buffers, self.triggered
Esempio n. 24
0
    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
Esempio n. 25
0
    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
Esempio n. 26
0
def init():
    "init the joystick"
    global joystick
    global lastaxisvalue
    global lasthatvalue
    try:
        num = pygame.joystick.get_count()
        if num > 0:
            joystick = pygame.joystick.Joystick(0)
            joystick.init()
            lastaxisvalue = [None] * joystick.get_numaxes()
            lasthatvalue = [[None, None]] * joystick.get_numhats()

    except pygame.error:
        joystick = None
Esempio n. 27
0
 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')
Esempio n. 28
0
    def refresh(self):
        """
        Finds all connected gamepads. Must be called at the start of the run loop if there has been a change.
        Will uninitialize and then initialize the joystick module
        """
        if self.joystick:
            self.joystick.quit()
            self.joystick = None

        joystick.quit()
        joystick.init()
        joyDictList = self.get_all_gamepads() # Must be fetched before initializing the ID, since otherwise we delete that ID afterwards, apparently the objects here are global!
        self.initialize(clamp(self.joystick_id, 0, maxVal((joystick.get_count() - 1), 0)))
        self.refreshedGamepad.emit(joyDictList)
        self.statusChanged.emit(self.joystick.get_init() if self.joystick else False)
Esempio n. 29
0
def initialize():
    passed, failed = PG.init()
    PJ.init()
    Globals.SCREEN = PDI.set_mode((800, 600), PG.DOUBLEBUF | PG.HWSURFACE)
    Globals.WIDTH = Globals.SCREEN.get_width()
    Globals.HEIGHT = Globals.SCREEN.get_height()
    Globals.FONT = PF.Font(None, 56)
    Globals.STATE = Title.Title_Screen()
    Globals.HERO = Player.Player()
    Globals.HUD = HeadsUpDisplay.HeadsUpDisplay()

    Globals.brightness = PG.Surface((800, 600))
    PX.init()
    Globals.MENU_MUSIC = PX.Sound(screen_start_sound)
    Globals.MUSIC = PX.Sound(loop_sound)
Esempio n. 30
0
 def joystick_init(self):  # Joystick's initialisation
     joystick_count = pygame.joystick.get_count()
     for count in range(joystick_count):
         if joystick_count == 2:
             self.joystick = pygame.joystick.Joystick(self.joy)
             print("{}-->joystick count".format(joystick_count))
             self.joystick.init()
             self.check_joystick = True
         elif joystick_count == 1:
             joystick = pygame.joystick.Joystick(0)
             joystick.init()
             print("connected only 1 joystick - {}".format(joystick))
             self.check_joystick = False
         elif not joystick_count:
             print("no joysticks connected")
             self.check_joystick = False
Esempio n. 31
0
def get_joysticks(joystick_number=None):
    # Get the state of all the joystick
    joystick_count = pygame.joystick.get_count()
    return_joystick_status = {}
    if joystick_number is not None and joystick_count >= joystick_number:
        joystick = pygame.joystick.Joystick(joystick_number)
        joystick.init()
        return_joystick_status[str(joystick_number)] = {}

        joystick_hats = joystick.get_numhats()
        for hat in range(joystick_hats):
            return_joystick_status[str(joystick_number)][
                "hat " + str(hat)] = joystick.get_hat(hat)

        joystick_buttons = joystick.get_numbuttons()
        return_joystick_status[str(
            joystick_number)]["buttons"] = [0] * joystick_buttons
        for button in range(joystick_buttons):
            return_joystick_status[str(joystick_number)]["buttons"][
                button] = joystick.get_button(button)

        joystick_axes = joystick.get_numaxes()
        for axis in range(joystick_axes):
            return_joystick_status[str(joystick_number)][
                "axis " + str(axis)] = round(joystick.get_axis(axis), 3)
    elif joystick_number is None:
        for i in range(joystick_count):
            joystick = pygame.joystick.Joystick(i)
            joystick.init()
            return_joystick_status[str(i)] = {}

            joystick_hats = joystick.get_numhats()
            for hat in range(joystick_hats):
                return_joystick_status[str(i)][
                    "hat " + str(hat)] = joystick.get_hat(hat)

            joystick_buttons = joystick.get_numbuttons()
            return_joystick_status[str(i)]["buttons"] = [0] * joystick_buttons
            for button in range(joystick_buttons):
                return_joystick_status[str(
                    i)]["buttons"][button] = joystick.get_button(button)

            joystick_axes = joystick.get_numaxes()
            for axis in range(joystick_axes):
                return_joystick_status[str(i)]["axis " + str(axis)] = round(
                    joystick.get_axis(axis), 3)
    return return_joystick_status
Esempio n. 32
0
    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))
Esempio n. 33
0
File: app.py Progetto: ilnurgi/robot
def run():

    pygame.init()
    if not pygame.joystick.get_count():
        print 'ERROR: joystick count is 0'
        exit()

    # dasboard_app = subprocess.Popen('python app.py d')

    joystick = pygame.joystick.Joystick(0)
    joystick.init()

    joystick_num_buttons = joystick.get_numbuttons()
    joystick_num_axes = joystick.get_numaxes()

    print 'joystick found:', joystick.get_name()
    print 'count buttons:', joystick_num_buttons
    print 'count axes:', joystick_num_axes

    # кнопки
    JOY_STATE.extend([0 for jb in JoyButtons.BUTTONS])
    # ползунки
    JOY_STATE.extend([-1.0 if ja in (JoyButtons.JOY_LT, JoyButtons.JOY_RT) else 0.0 for ja in JoyButtons.JOYS])

    sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sender.bind((settings.SOCKET_CLIENT_HOST, settings.SOCKET_CLIENT_PORT))

    # нам нужны только события джойстика
    pygame.event.set_allowed([JOYAXISMOTION, JOYBUTTONUP, JOYBUTTONDOWN, QUIT])

    get = pygame.event.get
    sleep = time.sleep

    send_to = sender.sendto
    host = settings.SERVER_HOST
    port = settings.SERVER_PORT

    while True:
        # бесконечный сбор событий с геймпада
        if process_events(get(), joystick_num_buttons):
            # print(JOY_STATE)
            send_to(','.join(str(i) for i in JOY_STATE), (host, port))
        else:
            break
        sleep(0.1)
Esempio n. 34
0
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
Esempio n. 35
0
    def __init__(self, argparser):
        Arbapp.__init__(self, argparser, True) # starting mock mode, init flags (-w and -ng) will be redirected to the server
        init()
        joystick.init()
        self.joysticks = []
        self.server_process = None

        # Joysticks initialization
        for i in range(joystick.get_count()):
            joy = joystick.Joystick(i)
            joy.init()
            if joy.get_numbuttons()>0:
                self.joysticks.append(joy)
            else:
                joy.quit()

        print len(self.joysticks), 'joystick(s) with buttons found!'
Esempio n. 36
0
    def __init__(self):
        print("")
        print("Joystick initializing...")
        if pygame.joystick.get_count() == 0:
            print("ERROR! Did not found a joystick!")
            time.sleep(2)
            print("")
            print("Keyboard initializing...")
            self.keyboardcontrole()
        else:
            joystick = pygame.joystick.Joystick(0)
            joystick.init()

            print("Joysticks gevonden:", pygame.joystick.get_count(), "(", joystick.get_name(), ")")
            print("Specs: assen:", joystick.get_numaxes(), ", knoppen:", joystick.get_numbuttons())
            self.knoppen = joystick.get_numbuttons()
            self.assen = joystick.get_numaxes()
            self.ps3Connected = True
Esempio n. 37
0
def wiimote_handler():
    joystick = pygame.joystick.Joystick(wii_joy_index)
    joystick.init()

    joy_x = joystick.get_axis(0)
    joy_y = joystick.get_axis(1)

    joy_buttons = list()
    for i in range(0, 8):
        joy_button = joystick.get_button(i)
        joy_buttons.append(joy_button)

    pub_direction((joy_x, joy_y))
    pub_arm(joy_buttons[0] - joy_buttons[1])
    pub_shovel(joy_buttons[2] - joy_buttons[3])
    pitch = joy_buttons[4] - joy_buttons[5]
    yaw = joy_buttons[6] - joy_buttons[7]
    pub_camera(pitch, yaw)
Esempio n. 38
0
    def __init__(self):
        self.port = 'COM22'  # change this to the com port for your Arduino
        self.baud = 115200  # baudrate don't change

        try:
            self.ser = serial.Serial(self.port, self.baud)
            print "Successfully opened Serial"
            print
        except serial.SerialException:
            self.ser = None
            print "Could not open Serial!"
            print

        # Initialize Joystick object
        joystick.init()
        pygame.display.init()

        if joystick.get_count():
            self.joy = joystick.Joystick(0)
            self.joy.init()

        else:
            self.joy = None

        self.x_axis = 0  # this is usually 0
        self.throttle_axis = 1  # change this to the correct axis for the joystick

        self.last_turn_val = 0
        self.last_sheet_val = 47

        self.auto_enabled = False  # change to true to use PID
        self.kite_tracker = KiteTracker(path='cam')
        self.pos_list = []

        self.pid = PID(3.0, 0.4, 1.2)
        self.pid.setSetPoint(
            0.0
        )  # Set-point corresponds to heading vector which has angle = 0.0 in its frame.

        # create log file
        self.logfile = datetime.datetime.strftime(
            datetime.datetime.now(), '%Y-%m-%d_%H_%M_%S') + '_log.txt'
        with open(logfile, 'w') as f:
            f.write('time,command,turn_val,power_val\n')
Esempio n. 39
0
    def __init__(self, name='demo'):
        """Initialise pygame and load the parameters for the game indicated
        by the `name` param. Start the clock for the screen's frame rate and
        create a window surface for the game's screen size.

        Create each of the screen objects referenced by the game and store
        their state, ready to show.
        """
        init()
        joystick.init()
        for i in range(joystick.get_count()):
            joystick.Joystick(i).init()

        State.game = util.load_cfg(name)
        State.clock = Clock(10, State.game['frame_rate'])
        State.window = display.set_mode(State.game['screen_size'])

        self._last_joystick_action = None
        self.create_screens()
Esempio n. 40
0
    def __init__(self):
        self.port = 'COM22'  # change this to the com port for your Arduino
        self.baud = 115200   # baudrate don't change

        try:
            self.ser = serial.Serial(self.port, self.baud)
            print "Successfully opened Serial"
            print
        except serial.SerialException:
            self.ser = None
            print "Could not open Serial!"
            print

        # Initialize Joystick object
        joystick.init()
        pygame.display.init()

        if joystick.get_count():
            self.joy = joystick.Joystick(0)
            self.joy.init()

        else:
            self.joy = None

        self.x_axis = 0  # this is usually 0
        self.throttle_axis = 1  # change this to the correct axis for the joystick

        self.last_turn_val = 0
        self.last_sheet_val = 47

        self.auto_enabled = False  # change to true to use PID
        self.kite_tracker = KiteTracker(path='cam')
        self.pos_list = []

        self.pid = PID(3.0, 0.4, 1.2)
        self.pid.setSetPoint(0.0)  # Set-point corresponds to heading vector which has angle = 0.0 in its frame.

        # create log file
        self.logfile = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H_%M_%S') + '_log.txt'
        with open(logfile, 'w') as f:
            f.write('time,command,turn_val,power_val\n')
Esempio n. 41
0
    def __init__(self, params):
        '''Initialize internal variables'''

        # Find us a joystick

        pygame.init()
        joystick.init()

        if joystick.get_count() == 0:
            raise OSError("No joysticks found!")

        self.joystick = joystick.Joystick(0)
        self.joystick.init()
        self.i_j = 0
        self.i_x = 0
        self.i_y = 1
        self.inv_x = True
        self.inv_y = True

        self.v_max = params[1]
        self.w_max = params[2]

        Controller.__init__(self, params[0])
Esempio n. 42
0
import math
import numpy as np
import spiral_zipper_auto as sz
import ball_tracker as cm

# Specify module ID and the name we want to give each of them:
modules = {0xE4: 'T1',0xEA:'T2',0xDF:'T3',0xF8:'T4',0xF1:'T5',0xF2:'T6'}

if __name__=="__main__":

    import sys

    print "Initializing Spiral Zipper Demo"  
    # Initialize pygame and a joystick
    pygame.init()
    joystick.init()

    joystick.Joystick(0).init()

    # Optionally specify left and right modules through the command line.
    
    if len(sys.argv) == 2:
        modules = {int(sys.argv[1]) : 'T1', int(sys.argv[2]) : 'T2', int(sys.argv[3]) : 'T3',int(sys.argv[4]) : 'T4',int(sys.argv[5]) : 'T5',int(sys.argv[6]) : 'T6'}

    # Create a CKBot cluster
    c = L.Cluster()
    
    c.populate( len(modules), modules )

    # Limit module speed and torque for safety
    torque_limit = 0.75
Esempio n. 43
0
def main():
    with serial.serial_for_url(SERIAL_PORT, BAUD_RATE, timeout=0) as xbee:
        controller_state = ControllerState()
        watchdog_timer = 0
        joysticks = []

        # Initialize pygame
        pygame.joystick.init()
        pygame.display.init()

        if not pygame.joystick.get_count():
            print "Please connect a joystick and run again."
            print
            quit()

        print "%s joystick(s) detected." % pygame.joystick.get_count()

        for i in range(pygame.joystick.get_count()):
            joystick = pygame.joystick.Joystick(i)
            joystick.init()
            joysticks.append(joystick)
            print "Joystick %d: " % (i) + joysticks[i].get_name()

        # Set destination node
        if XBEE_DESTINATION_NODE:
            print 'Setting XBee destination node to %s' % XBEE_DESTINATION_NODE
            xbee.write('+++')
            time.sleep(.5)
            xbee.write('ATDN')
            xbee.write(XBEE_DESTINATION_NODE)
            xbee.write('\r')
            time.sleep(1)
            print 'Destination node set'

        # Run joystick listener loop
        while True:
            poll_started = datetime.now()

            while True:
                # Dequeue all joystick events and update state
                e = pygame.event.poll()
                if e.type in (pygame.JOYAXISMOTION, pygame.JOYBUTTONDOWN, pygame.JOYBUTTONUP, pygame.JOYHATMOTION):
                    controller_state.handleJoyEvent(e)
                if e.type == pygame.NOEVENT:
                    break

            #s = xbee.read(1000000)

            #if s:
            #    print 'Incoming Serial:', s

            # Sleep only long enough to keep the output at 50Hz
            poll_ended = datetime.now()
            sleep_time = FREQUENCY - ((poll_ended - poll_started).microseconds / 1000000.)

            if sleep_time > 0.:
                time.sleep(sleep_time)
                # print controller_state
                xbee.write(controller_state.serial_format())

            write_ended = datetime.now()

            watchdog_timer += (write_ended - poll_started).microseconds

            # Print out the state every once in a while to make sure the program hasn't died
            if watchdog_timer > 5 * 1000000:
                print controller_state
                watchdog_timer = 0
Esempio n. 44
0
def goon():
    global q, q_gui
    if not dryrun:
        t = threading.Thread(target=gcodespitter)
        t.daemon = True
        t.start()

    st = 0
    b0 = b1 = b2 = b3 = 0
    correction = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

    def print_(x):
        print >> sys.stderr, x

    calibd = skip_calib  # False
    if calibaction == CALIB_LOAD:
        calibd = True
        with open(calibfile, "r") as f:
            correction = map(
                lambda j: map(float, j), map(lambda x: map(lambda z: z.strip(), x.split(",")), f.readlines())
            )

    pygame.joystick.init()  # initialize joystick module
    pygame.joystick.get_init()  # verify initialization (boolean)

    joystick_count = pygame.joystick.get_count()  # get number of joysticks
    # it's for some case, important to get the joystick number ...

    if joystick_count == 1:
        joystick = pygame.joystick.Joystick(0)
        joystick.get_name()
        joystick.init()
        joystick.get_init()

    while True:
        #      time.sleep(0.00001)

        if joystick_count == 1:

            # verify initialization (maybe cool to do some error trapping with this so    game doesn't crash
            pygame.event.pump()
            # So Now i can get my joystick Axis events

            xax_ = joystick.get_axis(0)
            yax_ = joystick.get_axis(1)
            zax_ = joystick.get_axis(3)

            buttons = joystick.get_numbuttons()
            b0 = joystick.get_button(0)
            b1 = joystick.get_button(1)
            b2 = joystick.get_button(2)
            b3 = joystick.get_button(3)

            if st == 1:
                print >> sys.stderr, "put joystick to center and press B0",
            elif st == 3:
                print >> sys.stderr, "put joystick to left and press B0",
            elif st == 5:
                print >> sys.stderr, "put joystick to right and press B0",
            elif st == 7:
                print >> sys.stderr, "put joystick to down and press B0",
            elif st == 9:
                print >> sys.stderr, "put joystick to up and press B0",
            elif st == 11:
                print >> sys.stderr, "put joystick to bottom and press B0",
            elif st == 13:
                print >> sys.stderr, "put joystick to top and press B0",

            if not calibd:
                st = calib(st, b0, (xax_, yax_, zax_), correction)
                print >> sys.stderr, correction
                if st == 14:
                    print >> sys.stderr, "CALIBRATED.",
                    calibd = True
                    if calibaction == CALIB_SAVE:
                        with open(calibfile, "w+") as f:
                            f.write("\n".join(map(lambda x: ",".join(map(str, x)), correction)))
                continue

            (xax, yax, zax) = correct(correction, (xax_, yax_, zax_))
        #          print >> sys.stderr, correction,
        #          print >> sys.stderr, (xax, yax, zax)
        if not dryrun:
            if b1 != b2:
                if b1:
                    # q.put('G1 Z10', block=False)
                    put_nonblock(q, "G1 Z%f" % (zax))
                if b2:
                    # q.put('G1 Z-10', block=False)
                    put_nonblock(q, "G1 Z%f" % (-zax))
                    # q.put('G1 Z-%f' % (zax), block=False)
            if b3:
                put_nonblock(q, "G1 X%f Y%f" % (xax, yax))
                # q.put('G1 X%f Y%f' % (xax, yax), block=False)

            print "q.join"
            # q.join()
        if b0:
            put_nonblock(q_gui, "save")
import pygame
import pygame.joystick as j
import time

#Initialize both joystick module and individual joystick
j.init()
js = j.Joystick(0)
js.init()

DISPLAY_WIDTH, DISPLAY_HEIGHT = 1000, 800

BLACK=(0,0,0)
WHITE=(235,235,235)
RED=(235,0,0)
GREEN=(0,235,0)
BLUE=(0,0,235)
AQUA = (  0, 255, 255)
FUCHSIA= (255,   0, 255)
GRAY = (128, 128, 128)
LIGHT_GREEN = (  0, 128,   0)
LIME = (  0, 255,   0)
MAROON = (128,  0,   0)
NAVY_BLUE = (  0,  0, 128)
OLIVE = (128, 128,   0)
PURPLE = (128,  0, 128)
SILVER = (192, 192, 192)
TEAL = (  0, 128, 128)
YELLOW = (255, 255,   0)

FPS=50
clock = pygame.time.Clock()