Python sensor_msgs.msg.Joy() Examples

The following are 26 code examples of sensor_msgs.msg.Joy(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sensor_msgs.msg , or try the search function .
Example #1
Source File: head_lift_joy.py    From cozmo_driver with Apache License 2.0 7 votes vote down vote up
def __init__(self):
        """
        Create HeadLiftJoy object.

        """
        # params
        self._head_axes = rospy.get_param('~head_axes', 3)
        self._lift_axes = rospy.get_param('~lift_axes', 3)
        self._head_button = rospy.get_param('~head_button', 4)
        self._lift_button = rospy.get_param('~lift_button', 5)

        # pubs
        self._head_pub = rospy.Publisher('head_angle', Float64, queue_size=1)
        self._lift_pub = rospy.Publisher('lift_height', Float64, queue_size=1)

        # subs
        self._joy_sub = rospy.Subscriber('joy', Joy, self._joy_cb, queue_size=1) 
Example #2
Source File: head_lift_joy.py    From cozmo_driver with Apache License 2.0 6 votes vote down vote up
def _joy_cb(self, msg):
        """
        The joy/game-pad message callback.

        :type   msg:    Joy
        :param  msg:    The incoming joy message.

        """
        if msg.buttons[self._head_button] == 1:
            angle_deg = ((msg.axes[self._head_axes] + 1.0) / 2.0) * SUM_HEAD_ANGLE + MIN_HEAD_ANGLE
            rospy.logdebug('Send head angle: {} degrees.'.format(angle_deg))
            self._head_pub.publish(data=angle_deg)

        if msg.buttons[self._lift_button] == 1:
            lift_mm = abs(msg.axes[self._lift_axes]) * SUM_LIFT_HEIGHT + MIN_LIFT_HEIGHT
            rospy.logdebug('Send lift height: {} mm.'.format(lift_mm))
            self._lift_pub.publish(data=abs(msg.axes[self._lift_axes])) 
Example #3
Source File: JoyController.py    From GtS with MIT License 6 votes vote down vote up
def __init__(self, ID, use_joy, joystick_topic, flow_motion=True):
    
        Controller.__init__(self, ID)
        self.use_joy = use_joy

        if self.use_joy:
            self.joy_sub = rospy.Subscriber(joystick_topic, Joy, self.joy_cb)
        else:
            print("------ JOYSTICK NOT BEING USED BY CONTROLLER NODE ------")
        self.curr_joy = None

        self.cmd = -1 # -1 : NONE

        self.is_flow_motion = True#flow_motion

    #Override 
Example #4
Source File: joyop.py    From ackermann-drive-teleop with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, args):
        if len(args)==1 or len(args)==2:
            self.max_speed = float(args[0])
            self.max_steering_angle = float(args[len(args)-1])
            cmd_topic = 'ackermann_cmd'
        elif len(args) == 3:
            self.max_speed = float(args[0])
            self.max_steering_angle = float(args[1])
            cmd_topic = '/' + args[2]
        else:
            self.max_speed = 0.2
            self.max_steering_angle = 0.7
            cmd_topic = 'ackermann_cmd'

        self.speed = 0
        self.steering_angle = 0
        self.joy_sub = rospy.Subscriber('/joy', Joy, self.joy_callback)
        self.drive_pub = rospy.Publisher(cmd_topic, AckermannDrive,
                                         queue_size=1)
        rospy.Timer(rospy.Duration(1.0/5.0), self.pub_callback, oneshot=False)
        rospy.loginfo('ackermann_drive_joyop_node initialized') 
Example #5
Source File: runModel.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def __init__(self):
        rospy.loginfo("runner.__init__")
        # ----------------------------
        self.sess = tf.InteractiveSession()
        self.model = cnn_cccccfffff()
        saver = tf.train.Saver()
        saver.restore(self.sess, "/home/ubuntu/catkin_ws/src/car/scripts/model.ckpt")
        rospy.loginfo("runner.__init__: model restored")
        # ----------------------------
        self.bridge = CvBridge()
        self.netEnable = False
        self.controller = XBox360()
        rospy.Subscriber("/camera/rgb/image_rect_color", Image, self.runCB)
        rospy.Subscriber("/joy", Joy ,self.joyCB)
        self.pub_twist = rospy.Publisher("/neural_twist", TwistStamped, queue_size=1)
        self.sound = rospy.Publisher("/sound_server/speech_synth", String, queue_size=1)
        rospy.init_node('neural_cmd',anonymous=True)
        rospy.spin() 
Example #6
Source File: dataRecorder.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def __init__(self):
        print "dataRecorder"
        self.record = False
        self.twist = None
        self.twistLock = Lock()
        self.bridge = CvBridge()
        self.globaltime = None
        self.controller = XBox360()
        ##rospy.Subscriber("/camera/depth/points" , PointCloud2, self.ptcloudCB)
        rospy.Subscriber("/camera/depth/image_rect_raw_drop", Image, self.depthCB)
        rospy.Subscriber("/camera/rgb/image_rect_color_drop", Image, self.streamCB)
        #rospy.Subscriber("/camera/rgb/image_rect_mono_drop", Image, self.streamCB)  ##for black and white images see run.launch and look at the drop fps nodes near the bottom
        rospy.Subscriber("/lidargrid", Image, self.lidargridCB)
        rospy.Subscriber("/cmd_vel", TwistStamped, self.cmd_velCB)
        rospy.Subscriber("/joy", Joy ,self.joyCB)
        self.sound = rospy.Publisher("/sound_server/speech_synth", String, queue_size=1)
        rospy.init_node('dataRecorder',anonymous=True)
        rospy.spin() 
Example #7
Source File: cmdControl.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def cmdRouter(self):     
        if self.joy_time+self.joy_timeout >= time.time():  ## If last joy message was recieved less than 2 seconds ago Joystick controlled      
            rospy.loginfo("Joy cmd")
            rospy.loginfo(self.joy_time+self.joy_timeout)
            rospy.loginfo(time.time())
            self.vel_pub.publish(self.joy_cmd) 
        elif self.lid_time+self.lid_timeout >= time.time(): ##else if last lidar twist was recieved less than 0.3 seconds ago lidar evasion controlled
            self.vel_pub.publish(self.lid_cmd)  
            rospy.loginfo("LIDAR cmd")
        elif self.cnn_time+self.cnn_timeout >= time.time(): ## else if last neural twist was recieved less than 0.1 seconds ago neural net controlled
            self.vel_pub.publish(self.cnn_cmd)
            rospy.loginfo("CNN cmd")
        else:                                               ##else if no command, neutral throttle and steering
            self.joy_cmd.twist.linear.x = 0.5
            self.joy_cmd.twist.angular.z = 0.5
            self.vel_pub.publish(self.joy_cmd)
            rospy.loginfo("Joy cmd else") 
Example #8
Source File: lidarEvasion.py    From Cherry-Autonomous-Racecar with MIT License 6 votes vote down vote up
def __init__(self):
        self.evadeSet = False
        self.controller = XBox360()
        self.bridge = CvBridge()
        self.throttle = 0
        self.grid_img = None
        ##self.throttleLock = Lock()
        print "evasion"
        rospy.Subscriber("/lidargrid", Image, self.gridCB, queue_size=1)
        rospy.Subscriber("/cmd_vel", TwistStamped , self.twistCB , queue_size = 1)
        rospy.Subscriber("/joy", Joy, self.joyCB, queue_size=5)
        self.pub_img = rospy.Publisher("/steering_img", Image)
        self.pub_twist = rospy.Publisher("/lidar_twist", TwistStamped, queue_size=1)
        self.sound = rospy.Publisher("/sound_server/speech_synth", String, queue_size=1)        
        rospy.init_node ('lidar_cmd',anonymous=True)
        rospy.spin() 
Example #9
Source File: racecar_joy.py    From tianbot_racecar with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        rospy.loginfo("Tianbot Racecar JoyTeleop Initializing...")
        self._twist = Twist()
        self._twist.linear.x = 1500
        self._twist.angular.z = 90
        self._deadman_pressed = False
        self._zero_twist_published = False

        self._cmd_vel_pub = rospy.Publisher('~/car/cmd_vel', Twist, queue_size=5)
        self._joy_sub = rospy.Subscriber('/joy', Joy, self.joy_callback)
        self._timer = rospy.Timer(rospy.Duration(0.05), self.joystick_controller)
        self._axis_throttle = 1

        _joy_mode = rospy.get_param("~joy_mode", "D").lower()
        if _joy_mode == "d":
            self._axis_servo = 2
        if _joy_mode == "x":
            self._axis_servo = 3

        self._throttle_scale = rospy.get_param("~throttle_scale", 0.5)
        self._servo_scale = rospy.get_param("~servo_scale", 1) 
Example #10
Source File: joystick_interface.py    From niryo_one_ros with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.joy_enabled = False
        self.joint_mode = JointMode()

        joy_subscriber = rospy.Subscriber('joy', Joy, self.callback_joy)

        self.joystick_server = rospy.Service(
            '/niryo_one/joystick_interface/enable', SetInt, self.callback_enable_joystick)

        self.joystick_enabled_publisher = rospy.Publisher('/niryo_one/joystick_interface/is_enabled',
                                                          Bool, queue_size=1)

        rospy.Timer(rospy.Duration(2), self.publish_joystick_enabled) 
Example #11
Source File: joystick.py    From crazyswarm with MIT License 5 votes vote down vote up
def __init__(self):
        self.lastButtonState = 0
        self.buttonWasPressed = False
        rospy.Subscriber("/joy", Joy, self.joyChanged) 
Example #12
Source File: inference_worker.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def joystick_thread(self):
        try:
            logger.debug('Joystick thread started')
            rospy.Subscriber('joy', Joy, self.joystick_callback)
        except Exception as e:
           logger.exception(e) 
Example #13
Source File: joy_twist.py    From ros_book_programs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
        self._joy_sub = rospy.Subscriber('joy', Joy, self.joy_callback, queue_size=1)
        self._twist_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1) 
Example #14
Source File: random.py    From GtS with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):

        #used to get joystick input
        # rospy.init_node("CrazyflieTeleopPolicy", anonymous=True)

        # self._outputs = kwargs['outputs'] 
        self._joy_topic = kwargs['joy_topic']

        self.curr_joy = None
        self.cmd = -1 # -1 : NONE

        self.is_flow_motion = bool(kwargs['flow_motion'])

        rospy.Subscriber(self._joy_topic, Joy, self.joy_cb)
        # self._rew_fn = kwargs['rew_fn']

        self._N = kwargs['N']
        self._gamma = kwargs['gamma']
        
        ### environment
        self._env_spec = kwargs['env_spec']
        self._obs_vec_keys = list(self._env_spec.observation_vec_spec.keys())
        self._action_keys = list(self._env_spec.action_spec.keys())
        self._goal_keys = list(self._env_spec.goal_spec.keys())
        # self._output_keys = sorted([output['name'] for output in self._outputs])
        self._obs_im_shape = self._env_spec.observation_im_space.shape

        
        self._obs_im_dim = np.prod(self._obs_im_shape)
        self._obs_vec_dim = len(self._obs_vec_keys)
        self._action_dim = len(self._action_keys)
        self._goal_dim = len(self._goal_keys)
        
        # self._output_dim = len(self._output_keys)
        self.prevSpikeButton = False


    #################
    ### Callbacks ###
    ################# 
Example #15
Source File: zero.py    From GtS with MIT License 5 votes vote down vote up
def __init__(self, **kwargs):

        #used to get joystick input
        # rospy.init_node("CrazyflieTeleopPolicy", anonymous=True)

        # self._outputs = kwargs['outputs'] 
        self._joy_topic = kwargs['joy_topic']

        self.curr_joy = None
        self.cmd = -1 # -1 : NONE

        self.is_flow_motion = bool(kwargs['flow_motion'])

        rospy.Subscriber(self._joy_topic, Joy, self.joy_cb)
        # self._rew_fn = kwargs['rew_fn']

        self._N = kwargs['N']
        self._gamma = kwargs['gamma']
        
        ### environment
        self._env_spec = kwargs['env_spec']
        self._obs_vec_keys = list(self._env_spec.observation_vec_spec.keys())
        self._action_keys = list(self._env_spec.action_spec.keys())
        self._goal_keys = list(self._env_spec.goal_spec.keys())
        # self._output_keys = sorted([output['name'] for output in self._outputs])
        self._obs_im_shape = self._env_spec.observation_im_space.shape

        
        self._obs_im_dim = np.prod(self._obs_im_shape)
        self._obs_vec_dim = len(self._obs_vec_keys)
        self._action_dim = len(self._action_keys)
        self._goal_dim = len(self._goal_keys)
        
        # self._output_dim = len(self._output_keys)
        self.prevSpikeButton = False


    #################
    ### Callbacks ###
    ################# 
Example #16
Source File: gamepad_marshall_node.py    From tello_driver with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # Define parameters
        self.joy_state_prev = GamepadState()
        # if None then not in agent mode, otherwise contains time of latest enable/ping
        self.agent_mode_t = None
        self.flip_dir = 0

        # Start ROS node
        rospy.init_node('gamepad_marshall_node')

        # Load parameters
        self.agent_mode_timeout_sec = rospy.get_param(
            '~agent_mode_timeout_sec', 1.0)

        self.pub_takeoff = rospy.Publisher(
            'takeoff', Empty,  queue_size=1, latch=False)
        self.pub_throw_takeoff = rospy.Publisher(
            'throw_takeoff', Empty,  queue_size=1, latch=False)
        self.pub_land = rospy.Publisher(
            'land', Empty,  queue_size=1, latch=False)
        self.pub_palm_land = rospy.Publisher(
            'palm_land', Empty,  queue_size=1, latch=False)
        self.pub_reset = rospy.Publisher(
            'reset', Empty,  queue_size=1, latch=False)
        self.pub_flattrim = rospy.Publisher(
            'flattrim', Empty,  queue_size=1, latch=False)
        self.pub_flip = rospy.Publisher(
            'flip', UInt8,  queue_size=1, latch=False)
        self.pub_cmd_out = rospy.Publisher(
            'cmd_vel', Twist, queue_size=10, latch=False)
        self.pub_fast_mode = rospy.Publisher(
            'fast_mode', Bool,  queue_size=1, latch=False)
        self.sub_agent_cmd_in = rospy.Subscriber(
            'agent_cmd_vel_in', Twist, self.agent_cmd_cb)
        self.sub_joy = rospy.Subscriber('/joy', Joy, self.joy_cb)
        rospy.loginfo('Gamepad marshall node initialized') 
Example #17
Source File: action_panel.py    From visual_dynamics with MIT License 5 votes vote down vote up
def __init__(self, fig, gs, rows, cols, actions_arr):
        """
        Constructs an ActionPanel assuming actions_arr is an array of
        fully initialized actions.
        Each action must have: key, name, func.
        Each action can have: axis_pos, keyboard_binding, ps3_binding.
        """
        assert len(actions_arr) <= rows*cols, 'Too many actions to put into gridspec.'

        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=gs)
        self._axarr = [plt.subplot(self._gs[i]) for i in range(len(actions_arr))]
        
        # Read keyboard_bindings and ps3_bindings from config
        self._actions = {action.key: action for action in actions_arr}
        for key, action in self._actions.items():
            if key in config['keyboard_bindings']:
                action.kb = config['keyboard_bindings'][key]
            if key in config['ps3_bindings']:
                action.pb = config['ps3_bindings'][key]

        self._buttons = None
        self._initialize_buttons()
        self._cid = self._fig.canvas.mpl_connect('key_press_event', self.on_key_press)
        if ROS_ENABLED:
            self._ps3_count = 0
            rospy.Subscriber(config['ps3_topic'], Joy, self.ps3_callback) 
Example #18
Source File: joystick.py    From intera_sdk with Apache License 2.0 5 votes vote down vote up
def _on_joy(self, msg):
        """ callback for messages from joystick input
        Args:
              msg(Joy): a joystick input message
        """

        self._controls['btnLeft'] = (msg.buttons[15] == 1)
        self._controls['btnUp'] = (msg.buttons[12] == 1)
        self._controls['btnDown'] = (msg.buttons[14] == 1)
        self._controls['btnRight'] = (msg.buttons[13] == 1)

        self._controls['dPadUp'] = (msg.buttons[4] == 1)
        self._controls['dPadDown'] = (msg.buttons[6] == 1)
        self._controls['dPadLeft'] = (msg.buttons[7] == 1)
        self._controls['dPadRight'] = (msg.buttons[5] == 1)

        self._controls['leftStickHorz'] = msg.axes[0]
        self._controls['leftStickVert'] = msg.axes[1]
        self._controls['rightStickHorz'] = msg.axes[2]
        self._controls['rightStickVert'] = msg.axes[3]

        self._controls['leftBumper'] = (msg.buttons[10] == 1)
        self._controls['rightBumper'] = (msg.buttons[11] == 1)
        self._controls['leftTrigger'] = (msg.buttons[8] == 1)
        self._controls['rightTrigger'] = (msg.buttons[9] == 1)

        self._controls['function1'] = (msg.buttons[0] == 1)
        self._controls['function2'] = (msg.buttons[3] == 1) 
Example #19
Source File: turtlesim_joy.py    From ROS-Robotics-By-Example with MIT License 5 votes vote down vote up
def joy_listener():

    # start node
    rospy.init_node("turtlesim_joy", anonymous=True)

    # subscribe to joystick messages on topic "joy"
    rospy.Subscriber("joy", Joy, tj_callback, queue_size=1)

    # keep node alive until stopped
    rospy.spin()

# called when joy message is received 
Example #20
Source File: joystick.py    From intera_sdk with Apache License 2.0 5 votes vote down vote up
def _on_joy(self, msg):
        """ callback for messages from joystick input
        Args:
              msg(Joy): a joystick input message
        """
        raise NotImplementedError() 
Example #21
Source File: joystick.py    From intera_sdk with Apache License 2.0 5 votes vote down vote up
def _on_joy(self, msg):
        """ callback for messages from joystick input
        Args:
              msg(Joy): a joystick input message
        """

        self._controls['btnLeft'] = (msg.buttons[2] == 1)
        self._controls['btnUp'] = (msg.buttons[3] == 1)
        self._controls['btnDown'] = (msg.buttons[0] == 1)
        self._controls['btnRight'] = (msg.buttons[1] == 1)

        self._controls['dPadUp'] = (msg.axes[7] > 0.5)
        self._controls['dPadDown'] = (msg.axes[7] < -0.5)
        self._controls['dPadLeft'] = (msg.axes[6] > 0.5)
        self._controls['dPadRight'] = (msg.axes[6] < -0.5)

        self._controls['leftStickHorz'] = msg.axes[0]
        self._controls['leftStickVert'] = msg.axes[1]
        self._controls['rightStickHorz'] = msg.axes[3]
        self._controls['rightStickVert'] = msg.axes[4]

        self._controls['leftBumper'] = (msg.buttons[4] == 1)
        self._controls['rightBumper'] = (msg.buttons[5] == 1)
        self._controls['leftTrigger'] = (msg.axes[2] < 0.0)
        self._controls['rightTrigger'] = (msg.axes[5] < 0.0)

        self._controls['function1'] = (msg.buttons[6] == 1)
        self._controls['function2'] = (msg.buttons[10] == 1) 
Example #22
Source File: cmdControl.py    From Cherry-Autonomous-Racecar with MIT License 5 votes vote down vote up
def __init__(self):
        self.throttleInitialized = False
        self.joy_timeout = 2.0
        self.lid_timeout = 0.30
        self.cnn_timeout = 0.1
        self.joy_time = time.time()
        self.lid_time = time.time()
        self.cnn_time = time.time()
        self.controller = XBox360()
        self.joy_cmd = TwistStamped()
        self.lid_cmd = TwistStamped()
        self.cnn_cmd = TwistStamped()
        self.cruiseControl = False
        self.cruiseThrottle = 0.5
        self.steeringAngle = 0.5
        self.throttle = 0.5
        self.trim = 0.0
        ##self.throttleLock = Lock()
        print "cmd_control"
       
        rospy.Subscriber("/imu", Imu, self.imuCB, queue_size=5)
        rospy.Subscriber("/lidar_twist", TwistStamped, self.lidarTwistCB, queue_size=5)
        rospy.Subscriber("/neural_twist", TwistStamped, self.neuralTwistCB, queue_size=5)
        rospy.Subscriber("/joy", Joy, self.joyCB, queue_size=5)
        self.vel_pub = rospy.Publisher("/cmd_vel", TwistStamped, queue_size = 1) 
        #self.state_pub = rospy.Publisher("/joint_states", JointState, queue_size=1)
        self.sound = rospy.Publisher("/sound_server/speech_synth", String, queue_size=1)        
        rospy.init_node ('cmd_control',anonymous=True)
        rate = rospy.Rate(66)
        while not rospy.is_shutdown():
            self.cmdRouter()
            rate.sleep() 
Example #23
Source File: joystick.py    From intera_sdk with Apache License 2.0 5 votes vote down vote up
def _on_joy(self, msg):
        """ callback for messages from joystick input
        Args:
              msg(Joy): a joystick input message
        """
        self._controls['btnLeft'] = (msg.buttons[2] == 1)
        self._controls['btnUp'] = (msg.buttons[3] == 1)
        self._controls['btnDown'] = (msg.buttons[0] == 1)
        self._controls['btnRight'] = (msg.buttons[1] == 1)

        self._controls['dPadUp'] = (msg.axes[7] > 0.5)
        self._controls['dPadDown'] = (msg.axes[7] < -0.5)
        self._controls['dPadLeft'] = (msg.axes[6] > 0.5)
        self._controls['dPadRight'] = (msg.axes[6] < -0.5)

        self._controls['leftStickHorz'] = msg.axes[0]
        self._controls['leftStickVert'] = msg.axes[1]
        self._controls['rightStickHorz'] = msg.axes[3]
        self._controls['rightStickVert'] = msg.axes[4]

        self._controls['leftBumper'] = (msg.buttons[4] == 1)
        self._controls['rightBumper'] = (msg.buttons[5] == 1)
        self._controls['leftTrigger'] = (msg.axes[2] < 0.0)
        self._controls['rightTrigger'] = (msg.axes[5] < 0.0)

        self._controls['function1'] = (msg.buttons[6] == 1)
        self._controls['function2'] = (msg.buttons[7] == 1) 
Example #24
Source File: joy_driver.py    From crazyflieROS with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,options=None):     
        self.options = options
           
        self.joy_scale = [-1,1,-1,1,1] #RPYTY
        self.trim_roll = 0
        self.trim_pitch = 0
        self.max_angle = 30
        self.max_yawangle = 200
        
        
        self.max_thrust = 80.
        self.min_thrust = 25.
        self.max_thrust_raw = percentageToThrust(self.max_thrust)
        self.min_thrust_raw = percentageToThrust(self.min_thrust)       
        self.old_thurst_raw = 0
        
        self.slew_limit = 45
        self.slew_rate = 30
        self.slew_limit_raw = percentageToThrust(self.slew_limit)            
        self.slew_rate_raw = percentageToThrust(self.slew_rate)   
        
        self.dynserver = None
        self.prev_cmd = None
        self.curr_cmd = None
        self.yaw_joy = True
        
        self.sub_joy   = rospy.Subscriber("/joy", JoyMSG, self.new_joydata)
        self.sub_tf    = tf.TransformListener()         
        self.pub_tf    = tf.TransformBroadcaster()    
        self.pub_cfJoy = rospy.Publisher("/cfjoy", CFJoyMSG)
        
        # Dynserver               
        
        self.dynserver = DynamicReconfigureServer(CFJoyCFG, self.reconfigure) 
Example #25
Source File: joystick.py    From intera_sdk with Apache License 2.0 4 votes vote down vote up
def __init__(self, scale=1.0, offset=0.0, deadband=0.1):
        """
        Maps joystick input to robot control.

        @type scale: float
        @param scale: scaling applied to joystick values [1.0]
        @type offset: float
        @param offset: joystick offset values, post-scaling [0.0]
        @type deadband: float
        @param deadband: deadband post scaling and offset [0.1]

        Raw joystick valuess are in [1.0...-1.0].
        """
        sub = rospy.Subscriber("/joy", Joy, self._on_joy)
        self._scale = scale
        self._offset = offset
        self._deadband = deadband
        self._controls = {}

        self._buttons = {}
        self._sticks = {}
        button_names = (
            'btnLeft', 'btnUp', 'btnDown', 'btnRight',
            'dPadUp', 'dPadDown', 'dPadLeft', 'dPadRight',
            'leftBumper', 'rightBumper',
            'leftTrigger', 'rightTrigger',
            'function1', 'function2')
        stick_names = (
            'leftStickHorz', 'leftStickVert',
            'rightStickHorz', 'rightStickVert')

        #doing this with lambda won't work
        def gen_val_func(name, type_name):
            def val_func():
                return type_name(
                    name in self._controls and self._controls[name])
            return val_func

        for name in button_names:
            self._buttons[name] = ButtonTransition(gen_val_func(name, bool))
        for name in stick_names:
            self._sticks[name] = StickTransition(gen_val_func(name, float)) 
Example #26
Source File: joy_driver_pid.py    From crazyflieROS with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self,options=None):     
        self.options = options
        self.warntime = time.time()
        self.USB = False
           
        self.joy_scale = [-1,1,-1,1,1] #RPYTY
        self.trim_roll = 0
        self.trim_pitch = 0
        self.max_angle = 30
        self.max_yawangle = 200
        
        
        self.max_thrust = 80.
        self.min_thrust = 25.
        self.max_thrust_raw = percentageToThrust(self.max_thrust)
        self.min_thrust_raw = percentageToThrust(self.min_thrust)       
        self.old_thurst_raw = 0
        
        self.slew_limit = 45
        self.slew_rate = 30
        self.slew_limit_raw = percentageToThrust(self.slew_limit)            
        self.slew_rate_raw = percentageToThrust(self.slew_rate)   
        
        self.dynserver = None
        self.prev_cmd = None
        self.curr_cmd = None
        self.yaw_joy = True
        
        self.sub_joy   = rospy.Subscriber("/joy", JoyMSG, self.new_joydata)
        self.sub_tf    = tf.TransformListener()         
        self.pub_tf    = tf.TransformBroadcaster()    
        self.pub_cfJoy = rospy.Publisher("/cfjoy", CFJoyMSG, queue_size=2)
        self.pub_PID = rospy.Publisher("/pid", PidMSG,queue_size=50)

        # PIDs for R,P,Y,THROTTLE
        self.PID = (PID(), PID(), PID(), PID()) # XY, Throttle, Yaw
        self.PIDActive = (True, True, True, True) # XY, YAw, Throttle on/off
        self.PIDDelay = 0.0
        self.PIDSource = Source.Qualisys
        self.PIDControl = True
        self.goal = [0.0, 0.0, 0.0, 0.0] # X Y Z YAW
        self.prev_msg = None
        self.PIDSetCurrentAuto = True

        self.thrust = (40., 90., 66.) # Min, Max, Base thrust
        self.distFunc = fLIN
        self.wandControl = False

        # Dynserver
        self.dynserver = DynamicReconfigureServer(CFJoyCFG, self.reconfigure)