Example #1
0
	def __init__(self, DEBUG=False):
		threading.Thread.__init__(self)
		# Set debugging flag
		self.debug = DEBUG
		
		# Setup variables to maintain real time left and right axis values
		self.left_value = 0
		self.right_value = 0
		
		# Setup connection flag as initially False
		self.connected = False
		
		# Maps internal button integer number to human-readable syntax
		self.button_map = {
					"1": "DUP", "2": "DDOWN", "3": "DLEFT", "4": "DRIGHT",
					"5": "START", "6": "BACK", "7": "LJOYTOGGLE", "8": "RJOYTOGGLE",
					"9": "LB", "10": "RB", "13": "A", "14": "B", "15": "X", "16": "Y",
				}
		
		# Maps button to state, initalize as all unpressed
		self.button_states = {
			"A": False,
		}

		self.actuator_up = False
		self.actuator_down = False

		self.joy_trigger = False

		# Maps human-readable syntax to internal button number
		self.inv_button_map = {v: k for k, v in self.button_map.items()}
		
		self.joysticks = XInputJoystick.enumerate_devices()
		self.j = None
		
		# Flag for running thread to exit
		self.exit = False
		
		# Flag for parent app to keep track of recording
		self.recording = False
		
		# Use start button as recording button. When first pressed, recording is true, when pressed again recording is false
		self.start_last_state = False
		self.start_curr_state = False
		
		# Queue of commands
		self.commands = deque()
		
		# Set status string that can be passed to parent GUI
		self.status = 'Controller Connection: Disconnected'
Example #2
0
    def __init__(self, dev_num=0, send_socket_port=63636, rec_socket_port=63637, socket_ip="localhost"):
        self.send_socket = TCPSendSocket(tcp_port=send_socket_port, tcp_ip=socket_ip, send_type=JSON)
        self.rec_socket = TCPReceiveSocket(tcp_port=rec_socket_port, tcp_ip=socket_ip, handler_function=self.on_receive)

        joysticks = XInputJoystick.enumerate_devices()
        device_numbers = list(map(attrgetter('device_number'), joysticks))

        print('found %d devices: %s' % (len(joysticks), device_numbers))

        if not joysticks:
            sys.exit(0)

        self.joystick = joysticks[dev_num]
        print('using %d' % self.joystick.device_number)

        @self.joystick.event
        def on_button(button, pressed):
            self.send_socket.send_data([button, pressed])

        @self.joystick.event
        def on_axis(axis, value):
            self.send_socket.send_data([axis, value])
Example #3
0
from drone_command import CommandThread
import sys
from xinput import XInputJoystick
import time

# l_thumb_x -> aile
# l_thumb_y -> elev
# r_thumb_x -> rotation
# r_thumb_y -> throttle

if __name__ == '__main__':
    controller = CommandThread()
    joystick = XInputJoystick(0)
    
    
    
    @joystick.event
    def on_button(button, pressed):
        print('button', button, pressed)
        controller.shutdown()

    left_speed = 0
    right_speed = 0

    @joystick.event
    def on_axis(axis, value):
        updateVals = False
        if   axis == "r_thumb_y":
            joystick.throttle = value
            updateVals = True
        elif axis == "r_thumb_x":
Example #4
0
from xinput import XInputJoystick
from Tkinter import Tk
from gui import ControllerGUI
from drone_video import VideoThread
from xinput import *
import time
import sys

root = Tk()
controllerGUI = ControllerGUI(root)

joystick = XInputJoystick(0)


@joystick.event
def on_button(button, pressed):
    #print('button', button, pressed)
    # LT
    if button == 9 and pressed == 1:
        controllerGUI.connectDrone()
    # RT
    if button == 10 and pressed == 1:
        controllerGUI.disconnectDrone()
    # X
    if button == 15 and pressed == 1:
        controllerGUI.disconnectDrone()
        print "**** Exiting ****"
        time.sleep(0.5)
        sys.exit(0)

    # A
Example #5
0
def sample_first_joystick():
    """
    Grab 1st available gamepad, logging changes to the screen.
    L & R analogue triggers set the vibration motor speed.
    """
    joysticks = XInputJoystick.enumerate_devices()
    device_numbers = list(map(attrgetter('device_number'), joysticks))

    print('found %d devices: %s' % (len(joysticks), device_numbers))

    if not joysticks:
        sys.exit(0)

    j0 = joysticks[int(sys.argv[1])]
    print('using %d' % j0.device_number)
    battery = j0.get_battery_information()
    print(battery)

    @j0.event
    def on_button(button, pressed):
        print(HUMANITY_X + ' button:', button, pressed)
        payload = json.dumps({"button": button, "value": pressed})
        client.publish(HUMANITY_X, payload)
        time.sleep(0.1)

    @j0.event
    def on_axis(axis, value):
        left_speed = 0
        right_speed = 0
        print('axis', axis, round(value * 1000))
        if abs(value * 1000) >= 10:
            if axis == "left_trigger":
                left_speed = value
            elif axis == "right_trigger":
                right_speed = value
            payload = json.dumps({"axis": axis, "value": round(value * 1000)})
            client.publish(HUMANITY_X, payload)

    # j1 = joysticks[1]
    # print('using %d' % j1.device_number)
    # battery = j1.get_battery_information()
    # print(battery)

    # @j1.event
    # def on_button(button, pressed):
    #     print('humanity 2 button:', button, pressed)
    #     payload = json.dumps({"button" : button, "value": pressed } )
    #     client.publish(HUMANITY_2, payload)
    #     time.sleep(0.1)

    # @j1.event
    # def on_axis(axis, value):
    #     left_speed = 0
    #     right_speed = 0
    #     print('axis', axis, round(value*1000))
    #     if abs(value *1000) >= 10:
    #         if axis == "left_trigger":
    #             left_speed = value
    #         elif axis == "right_trigger":
    #             right_speed = value
    #         payload = json.dumps({"axis" : axis, "value": round(value*1000)} )
    #         client.publish(HUMANITY_2, payload)

    while True:
        j0.dispatch_events()
        #j1.dispatch_events()

        time.sleep(.01)
        if client.is_connected():

            print("disconnected")
Example #6
0
	def __init__(self):
		threading.Thread.__init__(self)
	
		# Grabs 1st available gamepad, logging changes to the screen
		self.joysticks = XInputJoystick.enumerate_devices()
		self.device_numbers = list(map(attrgetter('device_number'), self.joysticks))
	
		self.l_joy_record = []
		self.r_joy_record = []
		
		self.state = 'normal'
		
		self.button_map = {
					"1": "DUP",
					"2": "DDOWN",
					"3": "DLEFT",
					"4": "DRIGHT",
					"5": "START",
					"6": "BACK",
					"7": "LJOYTOGGLE",
					"8": "RJOYTOGGLE",
					"9": "LB",
					"10": "RB",
					"13": "A",
					"14": "B",
					"15": "X",
					"16": "Y",
				}
				
		self.inv_button_map = {v: k for k, v in self.button_map.items()}
	
		self.button_state_map = {
						"0": "RELEASE",
						"1": "PRESSED",
						}
						
		print('found %d controller devices: %s' % (len(self.joysticks), self.device_numbers))

		if not self.joysticks:
			print("No joysticks found, exiting")
			return None
		
		# Use first joystick
		self.j = self.joysticks[0]
	
		print('Using device %d' % self.j.device_number)
		print('Press back button on controller to quit.')
	
		self.j.quit = False
		self.commands = deque()
		
		@self.j.event
		def on_button(button, pressed):
			#print('button %s %s' % (button_map[str(button)], button_state_map[str(pressed)]))
			self.j.quit = (button == int(self.inv_button_map['BACK']) and pressed)
			
			if (button == int(self.inv_button_map['START']) and pressed):
				if self.state == 'normal':
					self.state = 'record'
					print("Starting to record")
					self.l_joy_record[:] = []
					self.r_joy_record[:] = []
				elif self.state == 'record':
					self.state = 'normal'
					print("End record")
					for index in range(0, len(self.l_joy_record)):
						print(("L:%1.5f , R:%1.5f") % (self.l_joy_record[index], 
														self.r_joy_record[index]))
	
		@self.j.event
		def on_axis(axis, value):
			left_speed = 0
			right_speed = 0

			#print('axis', axis, value)
			
			if self.state == 'record':
				if axis == 'l_thumb_y':
					self.l_joy_record.append(value)
					if len(self.r_joy_record) > 0:
						self.r_joy_record.append(self.r_joy_record[-1])
					else:
						self.r_joy_record.append(0)
						
					value_convert = int(round(sensitivity_scale(value, 0.5, -0.5, 0.5, -127, 127)))
					if (abs(value_convert) <= 10):
						value_convert = 0
					self.commands.append(
						('L', value_convert)
					)
				elif axis == 'r_thumb_y':
					self.r_joy_record.append(value)
					if len(self.l_joy_record) > 0:
						self.l_joy_record.append(self.l_joy_record[-1])
					else:
						self.l_joy_record.append(0)
					
					value_convert = int(round(sensitivity_scale(value, 0.5, -0.5, 0.5, -127, 127)))
					
					if (abs(value_convert) <= 10):
						value_convert = 0
						
					self.commands.append(
						('R', value_convert)
					)
					
			if axis == "left_trigger":
				left_speed = value
			elif axis == "right_trigger":
				right_speed = value
			self.j.set_vibration(left_speed, right_speed)
Example #7
0
	def connect(self):
		"""
		Attempt connection to a joystick
		Returns True if connection succeeded
		Returns False if connection fails
		"""
		
		# Grabs 1st available gamepad, logging changes to the screen
		self.joysticks = XInputJoystick.enumerate_devices()
		self.device_numbers = list(map(attrgetter('device_number'), self.joysticks))
		if self.debug:
			print('found %d controller devices: %s' % (len(self.joysticks), self.device_numbers))
			
		# Attempt to connect to first joystick
		if not self.joysticks:
			if self.debug:
				self.status = 'Controller Connection: No controller found'
				print("No joysticks found, exiting")
			self.connected = False
			return False
		else:
			self.j = self.joysticks[0]
			self.connected = True
			self.status = 'Controller Connection: Connected'
		
		""" Define event handlers for axis and buttons """
		@self.j.event
		def on_button(button, pressed):
			#self.exit = (button == self.get_button_num('BACK') and pressed)
			if button == self.get_button_num('START'):
				self.start_curr_state = pressed
				if self.start_curr_state != self.start_last_state and pressed:
					self.recording = not self.recording
				self.start_last_state = self.start_curr_state

			if button == self.get_button_num('A'):
				if pressed:
					self.button_states['A'] = True
				else:
					self.button_states['A'] = False
			elif button == self.get_button_num('DUP'):
				if pressed:
					if self.button_states['A']:
						print("Actuator up")
						self.actuator_up = True
			elif button == self.get_button_num('DDOWN'):
				if pressed:
					if self.button_states['A']:
						print('Actuator down')
						self.actuator_down = True
						
		@self.j.event
		def on_axis(axis, value):
			left_speed = 0
			right_speed = 0
			
			if axis == 'l_thumb_y':
					
				# Maps analog values of -0.5 to 0.5 to -127 to 127 for motor control
				value_convert = int(round(sensitivity_scale(value, 0.5, -0.5, 0.5, -127, 127)))
				
				# Account for noisy deadzone in middle of joysticks
				if (abs(value_convert) <= 10):
					value_convert = 0
				
				self.left_value = value_convert
					
			elif axis == 'r_thumb_y':
					
				# Maps analog values of -0.5 to 0.5 to -127 to 127 for motor control
				value_convert = int(round(sensitivity_scale(value, 0.5, -0.5, 0.5, -127, 127)))
				
				# Account for noisy deadzone in middle of joysticks
				if (abs(value_convert) <= 10):
					value_convert = 0
					
				self.right_value = value_convert
			elif axis == 'right_trigger':
				if value > 0.7:
					self.joy_trigger = True
				else:
					self.joy_trigger = False
		
		if self.debug:
			print('Using device %d' % self.j.device_number)
			print('Press back button on controller to quit.')
		return True
Example #8
0
    def __init__(self):
        threading.Thread.__init__(self)

        # Grabs 1st available gamepad, logging changes to the screen
        self.joysticks = XInputJoystick.enumerate_devices()
        self.device_numbers = list(
            map(attrgetter('device_number'), self.joysticks))

        self.l_joy_record = []
        self.r_joy_record = []

        self.state = 'normal'

        self.button_map = {
            "1": "DUP",
            "2": "DDOWN",
            "3": "DLEFT",
            "4": "DRIGHT",
            "5": "START",
            "6": "BACK",
            "7": "LJOYTOGGLE",
            "8": "RJOYTOGGLE",
            "9": "LB",
            "10": "RB",
            "13": "A",
            "14": "B",
            "15": "X",
            "16": "Y",
        }

        self.inv_button_map = {v: k for k, v in self.button_map.items()}

        self.button_state_map = {
            "0": "RELEASE",
            "1": "PRESSED",
        }

        print('found %d controller devices: %s' %
              (len(self.joysticks), self.device_numbers))

        if not self.joysticks:
            print("No joysticks found, exiting")
            return None

        # Use first joystick
        self.j = self.joysticks[0]

        print('Using device %d' % self.j.device_number)
        print('Press back button on controller to quit.')

        self.j.quit = False
        self.commands = deque()

        @self.j.event
        def on_button(button, pressed):
            #print('button %s %s' % (button_map[str(button)], button_state_map[str(pressed)]))
            self.j.quit = (button == int(self.inv_button_map['BACK'])
                           and pressed)

            if (button == int(self.inv_button_map['START']) and pressed):
                if self.state == 'normal':
                    self.state = 'record'
                    print("Starting to record")
                    self.l_joy_record[:] = []
                    self.r_joy_record[:] = []
                elif self.state == 'record':
                    self.state = 'normal'
                    print("End record")
                    for index in range(0, len(self.l_joy_record)):
                        print(
                            ("L:%1.5f , R:%1.5f") % (self.l_joy_record[index],
                                                     self.r_joy_record[index]))

        @self.j.event
        def on_axis(axis, value):
            left_speed = 0
            right_speed = 0

            #print('axis', axis, value)

            if self.state == 'record':
                if axis == 'l_thumb_y':
                    self.l_joy_record.append(value)
                    if len(self.r_joy_record) > 0:
                        self.r_joy_record.append(self.r_joy_record[-1])
                    else:
                        self.r_joy_record.append(0)

                    value_convert = int(
                        round(
                            sensitivity_scale(value, 0.5, -0.5, 0.5, -127,
                                              127)))
                    if (abs(value_convert) <= 10):
                        value_convert = 0
                    self.commands.append(('L', value_convert))
                elif axis == 'r_thumb_y':
                    self.r_joy_record.append(value)
                    if len(self.l_joy_record) > 0:
                        self.l_joy_record.append(self.l_joy_record[-1])
                    else:
                        self.l_joy_record.append(0)

                    value_convert = int(
                        round(
                            sensitivity_scale(value, 0.5, -0.5, 0.5, -127,
                                              127)))

                    if (abs(value_convert) <= 10):
                        value_convert = 0

                    self.commands.append(('R', value_convert))

            if axis == "left_trigger":
                left_speed = value
            elif axis == "right_trigger":
                right_speed = value
            self.j.set_vibration(left_speed, right_speed)