def linear_movement(self,position, linear_speed = 0.2, linear_accel = 0.2, rotational_speed = 0.1, rotational_accel = 0.1):
	   	try:
			traj_options = TrajectoryOptions()
			traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
			traj = MotionTrajectory(trajectory_options = traj_options, limb = self._limb)

			wpt_opts = MotionWaypointOptions(max_linear_speed=linear_speed,
			                                 max_linear_accel=linear_accel,
			                                 max_rotational_speed=rotational_speed,
			                                 max_rotational_accel=rotational_accel,
			                                 max_joint_speed_ratio=0.2)
			waypoint = MotionWaypoint(options = wpt_opts.to_msg(), limb = self._limb)
			poseStamped = PoseStamped()
			poseStamped.pose = position
			waypoint.set_cartesian_pose(poseStamped, self._tip_name)

			rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

			traj.append_waypoint(waypoint.to_msg())

			result = traj.send_trajectory(timeout=5.0)
			if result is None:
			    rospy.logerr('Trajectory FAILED to send')
			    return

			if result.result:
			    rospy.loginfo('Motion controller successfully finished the trajectory!')
			else:
			    rospy.logerr('Motion controller failed to complete the trajectory with error %s',
			                 result.errorId)
		except rospy.ROSInterruptException:
			rospy.logerr('Keyboard interrupt detected from the user. Exiting before trajectory completion.')
Example #2
0
    def move(self, point_list, wait = True, MAX_LIN_SPD=7.0, MAX_LIN_ACCL=1.5):  # one point = [x_coord, y_coord, z_coord, x_deg, y_deg, z_deg]     
        try:
            limb = Limb()                                                     # point_list = [pointA, pointB, pointC, ...]
            traj_options = TrajectoryOptions()
            traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
            traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)
        except:
            print("There may have been an error while exiting")

        if self.STOP:
            traj.stop_trajectory()
            return True

        wpt_opts = MotionWaypointOptions(max_linear_speed=MAX_LIN_SPD, max_linear_accel=MAX_LIN_ACCL, corner_distance=0.002)
        
        for point in point_list:
            q_base = quaternion_from_euler(0, 0, math.pi/2)
            #q_rot = quaternion_from_euler(math.radians(point[3]), math.radians(point[4]), math.radians(point[5]))
            q_rot = quaternion_from_euler(point[3], point[4], point[5])
            q = quaternion_multiply(q_rot, q_base)

            newPose = PoseStamped()
            newPose.header = Header(stamp=rospy.Time.now(), frame_id='base')
            newPose.pose.position.x = point[0] + 0.65
            newPose.pose.position.y = point[1] + 0.0
            newPose.pose.position.z = point[2] + 0.4
            newPose.pose.orientation.x = q[0]
            newPose.pose.orientation.y = q[1]
            newPose.pose.orientation.z = q[2]
            newPose.pose.orientation.w = q[3]

            waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)
            waypoint.set_cartesian_pose(newPose, "right_hand", limb.joint_ordered_angles())
            traj.append_waypoint(waypoint.to_msg())

        if(wait):
            print(" \n --- Sending trajectory and waiting for finish --- \n")
            result = traj.send_trajectory(wait_for_result=wait)
            if result is None:
                rospy.logerr('Trajectory FAILED to send')
                success = False
            elif result.result:
                rospy.loginfo('Motion controller successfully finished the trajcetory')
                success = True
            else:
                rospy.logerr('Motion controller failed to complete the trajectory. Error: %s', result.errorId)
                success = False
        else:
            print("\n --- Sending trajector w/out waiting --- \n")
            traj.send_trajectory(wait_for_result=wait)
            success = True

        return success
    def go_to_pose(self, position, orientation):
        try:
            traj_options = TrajectoryOptions()
            traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
            traj = MotionTrajectory(trajectory_options=traj_options,
                                    limb=self._right_arm)

            wpt_opts = MotionWaypointOptions(max_linear_speed=0.6,
                                             max_linear_accel=0.6,
                                             max_rotational_speed=1.57,
                                             max_rotational_accel=1.57,
                                             max_joint_speed_ratio=1.0)
            waypoint = MotionWaypoint(options=wpt_opts.to_msg(),
                                      limb=self._right_arm)

            pose = Pose()
            pose.position.x = position[0]
            pose.position.y = position[1]
            pose.position.z = position[2]
            pose.orientation.x = orientation[0]
            pose.orientation.y = orientation[1]
            pose.orientation.z = orientation[2]
            pose.orientation.w = orientation[0]
            poseStamped = PoseStamped()
            poseStamped.pose = pose
            joint_angles = self._right_arm.joint_ordered_angles()
            waypoint.set_cartesian_pose(poseStamped, "right_hand",
                                        joint_angles)

            rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

            traj.append_waypoint(waypoint.to_msg())

            result = traj.send_trajectory(timeout=10)
            if result is None:
                rospy.logerr('Trajectory FAILED to send')
                return

            if result.result:
                rospy.loginfo(
                    'Motion controller successfully finished the trajectory!')
            else:
                rospy.logerr(
                    'Motion controller failed to complete the trajectory with error %s',
                    result.errorId)

        except rospy.ROSInterruptException:
            rospy.logerr(
                'Keyboard interrupt detected from the user. Exiting before trajectory completion.'
            )
Example #4
0
def moveRoboticArm(position, orientation, linear_speed, linear_accel):
    """
    Move the robot arm to the specified configuration given a positionX, positionY, positionZ, quaternion array and max linear speed.

    """
    try:
        limb = Limb()

        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

        wpt_opts = MotionWaypointOptions(max_linear_speed=linear_speed,
                                         max_linear_accel=linear_accel)
        waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)
        joint_names = limb.joint_names()
        endpoint_state = limb.tip_state('right_hand')
        pose = endpoint_state.pose
        if position is not None and len(position) == 3:
            pose.position.x = position[0]
            pose.position.y = position[1]
            pose.position.z = position[2]
        if orientation is not None and len(orientation) == 4:
            pose.orientation.x = orientation[0]
            pose.orientation.y = orientation[1]
            pose.orientation.z = orientation[2]
            pose.orientation.w = orientation[3]
        poseStamped = PoseStamped()
        poseStamped.pose = pose
        joint_angles = limb.joint_ordered_angles()
        waypoint.set_cartesian_pose(poseStamped, 'right_hand', joint_angles)
        rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())
        traj.append_waypoint(waypoint.to_msg())
        result = traj.send_trajectory()

        if result is None:
            rospy.logerr('Trajectory FAILED to send')
            return
        if result.result:
            rospy.loginfo(
                'Motion controller successfully finished the trajectory!')
        else:
            rospy.logerr(
                'Motion controller failed to complete the trajectory with error %s',
                result.errorId)
    except rospy.ROSInterruptException:
        print("Something went wrong")
        rospy.logerr(
            'Keyboard interrupt detected from the user. Exiting before trajectory completion.'
        )
Example #5
0
    def execute_trajectory(self,
                           trajectory,
                           joint_names,
                           speed=None,
                           acceleration=None):
        """
        trajectory is a list of points: approach (joint), init (cart), drawing (cart), retreat (cart)
        """
        speed = speed if speed is not None else self.speed
        acceleration = acceleration if acceleration is not None else self.acceleration
        if isinstance(trajectory, dict) and "approach" in trajectory:
            for mtype in ["approach", "init", "drawing", "retreat"]:
                points = trajectory[mtype]
                if points["type"] == "joint":
                    self._seed = points["joints"]
                    self.move_to_joint_positions(
                        dict(zip(joint_names, points["joints"])))
                elif points["type"] == "cart":

                    wpt_opts = MotionWaypointOptions(
                        max_joint_speed_ratio=speed,
                        max_joint_accel=acceleration)

                    traj = MotionTrajectory(limb=self.limb)
                    waypoint = MotionWaypoint(options=wpt_opts, limb=self.limb)
                    t_opt = TrajectoryOptions(
                        interpolation_type=TrajectoryOptions.CARTESIAN)
                    jv = deepcopy(points["joints"])
                    jv.reverse()
                    waypoint.set_joint_angles(jv)
                    waypoint.set_cartesian_pose(
                        list_to_pose_stamped(points["pose"], frame_id="base"))
                    traj.append_waypoint(waypoint)
                    jn = [str(j) for j in joint_names]
                    jn.reverse()
                    traj.set_joint_names(jn)
                    traj.set_trajectory_options(t_opt)
                    result = traj.send_trajectory(timeout=10)
                    self.last_activity = rospy.Time.now()
                    if result is None:
                        rospy.logerr("Trajectory failed to send")
                    elif not result.result:
                        rospy.logerr(
                            'Motion controller failed to complete the trajectory with error %s',
                            result.errorId)
                else:
                    rospy.logwarn("Unknown type %", mtype)
        else:
            rospy.logerr("Incorrect inputs to execute_trajectory")
            return
Example #6
0
    def goto_cartesian(self, x, y, z):
        print("goto_cartesian called with x={}, y={}, z={}".format(x, y, z))
        limb = Limb()
        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

        wpt_opts = MotionWaypointOptions()
        waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)

        joint_names = limb.joint_names()
        endpoint_state = limb.tip_state('right_hand')
        if endpoint_state is None:
            print('Endpoint state not found')
            return self.MOVE_ERROR
        pose = endpoint_state.pose

        pose.position.x = x
        pose.position.y = y
        pose.position.z = z
        pose.orientation.x = self.orientation_x
        pose.orientation.y = self.orientation_y
        pose.orientation.z = self.orientation_z
        pose.orientation.w = self.orientation_w
        poseStamped = PoseStamped()
        poseStamped.pose = pose
        waypoint.set_cartesian_pose(poseStamped, 'right_hand', [])

        traj.append_waypoint(waypoint.to_msg())

        result = traj.send_trajectory()
        if result is None:
            print("Trajectory FAILED to send")
            return self.MOVE_ERROR

        if result.result:
            print('Motion controller successfully finished the trajectory!')
            self.cur_x = x
            self.cur_y = y
            self.cur_z = z
            return self.MOVE_SUCCESS
        else:
            print('Motion controller failed to complete the trajectory %s',
                  result.errorId)
            return self.MOVE_ERROR
Example #7
0
def gripper_pose(x, y, z):
    limb = Limb()
    traj_options = TrajectoryOptions()
    traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
    traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

    wpt_opts = MotionWaypointOptions()
    waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)

    joint_names = limb.joint_names()
    endpoint_state = limb.tip_state('right_hand')
    if endpoint_state is None:
        print('Endpoint state not found')
        return False
    pose = endpoint_state.pose

    pose.position.x = x
    pose.position.y = y
    pose.position.z = z

    pose.orientation.x = 0
    pose.orientation.y = 0
    pose.orientation.z = 0
    pose.orientation.w = 1

    poseStamped = PoseStamped()
    poseStamped.pose = pose
    waypoint.set_cartesian_pose(poseStamped, 'right_hand', [])

    traj.append_waypoint(waypoint.to_msg())

    result = traj.send_trajectory()
    if result is None:
        print("Trajectory FAILED to send")
        return False

    if result.result:
        return True
    else:
        print('Motion controller failed to complete the trajectory %s',
              result.errorId)
        return False
    def gen_rand_waypoint(self):
        newX = (random.random() / 5) - 0.1
        newY = (random.random() / 5) - 0.7
        newZ = (random.random() / 5) + 0.4

        newPose = PoseStamped()
        newPose.header = Header(stamp=rospy.Time.now(), frame_id='base')
        newPose.pose.position.x = newX
        newPose.pose.position.y = newY
        newPose.pose.position.z = newZ
        newPose.pose.orientation.x = 0.5
        newPose.pose.orientation.y = -0.5
        newPose.pose.orientation.z = 0.5
        newPose.pose.orientation.w = 0.5

        limb = Limb()
        wpt_opts = MotionWaypointOptions(max_joint_speed_ratio=1.0,
                                         max_joint_accel=1.0,
                                         corner_distance=0.05)
        waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)
        waypoint.set_cartesian_pose(newPose, "right_hand",
                                    limb.joint_ordered_angles())

        self.waypoints.append(waypoint)
Example #9
0
def cartesian_pose(args):
    """
    Move the robot arm to the specified configuration.
    Call using:
    $ rosrun intera_examples go_to_cartesian_pose.py  [arguments: see below]

    -p 0.4 -0.3 0.18 -o 0.0 1.0 0.0 0.0 -t right_hand
    --> Go to position: x=0.4, y=-0.3, z=0.18 meters
    --> with quaternion orientation (0, 1, 0, 0) and tip name right_hand
    --> The current position or orientation will be used if only one is provided.

    -q 0.0 -0.9 0.0 1.8 0.0 -0.9 0.0
    --> Go to joint angles: 0.0 -0.9 0.0 1.8 0.0 -0.9 0.0 using default settings
    --> If a Cartesian pose is not provided, Forward kinematics will be used
    --> If a Cartesian pose is provided, the joint angles will be used to bias the nullspace

    -R 0.01 0.02 0.03 0.1 0.2 0.3 -T
    -> Jog arm with Relative Pose (in tip frame)
    -> x=0.01, y=0.02, z=0.03 meters, roll=0.1, pitch=0.2, yaw=0.3 radians
    -> The fixed position and orientation paramters will be ignored if provided

    
    arg_fmt = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=arg_fmt,
                                     description="cartesian_pose.__doc__")
    parser.add_argument(
        "-p", "--position", type=float,
        nargs='+',
        help="Desired end position: X, Y, Z")
    parser.add_argument(
        "-o", "--orientation", type=float,
        nargs='+',
        help="Orientation as a quaternion (x, y, z, w)")
    parser.add_argument(
        "-R", "--relative_pose", type=float,
        nargs='+',
        help="Jog pose by a relative amount in the base frame: X, Y, Z, roll, pitch, yaw")
    parser.add_argument(
        "-T", "--in_tip_frame", action='store_true',
        help="For relative jogs, job in tip frame (default is base frame)")
    parser.add_argument(
        "-q", "--joint_angles", type=float,
        nargs='+', default=[],
        help="A list of joint angles, one for each of the 7 joints, J0...J6")
    parser.add_argument(
        "-t",  "--tip_name", default='right_hand',
        help="The tip name used by the Cartesian pose")
    parser.add_argument(
        "--linear_speed", type=float, default=0.6,
        help="The max linear speed of the endpoint (m/s)")
    parser.add_argument(
        "--linear_accel", type=float, default=0.6,
        help="The max linear acceleration of the endpoint (m/s/s)")
    parser.add_argument(
        "--rotational_speed", type=float, default=1.57,
        help="The max rotational speed of the endpoint (rad/s)")
    parser.add_argument(
        "--rotational_accel", type=float, default=1.57,
        help="The max rotational acceleration of the endpoint (rad/s/s)")
    parser.add_argument(
        "--timeout", type=float, default=None,
        help="Max time in seconds to complete motion goal before returning. None is interpreted as an infinite timeout.")
    """

    try:
        #rospy.init_node('go_to_cartesian_pose_py')
        limb = Limb()

        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

        wpt_opts = MotionWaypointOptions(
            max_linear_speed=args.linear_speed,
            max_linear_accel=args.linear_accel,
            max_rotational_speed=args.rotational_speed,
            max_rotational_accel=args.rotational_accel,
            max_joint_speed_ratio=1.0)
        waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)

        joint_names = limb.joint_names()

        if args.joint_angles and len(args.joint_angles) != len(joint_names):
            rospy.logerr('len(joint_angles) does not match len(joint_names!)')
            return None

        if (args.position is None and args.orientation is None
                and args.relative_pose is None):
            if args.joint_angles:
                # does Forward Kinematics
                waypoint.set_joint_angles(args.joint_angles, args.tip_name,
                                          joint_names)
            else:
                rospy.loginfo(
                    "No Cartesian pose or joint angles given. Using default")
                waypoint.set_joint_angles(joint_angles=None,
                                          active_endpoint=args.tip_name)
        else:
            endpoint_state = limb.tip_state(args.tip_name)
            if endpoint_state is None:
                rospy.logerr('Endpoint state not found with tip name %s',
                             args.tip_name)
                return None
            pose = endpoint_state.pose

            if args.relative_pose is not None:
                if len(args.relative_pose) != 6:
                    rospy.logerr(
                        'Relative pose needs to have 6 elements (x,y,z,roll,pitch,yaw)'
                    )
                    return None
                # create kdl frame from relative pose
                rot = PyKDL.Rotation.RPY(args.relative_pose[3],
                                         args.relative_pose[4],
                                         args.relative_pose[5])
                trans = PyKDL.Vector(args.relative_pose[0],
                                     args.relative_pose[1],
                                     args.relative_pose[2])
                f2 = PyKDL.Frame(rot, trans)
                # and convert the result back to a pose message
                if args.in_tip_frame:
                    # end effector frame
                    pose = posemath.toMsg(posemath.fromMsg(pose) * f2)
                else:
                    # base frame
                    pose = posemath.toMsg(f2 * posemath.fromMsg(pose))
            else:
                if args.position is not None and len(args.position) == 3:
                    pose.position.x = args.position[0]
                    pose.position.y = args.position[1]
                    pose.position.z = args.position[2]
                if args.orientation is not None and len(args.orientation) == 4:
                    pose.orientation.x = args.orientation[0]
                    pose.orientation.y = args.orientation[1]
                    pose.orientation.z = args.orientation[2]
                    pose.orientation.w = args.orientation[3]
            poseStamped = PoseStamped()
            poseStamped.pose = pose
            waypoint.set_cartesian_pose(poseStamped, args.tip_name,
                                        args.joint_angles)

        rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

        traj.append_waypoint(waypoint.to_msg())

        result = traj.send_trajectory(timeout=args.timeout)
        if result is None:
            rospy.logerr('Trajectory FAILED to send')
            return

        if result.result:
            rospy.loginfo(
                'Motion controller successfully finished the trajectory!')
        else:
            rospy.logerr(
                'Motion controller failed to complete the trajectory with error %s',
                result.errorId)
    except rospy.ROSInterruptException:
        rospy.logerr(
            'Keyboard interrupt detected from the user. Exiting before trajectory completion.'
        )
Example #10
0
def go_to_cartesian(position=None,
                    orientation=None,
                    joint_angles=None,
                    linear_speed=0.1,
                    rotational_speed=0.57,
                    linear_accel=0.3,
                    tip_name='right_hand',
                    relative_pose=None,
                    rotational_accel=0.57,
                    timeout=None):

    if not rospy.is_shutdown():
        try:
            limb = Limb()

            traj_options = TrajectoryOptions()
            traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
            traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

            wpt_opts = MotionWaypointOptions(
                max_linear_speed=linear_speed,
                max_linear_accel=linear_accel,
                max_rotational_speed=rotational_speed,
                max_rotational_accel=rotational_accel,
                max_joint_speed_ratio=1.0)
            waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)

            joint_names = limb.joint_names()

            if joint_angles and len(joint_angles) != len(joint_names):
                rospy.logerr(
                    'len(joint_angles) does not match len(joint_names!)')
                return None

            if (position is None and orientation is None
                    and relative_pose is None):
                if joint_angles:
                    # does Forward Kinematics
                    waypoint.set_joint_angles(joint_angles, tip_name,
                                              joint_names)
                else:
                    rospy.loginfo(
                        "No Cartesian pose or joint angles given. Using default"
                    )
                    waypoint.set_joint_angles(joint_angles=None,
                                              active_endpoint=tip_name)
            else:
                endpoint_state = limb.tip_state(tip_name)
                if endpoint_state is None:
                    rospy.logerr('Endpoint state not found with tip name %s',
                                 tip_name)
                    return None
                pose = endpoint_state.pose

                if relative_pose is not None:
                    if len(relative_pose) != 6:
                        rospy.logerr(
                            'Relative pose needs to have 6 elements (x,y,z,roll,pitch,yaw)'
                        )
                        return None
                    # create kdl frame from relative pose
                    rot = PyKDL.Rotation.RPY(relative_pose[3],
                                             relative_pose[4],
                                             relative_pose[5])
                    trans = PyKDL.Vector(relative_pose[0], relative_pose[1],
                                         relative_pose[2])
                    f2 = PyKDL.Frame(rot, trans)
                    # and convert the result back to a pose message
                    if in_tip_frame:
                        # end effector frame
                        pose = posemath.toMsg(posemath.fromMsg(pose) * f2)
                    else:
                        # base frame
                        pose = posemath.toMsg(f2 * posemath.fromMsg(pose))
                else:
                    if position is not None:
                        pose.position.x = position.x
                        pose.position.y = position.y
                        pose.position.z = position.z
                    if orientation is not None:
                        pose.orientation.x = orientation.x
                        pose.orientation.y = orientation.y
                        pose.orientation.z = orientation.z
                        pose.orientation.w = orientation.w
                poseStamped = PoseStamped()
                poseStamped.pose = pose
                waypoint.set_cartesian_pose(poseStamped, tip_name,
                                            joint_angles)

            #rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

            traj.append_waypoint(waypoint.to_msg())

            result = traj.send_trajectory(timeout=timeout)
            if result is None:
                return

            if result.result:
                rospy.loginfo(
                    'Motion controller successfully finished the trajectory!')
            else:
                rospy.logerr(
                    'Motion controller failed to complete the trajectory with error %s',
                    result.errorId)
        except rospy.ROSInterruptException:
            rospy.logerr(
                'Keyboard interrupt detected from the user. Exiting before trajectory completion.'
            )
Example #11
0
  def cart_move_to(self, target_pos, tout=None, relative_mode=False,  wait_for_result=True):
    #
    # for Motion Controller Interface
    _trajectory_opts=TrajectoryOptions()
    _trajectory_opts.interpolation_type=TrajectoryOptions.CARTESIAN

    #
    self._motion_trajectory=MotionTrajectory(trajectory_options=_trajectory_opts, limb=self._limb)
    #
    # set Waypoint Options
    _wpt_opts=MotionWaypointOptions(max_linear_speed=self._linear_speed,
                                       max_linear_accel=self._linear_accel,
                                       max_rotational_speed=self._rotational_speed,
                                       max_rotational_accel=self._rotational_accel,
                                       max_joint_speed_ratio=1.0)
    _waypoint=MotionWaypoint(options=_wpt_opts, limb=self._limb)

    #
    endpoint_state=self._limb.tip_state(self._tip_name)
    pose=endpoint_state.pose

    ########################################
    #  set target position

    if relative_mode:
      # relative position : target_pos -> x, y, z, roll, pitch, yew
      trans = PyKDL.Vector(target_pos[0],target_pos[1],target_pos[2])
      rot = PyKDL.Rotation.RPY(target_pos[3], target_pos[4],target_pos[5])
      f2 = PyKDL.Frame(rot, trans)

      if self._in_tip_frame:
        # endpoint's cartesian systems
        pose=posemath.toMsg(posemath.fromMsg(pose) * f2)
      else:
        # base's cartesian systems
        pose=posemath.toMsg(f2 * posemath.fromMsg(pose))
    else:
      #  global position : x, y, z, rx, ry, rz, rw
      pose.position.x=target_pos[0]
      pose.position.y=target_pos[1]
      pose.position.z=target_pos[2]
      pose.orientation.x=target_pos[3]
      pose.orientation.y=target_pos[4]
      pose.orientation.z=target_pos[5]
      pose.orientation.w=target_pos[6]
    #
    ###########################################
    # set target position.
    poseStamped=PoseStamped()
    poseStamped.pose=pose
    _waypoint.set_cartesian_pose(poseStamped, self._tip_name, [])
    self._motion_trajectory.append_waypoint(_waypoint.to_msg())
    #
    # run motion...
    self._light.head_green()
    result=self._motion_trajectory.send_trajectory( wait_for_result=wait_for_result,timeout=tout)

    #
    if result is None:
      self._light.head_yellow()
      print("Trajectory FAILED to send")
      return None
    #
    if not wait_for_result : return True
    #
    if result.result: self._light.head_on()
    else: self._light.head_red()
    #
    self._motion_trajectory=None
    return result.result
Example #12
0
pose_goal.orientation.w = OR_W
pose_goal.orientation.x = OR_X
pose_goal.orientation.y = OR_Y
pose_goal.orientation.z = OR_Z
pose_goal.position.x = BASE_X
pose_goal.position.y = BASE_Y
pose_goal.position.z = BASE_Z

poseStamped = PoseStamped()
poseStamped.pose = pose_goal

traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

joint_angles = limb.joint_ordered_angles()
waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)
waypoint.set_cartesian_pose(poseStamped, 'right_hand', joint_angles)

traj.append_waypoint(waypoint.to_msg())

result = traj.send_trajectory(timeout=5.0)

rate = rospy.Rate(30.0)  # SUGGEST - Try 10 or more
while not rospy.is_shutdown():
    try:
        (trans, rot) = listener.lookupTransform('kinect/user_1/torso',
                                                'kinect/user_1/right_hand',
                                                rospy.Time(0))
    except (tf.LookupException, tf.ConnectivityException,
            tf.ExtrapolationException) as e:
        rospy.loginfo('user_1 not found:' + str(type(e)))
        try:
    def run(self):
        rate = rospy.Rate(100)
        limb = Limb()
        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)

        wpt_opts = MotionWaypointOptions(max_joint_speed_ratio=0.5,
                                         max_joint_accel=0.5,
                                         corner_distance=0.05)
        waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)

        self.pose.header = Header(stamp=rospy.Time.now(), frame_id='base')
        self.pose.pose.position.x = 0.0
        self.pose.pose.position.y = -0.6
        self.pose.pose.position.z = 0.5
        self.pose.pose.orientation.x = 0.5
        self.pose.pose.orientation.y = -0.5
        self.pose.pose.orientation.z = 0.5
        self.pose.pose.orientation.w = 0.5

        joint_angles = limb.joint_ordered_angles()
        waypoint.set_cartesian_pose(self.pose, "right_hand", joint_angles)
        self.waypoints.append(waypoint)

        rospy.loginfo("Sending inital waypoint: %s",
                      self.waypoints[0].to_string())
        traj.append_waypoint(self.waypoints[0].to_msg())

        result = traj.send_trajectory()
        if result is None:
            rospy.logerr('Trajectory FAILED to send')

        elif result.result:
            rospy.loginfo(
                'Motion controller successfully finished the trajectory!')
        else:
            rospy.logerr(
                'Motion controller failed to complete the trajectory with error %s',
                result.errorId)
            traj.clear_waypoints()

        l = Lights()
        l_name = 'head_green_light'
        initial_state = l.get_light_state(l_name)
        for i in range(0, 2):
            state = not initial_state
            l.set_light_state(l_name, state)
            rospy.sleep(0.5)
            state = not state
            l.set_light_state(l_name, state)
            rospy.sleep(0.5)

        l.set_light_state(l_name, True)

        for i in range(0, 19):
            self.gen_rand_waypoint()

        sendCommand = True

        while not rospy.is_shutdown():
            traj.clear_waypoints()
            for i in range(0, 19):
                self.waypoints.pop(i)
                self.gen_rand_waypoint()

            for point in self.waypoints:
                traj.append_waypoint(point.to_msg())

            print(len(self.waypoints))
            result = traj.send_trajectory(wait_for_result=True)

            self.firstShutdown = True

            def clean_shutdown():
                if self.firstShutdown:
                    print("STOPPING TRAJECTORY")
                    traj.stop_trajectory()
                    traj.clear_waypoints()

                    l = Lights()
                    l.set_light_state('head_green_light', False)
                    self.firstShutdown = False

            rospy.on_shutdown(clean_shutdown)
            rate.sleep()
        return
Example #14
0
def moveTo(myArgs):
    arg_fmt = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=arg_fmt,
                                     description=main_server.__doc__)
    parser.add_argument(
        "-p", "--position", type=float,
        nargs='+',
        help="Desired end position: X, Y, Z")
    parser.add_argument(
        "-o", "--orientation", type=float,
        nargs='+',
        help="Orientation as a quaternion (x, y, z, w)")
    parser.add_argument(
        "-R", "--relative_pose", type=float,
        nargs='+',
        help="Jog pose by a relative amount in the base frame: X, Y, Z, roll, pitch, yaw")
    parser.add_argument(
        "-T", "--in_tip_frame", action='store_true',
        help="For relative jogs, job in tip frame (default is base frame)")
    parser.add_argument(
        "-q", "--joint_angles", type=float,
        nargs='+', default=[],
        help="A list of joint angles, one for each of the 7 joints, J0...J6")
    parser.add_argument(
        "--timeout", type=float, default=None,
        help="Max time in seconds to complete motion goal before returning. None is interpreted as an infinite timeout.")
    args = parser.parse_args(myArgs.call.split(" "))
    print(args.position)
    #test_string = ['-p','0.5', '0.3', '0.5']
    #args = parser.parse_args(test_string)

    try:
        limb = Limb()

        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options = traj_options, limb = limb)

        wpt_opts = MotionWaypointOptions(max_linear_speed=0.4,
                                         max_linear_accel=0.4,
                                         max_rotational_speed=1.57,
                                         max_rotational_accel=1.5,
                                         max_joint_speed_ratio=1.0)
        waypoint = MotionWaypoint(options = wpt_opts.to_msg(), limb = limb)

        joint_names = limb.joint_names()

        if args.joint_angles and len(args.joint_angles) != len(joint_names):
            rospy.logerr('len(joint_angles) does not match len(joint_names!)')
            return "failed"

        if (args.position is None and args.orientation is None
            and args.relative_pose is None):
            if args.joint_angles:
                # does Forward Kinematics
                waypoint.set_joint_angles(args.joint_angles,'right_hand', joint_names)
            else:
                rospy.loginfo("No Cartesian pose or joint angles given. Using default")
                waypoint.set_joint_angles(joint_angles=None, active_endpoint='right_hand')
        else:
            endpoint_state = limb.tip_state('right_hand')
            if endpoint_state is None:
                rospy.logerr('Endpoint state not found with tip name %s', 'right_hand')
                return "failed"
            pose = endpoint_state.pose

            if args.relative_pose is not None:
                if len(args.relative_pose) != 6:
                    rospy.logerr('Relative pose needs to have 6 elements (x,y,z,roll,pitch,yaw)')
                    return "failed"
                # create kdl frame from relative pose
                rot = PyKDL.Rotation.RPY(args.relative_pose[3],
                                         args.relative_pose[4],
                                         args.relative_pose[5])
                trans = PyKDL.Vector(args.relative_pose[0],
                                     args.relative_pose[1],
                                     args.relative_pose[2])
                f2 = PyKDL.Frame(rot, trans)
                # and convert the result back to a pose message
                if args.in_tip_frame:
                  # end effector frame
                  pose = posemath.toMsg(posemath.fromMsg(pose) * f2)
                else:
                  # base frame
                  pose = posemath.toMsg(f2 * posemath.fromMsg(pose))
            else:
                if args.position is not None and len(args.position) == 3:
                    pose.position.x = args.position[0]
                    pose.position.y = args.position[1]
                    pose.position.z = args.position[2]
                if args.orientation is not None and len(args.orientation) == 4:
                    pose.orientation.x = args.orientation[0]
                    pose.orientation.y = args.orientation[1]
                    pose.orientation.z = args.orientation[2]
                    pose.orientation.w = args.orientation[3]
            poseStamped = PoseStamped()
            poseStamped.pose = pose
            waypoint.set_cartesian_pose(poseStamped, 'right_hand', args.joint_angles)

        rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

        traj.append_waypoint(waypoint.to_msg())

        result = traj.send_trajectory(timeout=args.timeout)
        if result is None:
            rospy.logerr('Trajectory FAILED to send')
            return 'Trajectory FAILED to send'

        if result.result:
            rospy.loginfo('Motion controller successfully finished the trajectory!')
            return 'Motion Success'
        else:
            rospy.logerr('Motion controller failed to complete the trajectory with error %s',
                         result.errorId)
            return result.errorId

    except rospy.ROSInterruptException:
        rospy.logerr('Keyboard interrupt detected from the user. Exiting before trajectory completion.')
    return "failed"
Example #15
0
	def go_to_cartesian_pose(self, position = None, orientation = None, relative_pose = None,
		in_tip_frame = False, joint_angles = None, tip_name = 'right_hand',
		linear_speed = 0.6, linear_accel = 0.6, rotational_speed = 1.57,
		rotational_accel = 1.57, timeout = None, endpoint_pose = None):
		
		traj_options = TrajectoryOptions()
		traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
		traj = MotionTrajectory(trajectory_options = traj_options, limb = self)

		wpt_opts = MotionWaypointOptions(max_linear_speed=linear_speed,
										 max_linear_accel=linear_accel,
										 max_rotational_speed=rotational_speed,
										 max_rotational_accel=rotational_accel,
										 max_joint_speed_ratio=1.0)
		waypoint = MotionWaypoint(options = wpt_opts.to_msg(), limb = self)

		joint_names = self.joint_names()

		if joint_angles and len(joint_angles) != len(joint_names):
			rospy.logerr('len(joint_angles) does not match len(joint_names!)')
			return None

		if (position is None and orientation is None and relative_pose is None and endpoint_pose is None):
			if joint_angles:
				# does Forward Kinematics
				waypoint.set_joint_angles(joint_angles, tip_name, joint_names)
			else:
				rospy.loginfo("No Cartesian pose or joint angles given. Using default")
				waypoint.set_joint_angles(joint_angles=None, active_endpoint=args.tip_name)
		else:
			endpoint_state = self.tip_state(tip_name)
			if endpoint_state is None:
				rospy.logerr('Endpoint state not found with tip name %s', tip_name)
				return None
			pose = endpoint_state.pose

			if relative_pose is not None:
				if len(relative_pose) != 6:
					rospy.logerr('Relative pose needs to have 6 elements (x,y,z,roll,pitch,yaw)')
					return None
				# create kdl frame from relative pose
				rot = PyKDL.Rotation.RPY(relative_pose[3],
										 relative_pose[4],
										 relative_pose[5])
				trans = PyKDL.Vector(relative_pose[0],
									 relative_pose[1],
									 relative_pose[2])
				f2 = PyKDL.Frame(rot, trans)
				# and convert the result back to a pose message
				if in_tip_frame:
				  # end effector frame
				  pose = posemath.toMsg(posemath.fromMsg(pose) * f2)
				else:
				  # base frame
				  pose = posemath.toMsg(f2 * posemath.fromMsg(pose))
			else:
				if endpoint_pose is None:
					if position is not None and len(position) == 3:
						pose.position.x = position[0]
						pose.position.y = position[1]
						pose.position.z = position[2]
					if orientation is not None and len(orientation) == 4:
						pose.orientation.x = orientation[0]
						pose.orientation.y = orientation[1]
						pose.orientation.z = orientation[2]
						pose.orientation.w = orientation[3]
				else:
					pose.position.x = endpoint_pose['position'].x
					pose.position.y = endpoint_pose['position'].y
					pose.position.z = endpoint_pose['position'].z
					pose.orientation.x = endpoint_pose['orientation'].x
					pose.orientation.y = endpoint_pose['orientation'].y
					pose.orientation.z = endpoint_pose['orientation'].z
					pose.orientation.w = endpoint_pose['orientation'].w
			poseStamped = PoseStamped()
			poseStamped.pose = pose

			if not joint_angles:
				# using current joint angles for nullspace bais if not provided
				joint_angles = self.joint_ordered_angles()
				print(poseStamped.pose)
				waypoint.set_cartesian_pose(poseStamped, tip_name, joint_angles)
			else:
				waypoint.set_cartesian_pose(poseStamped, tip_name, joint_angles)

		#rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

		traj.append_waypoint(waypoint.to_msg())

		result = traj.send_trajectory(timeout=timeout)
		if result is None:
			rospy.logerr('Trajectory FAILED to send')
			return

		if result.result:
			rospy.loginfo('Motion controller successfully finished the trajectory!')
		else:
			rospy.logerr('Motion controller failed to complete the trajectory with error %s',
						 result.errorId)
Example #16
0
class CircularMotion():
    def __init__(self):
        self.mover = move_to_point.MoveToPoint()
        self.retrieve_height = -0.015
        self._limb = Limb()
        self.traj_options = TrajectoryOptions()
        self.traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        self.traj = MotionTrajectory(trajectory_options=self.traj_options,
                                     limb=self._limb)
        self.wpt_options = MotionWaypointOptions(max_linear_speed=0.4,
                                                 max_linear_accel=0.4,
                                                 max_rotational_speed=1.57,
                                                 max_rotational_accel=1.57,
                                                 max_joint_speed_ratio=1.0)
        self.waypoint = MotionWaypoint(options=self.wpt_options.to_msg(),
                                       limb=self._limb)
        self.joint_names = self._limb.joint_names()
        endpoint_state = self._limb.tip_state('right_hand')
        self.pose = endpoint_state.pose

    def to_quaternion(self, roll, pitch, yaw):
        cy = math.cos(0.5 * yaw)
        sy = math.sin(0.5 * yaw)
        cr = math.cos(0.5 * roll)
        sr = math.sin(0.5 * roll)
        cp = math.cos(0.5 * pitch)
        sp = math.sin(0.5 * pitch)

        qx = cy * sr * cp - sy * cr * sp
        qy = cy * cr * sp + sy * sr * cp
        qz = sy * cr * cp - cy * sr * sp
        qw = cy * cr * cp + sy * sr * sp

        orientation = [qx, qy, qz, qw]
        return orientation

    def displacement(self, time):
        disp = 0.1667 * math.pi * math.sin(time)
        return disp

    def move(self, cur_pos):
        curr_roll = 1.1667 * math.pi
        curr_pitch = 0
        curr_yaw = 0
        self.mover.move(cur_pos[0], cur_pos[1], self.retrieve_height,
                        cur_pos[3], cur_pos[4], cur_pos[5], cur_pos[6])
        rospy.sleep(1)
        time = 0

        while time < 2 * math.pi:

            end = self.to_quaternion(curr_roll, curr_pitch, curr_yaw)
            self.pose.position.x = cur_pos[0]
            self.pose.position.y = cur_pos[1]
            self.pose.position.z = self.retrieve_height
            self.pose.orientation.x = end[0]
            self.pose.orientation.y = end[1]
            self.pose.orientation.z = end[2]
            self.pose.orientation.w = end[3]

            if time < 0.5 * math.pi:
                curr_roll = 1.1667 * math.pi - self.displacement(time)
            elif time < math.pi:
                curr_roll = 0.833 * math.pi + self.displacement(time)
            elif time < 1.5 * math.pi:
                curr_roll = 0.833 * math.pi - self.displacement(time)
            else:
                curr_roll = 1.1667 * math.pi + self.displacement(time)

            curr_pitch = self.displacement(time)
            time = time + 0.1

            poseStamped = PoseStamped()
            poseStamped.pose = self.pose
            self.waypoint.set_cartesian_pose(poseStamped, 'right_hand', [])
            self.traj.append_waypoint(self.waypoint.to_msg())

        result = self.traj.send_trajectory(timeout=None)
            	self.prevX = nextX
            	self.prevY = nextY
            
            	newPose = PoseStamped()
            	newPose.header = Header(stamp=rospy.Time.now(), frame_id='base')
            	newPose.pose.position.x = nextX
            	newPose.pose.position.y = nextY
            	newPose.pose.position.z = nextZ
            	newPose.pose.orientation.x = q[0]
            	newPose.pose.orientation.y = q[1]
            	newPose.pose.orientation.z = q[2]
            	newPose.pose.orientation.w = q[3]
            
            	wpt_opts = MotionWaypointOptions(max_linear_speed=7.0, max_linear_accel=5.0, corner_distance=0.085)
            	waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)
            	waypoint.set_cartesian_pose(newPose, "right_hand", limb.joint_ordered_angles())
            	self.waypoints.append(copy(waypoint))
            	if len(self.waypoints) > 240:
            		self.waypoints.pop(0)

    def run(self):
        rate = rospy.Rate(100)
        limb = Limb()
        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options=traj_options, limb=limb)
    
        wpt_opts = MotionWaypointOptions(max_linear_speed=7.0, max_linear_accel=1.5, corner_distance=0.05)
        waypoint = MotionWaypoint(options=wpt_opts.to_msg(), limb=limb)
        
        q_base = quaternion_from_euler(0, math.pi/2, 0)
Example #18
0
def move2cartesian(position=None, orientation=None, relative_pose=None, in_tip_frame=False, joint_angles=[],
         tip_name='right_hand', linear_speed=0.6, linear_accel=0.6, rotational_speed=1.57,
         rotational_accel=1.57, timeout=None, neutral=False):
    """
    Move the robot arm to the specified configuration.
    Call using:
    $ rosrun intera_examples go_to_cartesian_pose.py  [arguments: see below]
    -p 0.4 -0.3 0.18 -o 0.0 1.0 0.0 0.0 -t right_hand
    --> Go to position: x=0.4, y=-0.3, z=0.18 meters
    --> with quaternion orientation (0, 1, 0, 0) and tip name right_hand
    --> The current position or orientation will be used if only one is provided.
    -q 0.0 -0.9 0.0 1.8 0.0 -0.9 0.0
    --> Go to joint angles: 0.0 -0.9 0.0 1.8 0.0 -0.9 0.0 using default settings
    --> If a Cartesian pose is not provided, Forward kinematics will be used
    --> If a Cartesian pose is provided, the joint angles will be used to bias the nullspace
    -R 0.01 0.02 0.03 0.1 0.2 0.3 -T
    -> Jog arm with Relative Pose (in tip frame)
    -> x=0.01, y=0.02, z=0.03 meters, roll=0.1, pitch=0.2, yaw=0.3 radians
    -> The fixed position and orientation paramters will be ignored if provided
    """

    try:
        #rospy.init_node('go_to_cartesian_pose_py')
        limb = Limb()

        traj_options = TrajectoryOptions()
        traj_options.interpolation_type = TrajectoryOptions.CARTESIAN
        traj = MotionTrajectory(trajectory_options = traj_options, limb = limb)

        wpt_opts = MotionWaypointOptions(max_linear_speed=linear_speed,
                                         max_linear_accel=linear_accel,
                                         max_rotational_speed=rotational_speed,
                                         max_rotational_accel=rotational_accel,
                                         max_joint_speed_ratio=1.0)
        waypoint = MotionWaypoint(options = wpt_opts.to_msg(), limb = limb)

        joint_names = limb.joint_names()

        if joint_angles and len(joint_angles) != len(joint_names):
            rospy.logerr('len(joint_angles) does not match len(joint_names!)')
            return None

        if neutral == True:
            limb.move_to_neutral()
        else:
            if (position is None and orientation is None and relative_pose is None):
                if joint_angles:
                    # does Forward Kinematics
                    waypoint.set_joint_angles(joint_angles, tip_name, joint_names)
                else:
                    rospy.loginfo("No Cartesian pose or joint angles given. Using default")
                    waypoint.set_joint_angles(joint_angles=None, active_endpoint=tip_name)
            else:
                endpoint_state = limb.tip_state(tip_name)
                if endpoint_state is None:
                    rospy.logerr('Endpoint state not found with tip name %s', tip_name)
                    return None
                pose = endpoint_state.pose

                if relative_pose is not None:
                    if len(relative_pose) != 6:
                        rospy.logerr('Relative pose needs to have 6 elements (x,y,z,roll,pitch,yaw)')
                        return None
                    # create kdl frame from relative pose
                    rot = PyKDL.Rotation.RPY(relative_pose[3],
                                             relative_pose[4],
                                             relative_pose[5])
                    trans = PyKDL.Vector(relative_pose[0],
                                         relative_pose[1],
                                         relative_pose[2])
                    f2 = PyKDL.Frame(rot, trans)
                    # and convert the result back to a pose message
                    if in_tip_frame:
                      # end effector frame
                      pose = posemath.toMsg(posemath.fromMsg(pose) * f2)
                    else:
                      # base frame
                      pose = posemath.toMsg(f2 * posemath.fromMsg(pose))
                else:
                    if position is not None and len(position) == 3:
                        pose.position.x = position[0]
                        pose.position.y = position[1]
                        pose.position.z = position[2]
                    if orientation is not None and len(orientation) == 4:
                        pose.orientation.x = orientation[0]
                        pose.orientation.y = orientation[1]
                        pose.orientation.z = orientation[2]
                        pose.orientation.w = orientation[3]
                poseStamped = PoseStamped()
                poseStamped.pose = pose

                if not joint_angles:
                    # using current joint angles for nullspace bais if not provided
                    joint_angles = limb.joint_ordered_angles()
                    waypoint.set_cartesian_pose(poseStamped, tip_name, joint_angles)
                else:
                    waypoint.set_cartesian_pose(poseStamped, tip_name, joint_angles)

            rospy.loginfo('Sending waypoint: \n%s', waypoint.to_string())

            traj.append_waypoint(waypoint.to_msg())

            result = traj.send_trajectory(timeout=timeout)
            if result is None:
                rospy.logerr('Trajectory FAILED to send')
                return

            if result.result:
                rospy.loginfo('Motion controller successfully finished the trajectory!')
            else:
                rospy.logerr('Motion controller failed to complete the trajectory with error %s',
                             result.errorId)
                             
    except rospy.ROSInterruptException:
        rospy.logerr('Keyboard interrupt detected from the user. Exiting before trajectory completion.')