def setUp(self):
        # create a action client of move group
        self._move_client = SimpleActionClient('move_group', MoveGroupAction)
        self._move_client.wait_for_server()

        moveit_commander.roscpp_initialize(sys.argv)
        group_name = moveit_commander.RobotCommander().get_group_names()[0]
        group = moveit_commander.MoveGroupCommander(group_name)

        # prepare a joint goal
        self._goal = MoveGroupGoal()
        self._goal.request.group_name = group_name
        self._goal.request.max_velocity_scaling_factor = 0.1
        self._goal.request.max_acceleration_scaling_factor = 0.1
        self._goal.request.start_state.is_diff = True

        goal_constraint = Constraints()
        joint_values = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
        joint_names = group.get_active_joints()
        for i in range(len(joint_names)):
            joint_constraint = JointConstraint()
            joint_constraint.joint_name = joint_names[i]
            joint_constraint.position = joint_values[i]
            joint_constraint.weight = 1.0
            goal_constraint.joint_constraints.append(joint_constraint)

        self._goal.request.goal_constraints.append(goal_constraint)
        self._goal.planning_options.planning_scene_diff.robot_state.is_diff = True
Beispiel #2
0
    def _cmd_to_request(self, robot):
        """Transforms the gripper command to a MotionPlanRequest."""
        req = MotionPlanRequest()

        # Set general info
        req.planner_id = "PTP"
        req.group_name = self._planning_group
        req.max_velocity_scaling_factor = self._vel_scale * robot.global_motion_factor
        req.max_acceleration_scaling_factor = self._acc_scale * robot.global_motion_factor
        req.allowed_planning_time = 1.0
        # Set an empty diff as start_state => the current state is used by the planner
        req.start_state.is_diff = True

        # create goal constraints
        goal_constraints = Constraints()
        if isinstance(self._goal, (float, int, long)):
            joint_names = robot._robot_commander.get_group(self._planning_group).get_active_joints()

            if len(joint_names) != 1:
                raise IndexError("PG70 should have only one joint. But group " + req.group_name +
                                 " contains " + str(len(joint_names)) + " joints.")

            joint_constraint = JointConstraint()
            joint_constraint.joint_name = joint_names[0]
            joint_constraint.position = float(self._goal)
            joint_constraint.weight = 1
            goal_constraints.joint_constraints.append(joint_constraint)

        else:
            raise NotImplementedError("Unknown type of goal is given.")

        req.goal_constraints.append(goal_constraints)

        return req
Beispiel #3
0
    def add_way_points(self, waypoints):

        arm = self.arm

        # 限制末端夹具运动
        right_joint_const = JointConstraint()
        right_joint_const.joint_name = "gripper_r_joint_r"
        right_joint_const.position = 0
        right_joint_const.weight = 1.0
        # 施加全约束
        consts = Constraints()
        consts.joint_constraints = [right_joint_const]
        arm.set_path_constraints(consts)

        wpose = arm.get_current_pose().pose
        wpose.orientation.x = Qux
        wpose.orientation.y = Quy
        wpose.orientation.z = Quz
        wpose.orientation.w = Quw
        wpose.position.x = a[5]
        wpose.position.y = a[3]
        wpose.position.z = a[4]

        waypoints.append(copy.deepcopy(wpose))

        # print waypoints
        # print "----------------\n"
        return waypoints
    def setUp(self):
        # create a action client of move group
        self._move_client = SimpleActionClient('move_group', MoveGroupAction)
        self._move_client.wait_for_server()

        moveit_commander.roscpp_initialize(sys.argv)
        group_name = moveit_commander.RobotCommander().get_group_names()[0]
        group = moveit_commander.MoveGroupCommander(group_name)

        # prepare a joint goal
        self._goal = MoveGroupGoal()
        self._goal.request.group_name = group_name
        self._goal.request.max_velocity_scaling_factor = 0.1
        self._goal.request.max_acceleration_scaling_factor = 0.1
        self._goal.request.start_state.is_diff = True

        goal_constraint = Constraints()
        joint_values = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
        joint_names = group.get_active_joints()
        for i in range(len(joint_names)):
            joint_constraint = JointConstraint()
            joint_constraint.joint_name = joint_names[i]
            joint_constraint.position = joint_values[i]
            joint_constraint.weight = 1.0
            goal_constraint.joint_constraints.append(joint_constraint)

        self._goal.request.goal_constraints.append(goal_constraint)
        self._goal.planning_options.planning_scene_diff.robot_state.is_diff = True
    def right_arm_go_to_pose_goal(self):
        # 设置动作对象变量,此处为arm
        right_arm = self.right_arm

        # Create a path constraint for the arm
        # UNCOMMENT TO ENABLE ORIENTATION CONSTRAINTS
        joint_const = JointConstraint()
        joint_const.joint_name = "gripper_r_joint_r"
        joint_const.position = 0
        consts = Constraints()
        consts.joint_constraints = [joint_const]
        right_arm.set_path_constraints(consts)

        # 获取当前末端执行器位置姿态
        pose_goal = right_arm.get_current_pose().pose
        # print (a)
        # print (Qux, Quy, Quz, Quw)
        # 设置动作对象目标位置姿态
        pose_goal.orientation.x = Right_Qux
        pose_goal.orientation.y = Right_Quy
        pose_goal.orientation.z = Right_Quz
        pose_goal.orientation.w = Right_Quw
        pose_goal.position.x = Neurondata[5]
        pose_goal.position.y = Neurondata[3]
        pose_goal.position.z = Neurondata[4]
        right_arm.set_pose_target(pose_goal)
        print "End effector pose %s" % pose_goal

        # 规划和输出动作
        traj = right_arm.plan()
        right_arm.execute(traj, wait=False)
        # 动作完成后清除目标信息
        right_arm.clear_pose_targets()
        # 确保没有剩余未完成动作在执行
        right_arm.stop()
Beispiel #6
0
    def _cmd_to_request(self, robot):
        """Transforms the given command to a MotionPlanRequest."""
        req = MotionPlanRequest()

        # Set general info
        req.planner_id = self._planner_id
        req.group_name = self._planning_group
        req.max_velocity_scaling_factor = self._vel_scale
        req.max_acceleration_scaling_factor = self._acc_scale
        req.allowed_planning_time = 1.0

        # Set an empty diff as start_state => the current state is used by the planner
        req.start_state.is_diff = True

        # Set goal constraint
        if self._goal is None:
            raise NameError("Goal is not given.")

        goal_constraints = Constraints()

        # goal as Pose in Cartesian space
        if isinstance(self._goal, Pose):
            goal_pose = self._get_goal_pose(robot)

            robot_reference_frame = robot._robot_commander.get_planning_frame()
            goal_constraints.orientation_constraints.append(
                _to_ori_constraint(goal_pose, robot_reference_frame,
                                   self._target_link))
            goal_constraints.position_constraints.append(
                _to_pose_constraint(goal_pose, robot_reference_frame,
                                    self._target_link))

        # goal as list of int or float in joint space
        elif isinstance(self._goal, list):
            joint_names = robot._robot_commander.get_group(
                self._planning_group).get_active_joints()
            joint_values = self._get_joint_pose(robot)

            if len(joint_names) != len(joint_values):
                raise IndexError(
                    "Given joint goal does not match the planning group " +
                    req.group_name + ".")

            for joint_name, joint_value in zip(joint_names, joint_values):
                joint_constraint = JointConstraint()
                joint_constraint.joint_name = joint_name
                joint_constraint.position = joint_value
                joint_constraint.weight = 1
                goal_constraints.joint_constraints.append(joint_constraint)

        else:
            raise NotImplementedError("Unknown type of goal is given.")

        req.goal_constraints.append(goal_constraints)

        return req
Beispiel #7
0
    def right_arm_go_to_pose_goal(self):
        # 设置动作对象变量,此处为arm
        right_arm = self.right_arm

        # 获取当前末端执行器位置姿态
        pose_goal = right_arm.get_current_pose().pose

        # 限制末端夹具运动
        right_joint_const = JointConstraint()
        right_joint_const.joint_name = "gripper_r_joint_r"
        # if Rightfinger > -55 :
        #     right_joint_const.position = 0.024
        # else:
        right_joint_const.position = 0
        right_joint_const.weight = 1.0
        # 施加全约束
        consts = Constraints()
        consts.joint_constraints = [right_joint_const]
        right_arm.set_path_constraints(consts)

        # 计算夹取姿态
        if obj_theta <= 0:
            (Qux, Quy, Quz,
             Quw) = quaternion_from_euler(90.01 / 180 * pi, 0,
                                          (-180 - obj_theta) / 180 * pi)
        else:
            (Qux, Quy, Quz,
             Quw) = quaternion_from_euler(90.01 / 180 * pi, 0,
                                          (180 - obj_theta) / 180 * pi)

        # (Qux, Quy, Quz, Quw) = quaternion_from_euler(90/180*pi, 0, -180/180*pi)

        # 设置动作对象目标位置姿态
        pose_goal.orientation.x = Qux
        pose_goal.orientation.y = Quy
        pose_goal.orientation.z = Quz
        pose_goal.orientation.w = Quw
        # pose_goal.position.y = 0.0244387395252 + (-0.595877665686-0.0244387395252)*obj_x/320
        # pose_goal.position.x = 0.625989932306 + (0.197518221397-0.625989932306)*obj_y/240
        pose_goal.position.x = 0.1819576873 + (160 - obj_y) * (
            0.494596343128 - 0.1819576873) / 160
        pose_goal.position.y = obj_x * (
            -0.455644324437 + 0.0238434066464) / 220 - 0.0238434066464
        pose_goal.position.z = 0.0942404372508
        right_arm.set_pose_target(pose_goal)
        print "End effector pose %s" % pose_goal

        # 规划和输出动作
        traj = right_arm.plan()
        right_arm.execute(traj, wait=False)
        # 动作完成后清除目标信息
        right_arm.clear_pose_targets()
        # 清除路径约束
        right_arm.clear_path_constraints()
        # 确保没有剩余未完成动作在执行
        right_arm.stop()
Beispiel #8
0
    def plan_trajectory(self, start_point, goal_point, planner_number, joint_names, group_name, planning_time, planner_config_name):
        """
          Given a start and goal point, returns the planned path.

          Args:
            start_point (list of float): A starting joint configuration.
            goal_point (list of float): A goal joint configuration.
            planner_number (int): The index of the planner to be used as
              returned by acquire_planner().
            joint_names (list of str): The name of the joints corresponding to
              start_point and goal_point.
            group_name (str): The name of the group to which the joint names
              correspond.
            planning_time (float): Maximum allowed time for planning, in seconds.
            planner_config_name (str): Type of planner to use.
          Return:
            list of list of float: A sequence of points representing the joint
              configurations at each point on the path.
        """
        planner_client = rospy.ServiceProxy(self.planners[planner_number], GetMotionPlan)
        rospy.loginfo("Plan Trajectory Wrapper: got a plan_trajectory request for %s with start = %s and goal = %s" % (self.planners[planner_number], start_point, goal_point))
        # Put together the service request.
        req = GetMotionPlanRequest()
        req.motion_plan_request.workspace_parameters.header.stamp = rospy.get_rostime()
        req.motion_plan_request.group_name = group_name
        req.motion_plan_request.num_planning_attempts = 1
        req.motion_plan_request.allowed_planning_time = planning_time
        req.motion_plan_request.planner_id = planner_config_name #using RRT planner by default

        req.motion_plan_request.start_state.joint_state.header.stamp = rospy.get_rostime()
        req.motion_plan_request.start_state.joint_state.name = joint_names
        req.motion_plan_request.start_state.joint_state.position = start_point

        req.motion_plan_request.goal_constraints.append(Constraints())
        req.motion_plan_request.goal_constraints[0].joint_constraints = []
        for i in xrange(len(joint_names)):
            temp_constraint = JointConstraint()
            temp_constraint.joint_name = joint_names[i]
            temp_constraint.position = goal_point[i]
            temp_constraint.tolerance_above = 0.05;
            temp_constraint.tolerance_below = 0.05;
            req.motion_plan_request.goal_constraints[0].joint_constraints.append(temp_constraint)

        #call the planner
        rospy.wait_for_service(self.planners[planner_number])
        rospy.loginfo("Plan Trajectory Wrapper: sent request to service %s" % planner_client.resolved_name)
        try:
            response = planner_client(req)
        except rospy.ServiceException, e:
            rospy.loginfo("Plan Trajectory Wrapper: service call failed: %s"%e)
            return None
Beispiel #9
0
    def right_arm_go_down_goal(self):
        # 设置动作对象变量,此处为arm
        right_arm = self.right_arm

        waypoints = []

        # 获取当前末端执行器位置姿态
        pose_goal = right_arm.get_current_pose().pose

        # 添加路径起始点
        waypoints.append(copy.deepcopy(pose_goal))

        # 限制末端夹具运动
        right_joint_const = JointConstraint()
        right_joint_const.joint_name = "gripper_r_joint_r"
        # if Rightfinger > -55 :
        #     right_joint_const.position = 0.024
        # else:
        right_joint_const.position = 0.0239
        right_joint_const.weight = 1.0
        # 施加全约束
        consts = Constraints()
        consts.joint_constraints = [right_joint_const]
        right_arm.set_path_constraints(consts)

        # 设置动作对象目标位置姿态
        pose_goal.position.z = pose_goal.position.z - 0.045
        # pose_goal.position.y = pose_goal.position.y - 0.1

        # 添加路径末端点
        waypoints.append(copy.deepcopy(pose_goal))

        # 路径规划
        (plan, fraction) = right_arm.compute_cartesian_path(
            waypoints,  # waypoints to follow
            0.01,  # eef_step
            0.0)  # jump_threshold

        print "End effector pose %s" % waypoints

        # robot = self.robot
        # display_trajectory_publisher = self.display_trajectory_publisher

        # display_trajectory = moveit_msgs.msg.DisplayTrajectory()
        # display_trajectory.trajectory_start = robot.get_current_state()
        # display_trajectory.trajectory.append(plan)
        # display_trajectory_publisher.publish(display_trajectory)

        # 规划和输出动作
        right_arm.execute(plan, wait=False)
def make_moveit_action_goal(joint_names, joint_positions):
    goal_config_constraint = Constraints()
    for name, position in zip(joint_names, joint_positions):
        joint_constraint = JointConstraint()
        joint_constraint.joint_name = name
        joint_constraint.position = position
        goal_config_constraint.joint_constraints.append(joint_constraint)

    req = MotionPlanRequest()
    req.group_name = 'both_arms'
    req.goal_constraints.append(goal_config_constraint)

    goal = MoveGroupGoal()
    goal.request = req
    return goal
Beispiel #11
0
    def send_move_group_joint_space_goal(self, move_group, joint_names, joint_values, plan_only=None):
        '''
        Retrieve the current move group action configuration and send the move request

        @param move_group           : string specifying a particular move group
        @param joint_names          : list of joint names for command
        @param joint_values         : list of joint values for target
        '''

        # We should have already set this pairing up during initialization
        action_topic = ProxyMoveItClient._move_group_clients_[move_group]

        # Get the latest setup of of the MoveGroup goal data
        goal = MoveGroupGoal()
        goal.request          = copy.deepcopy(ProxyMoveItClient._motion_plan_requests[move_group])
        goal.planning_options = copy.deepcopy(ProxyMoveItClient._planning_options[move_group])

        if (plan_only is not None):
            goal.planning_options.plan_only = plan_only

        goal_constraints = Constraints()
        for i in range(len(joint_names)):
                jc = ProxyMoveItClient._joint_constraints[move_group][joint_names[i]]
                goal_constraints.joint_constraints.append(JointConstraint(
                        joint_name=joint_names[i],
                        position=joint_values[i],
                        tolerance_above=jc.tolerance_above,
                        tolerance_below=jc.tolerance_above,
                        weight=jc.weight))

        goal.request.goal_constraints.append(goal_constraints)

        ProxyMoveItClient._action_clients[action_topic].send_goal(action_topic, goal)
	def on_enter(self, userdata):
		self._planning_failed = False
		self._control_failed = False
		self._success = False

		self._action_topic = userdata.move_group_prefix + userdata.action_topic
		self._client = ProxyActionClient({self._action_topic: MoveGroupAction})

		self._move_group = userdata.move_group
		self._joint_names = None


		self._joint_names = userdata.joint_names

		action_goal = MoveGroupGoal()
		action_goal.request.group_name = self._move_group
		goal_constraints = Constraints()
		for i in range(len(self._joint_names)):
			goal_constraints.joint_constraints.append(JointConstraint(joint_name=self._joint_names[i], position=userdata.joint_values[i]))
		action_goal.request.goal_constraints.append(goal_constraints)

		try:
			self._client.send_goal(self._action_topic, action_goal)
		except Exception as e:
			Logger.logwarn('Failed to send action goal for group: %s\n%s' % (self._move_group, str(e)))
			self._planning_failed = True
Beispiel #13
0
    def on_enter(self, userdata):
        self._planning_failed = False
        self._control_failed = False
        self._success = False
        self._config_name = userdata.config_name  # Currently not used
        self._robot_name = userdata.robot_name  # Currently not used
        self._move_group = userdata.move_group
        self._action_topic = userdata.action_topic
        self._joint_config = userdata.joint_values
        self._joint_names = userdata.joint_names

        self._client = ProxyActionClient({self._action_topic: MoveGroupAction})

        # Action Initialization
        action_goal = MoveGroupGoal()
        action_goal.request.group_name = self._move_group
        action_goal.request.allowed_planning_time = 1.0
        goal_constraints = Constraints()
        for i in range(len(self._joint_names)):
            goal_constraints.joint_constraints.append(
                JointConstraint(joint_name=self._joint_names[i],
                                position=self._joint_config[i],
                                weight=1.0))
        action_goal.request.goal_constraints.append(goal_constraints)

        try:
            self._client.send_goal(self._action_topic, action_goal)
            userdata.action_topic = self._action_topic  # Save action topic to output key
        except Exception as e:
            Logger.logwarn('Failed to send action goal for group: %s\n%s' %
                           (self._move_group, str(e)))
            self._planning_failed = True
Beispiel #14
0
    def __init__(self, frame, ns = ''):
        # self.scene_pub = PlanningScenePublisher(ns)

        self.move_group_client = SimpleActionClient("/{}/move_group".format(ns), MoveGroupAction)     
        self.move_group_client.wait_for_server()
        
        self.move_group_msg = MoveGroupGoal()

        #Create the message for the request
        self.move_group_msg.request = MotionPlanRequest()

        self.move_group_msg.request.workspace_parameters.header.frame_id = frame
        self.move_group_msg.request.workspace_parameters.min_corner.x = -50
        self.move_group_msg.request.workspace_parameters.min_corner.y = -50
        self.move_group_msg.request.workspace_parameters.min_corner.z = 0
        self.move_group_msg.request.workspace_parameters.max_corner.x = 50
        self.move_group_msg.request.workspace_parameters.max_corner.y = 50
        self.move_group_msg.request.workspace_parameters.max_corner.z = 50

        # Target definition      
        self.move_group_msg.request.goal_constraints.append(Constraints())

        self.constraints = JointConstraint()
        self.constraints.tolerance_above = 0.001
        self.constraints.tolerance_below = 0.001
        self.constraints.weight = 1.0

        for i in range(0,7):
            self.move_group_msg.request.goal_constraints[0].joint_constraints.append(copy.deepcopy(self.constraints))

        self.move_group_msg.planning_options.planning_scene_diff.is_diff = True
        self.move_group_msg.planning_options.plan_only = True
Beispiel #15
0
    def on_enter(self, userdata):
        self._planning_failed = False
        self._control_failed = False
        self._success = False
        self._joint_config = userdata.joint_values
        self._joint_names = userdata.joint_names

        self._sub = ProxySubscriberCached({self._position_topic: JointState})
        self._current_position = []

        self._client = ProxyActionClient({self._action_topic: MoveGroupAction})

        # Action Initialization
        action_goal = MoveGroupGoal()
        action_goal.request.group_name = self._move_group
        action_goal.request.allowed_planning_time = 1.0
        goal_constraints = Constraints()
        for i in range(len(self._joint_names)):
            goal_constraints.joint_constraints.append(
                JointConstraint(joint_name=self._joint_names[i],
                                position=self._joint_config[i],
                                weight=1.0))
        action_goal.request.goal_constraints.append(goal_constraints)

        try:
            self._client.send_goal(self._action_topic, action_goal)
        except Exception as e:
            Logger.logwarn('Failed to send action goal for group: %s\n%s' %
                           (self._move_group, str(e)))
            self._planning_failed = True
Beispiel #16
0
        def on_enter(self, userdata):
                self._param_error     = False
                self._planning_failed = False
                self._control_failed  = False
                self._success         = False

                #Parameter check
                if self._srdf_param is None:
                        self._param_error = True
                        return

                try:
                        self._srdf = ET.fromstring(self._srdf_param)
                except Exception as e:
                        Logger.logwarn('Unable to parse given SRDF parameter: /robot_description_semantic')
                        self._param_error = True

                if not self._param_error:

                        robot = None
                        for r in self._srdf.iter('robot'):
                                if self._robot_name == '' or self._robot_name == r.attrib['name']:
                                        robot = r
                                        break
                        if robot is None:
                                Logger.logwarn('Did not find robot name in SRDF: %s' % self._robot_name)
                                return 'param_error'

                        config = None
                        for c in robot.iter('group_state'):
                                if (self._move_group == '' or self._move_group == c.attrib['group']) \
                                and c.attrib['name'] == self._config_name:
                                        config = c
                                        break
                        if config is None:
                                Logger.logwarn('Did not find config name in SRDF: %s' % self._config_name)
                                return 'param_error'

                        try:
                                self._joint_config = [float(j.attrib['value']) for j in config.iter('joint')]
                                self._joint_names  = [str(j.attrib['name']) for j in config.iter('joint')]
                        except Exception as e:
                                Logger.logwarn('Unable to parse joint values from SRDF:\n%s' % str(e))
                                return 'param_error'


                        #Action Initialization
                        action_goal = MoveGroupGoal()
                        action_goal.request.group_name = self._move_group
                        goal_constraints = Constraints()
                        for i in range(len(self._joint_names)):
                                goal_constraints.joint_constraints.append(JointConstraint(joint_name=self._joint_names[i], position=self._joint_config[i]))
                        action_goal.request.goal_constraints.append(goal_constraints)

                        try:
                                self._client.send_goal(self._action_topic, action_goal)
                        except Exception as e:
                                Logger.logwarn('Failed to send action goal for group: %s\n%s' % (self._move_group, str(e)))
                                self._planning_failed = True
    def left_arm_go_to_pose_goal(self):
        # 设置动作对象变量,此处为arm
        left_arm = self.left_arm
        # 限制末端夹具运动
        left_joint_const = JointConstraint()
        left_joint_const.joint_name = "gripper_l_joint_r"
        if Leftfinger >= 0.025:
            left_joint_const.position = 0.024
        else:
            left_joint_const.position = 0
        consts = Constraints()
        consts.joint_constraints = [left_joint_const]
        left_arm.set_path_constraints(consts)

        # 获取当前末端执行器位置姿态
        pose_goal = left_arm.get_current_pose().pose

        # 设置动作对象目标位置姿态
        pose_goal.orientation.x = Left_Qux
        pose_goal.orientation.y = Left_Quy
        pose_goal.orientation.z = Left_Quz
        pose_goal.orientation.w = Left_Quw
        pose_goal.position.x = (Neurondata[11] - 0.05) * 1.48 + 0.053
        pose_goal.position.y = (Neurondata[9] - 0.18) * 1.48 + 0.12
        pose_goal.position.z = (Neurondata[10] - 0.53) * 1.48 + 0.47
        left_arm.set_pose_target(pose_goal)
        print "End effector pose %s" % pose_goal

        # # 设置动作对象目标位置姿态
        # pose_goal.orientation.x = pose_goal.orientation.x
        # pose_goal.orientation.y = pose_goal.orientation.y
        # pose_goal.orientation.z = pose_goal.orientation.z
        # pose_goal.orientation.w = pose_goal.orientation.w
        # pose_goal.position.x = pose_goal.position.x
        # pose_goal.position.y = pose_goal.position.y - 0.01
        # pose_goal.position.z = pose_goal.position.z
        # left_arm.set_pose_target(pose_goal)
        # print "End effector pose %s" % pose_goal

        # 规划和输出动作
        traj = left_arm.plan()
        left_arm.execute(traj, wait=False)
        # 动作完成后清除目标信息
        left_arm.clear_pose_targets()
        # 确保没有剩余未完成动作在执行
        left_arm.stop()
    def right_arm_go_to_pose_goal(self):
        # 设置动作对象变量,此处为arm
        right_arm = self.right_arm
        # 限制末端夹具运动
        right_joint_const = JointConstraint()
        right_joint_const.joint_name = "gripper_r_joint_r"
        if Rightfinger >= 0.025:
            right_joint_const.position = 0.024
        else:
            right_joint_const.position = 0
        consts = Constraints()
        consts.joint_constraints = [right_joint_const]
        right_arm.set_path_constraints(consts)
        # 获取当前末端执行器位置姿态
        pose_goal = right_arm.get_current_pose().pose

        # 设置动作对象目标位置姿态
        pose_goal.orientation.x = Right_Qux
        pose_goal.orientation.y = Right_Quy
        pose_goal.orientation.z = Right_Quz
        pose_goal.orientation.w = Right_Quw
        pose_goal.position.x = (Neurondata[5] - 0.05) * 1.48 + 0.053
        pose_goal.position.y = (Neurondata[3] + 0.18) * 1.48 - 0.12
        pose_goal.position.z = (Neurondata[4] - 0.53) * 1.48 + 0.47
        right_arm.set_pose_target(pose_goal)
        print "End effector pose %s" % pose_goal

        # # 设置动作对象目标位置姿态
        # pose_goal.orientation.x = pose_goal.orientation.x
        # pose_goal.orientation.y = pose_goal.orientation.y
        # pose_goal.orientation.z = pose_goal.orientation.z
        # pose_goal.orientation.w = pose_goal.orientation.w
        # pose_goal.position.x = pose_goal.position.x
        # pose_goal.position.y = pose_goal.position.y - 0.01
        # pose_goal.position.z = pose_goal.position.z
        # right_arm.set_pose_target(pose_goal)
        # print "End effector pose %s" % pose_goal

        # 规划和输出动作
        traj = right_arm.plan()
        right_arm.execute(traj, wait=False)
        # 动作完成后清除目标信息
        right_arm.clear_pose_targets()
        # 确保没有剩余未完成动作在执行
        right_arm.stop()
    def create_move_group_joints_goal(self,
                                      joint_names,
                                      joint_values,
                                      group="right_arm",
                                      plan_only=False):
        """ Creates a move_group goal based on pose.
        @arg joint_names list of strings of the joint names
        @arg joint_values list of digits with the joint values
        @arg group string representing the move_group group to use
        @arg plan_only bool to for only planning or planning and executing
        @return MoveGroupGoal with the desired contents"""

        header = Header()
        header.frame_id = 'base_link'
        header.stamp = rospy.Time.now()
        moveit_goal = MoveGroupGoal()
        goal_c = Constraints()
        for name, value in zip(joint_names, joint_values):
            joint_c = JointConstraint()
            joint_c.joint_name = name
            joint_c.position = value
            joint_c.tolerance_above = 0.01
            joint_c.tolerance_below = 0.01
            joint_c.weight = 1.0
            goal_c.joint_constraints.append(joint_c)

        moveit_goal.request.goal_constraints.append(goal_c)
        moveit_goal.request.num_planning_attempts = 5
        moveit_goal.request.allowed_planning_time = 5.0
        moveit_goal.planning_options.plan_only = plan_only
        moveit_goal.planning_options.planning_scene_diff.is_diff = True
        moveit_goal.request.group_name = group

        return moveit_goal
Beispiel #20
0
 def execute(self, userdata):
     header = Header()
     header.frame_id = 'base_link'
     header.stamp = rospy.Time.now()
     userdata.move_it_joint_goal =  MoveGroupGoal()
     goal_c = Constraints()
     for name, value in zip(userdata.manip_joint_names, userdata.manip_goal_joint_pose):
         joint_c = JointConstraint()
         joint_c.joint_name = name
         joint_c.position = value
         joint_c.tolerance_above = 0.01
         joint_c.tolerance_below = 0.01
         joint_c.weight = 1.0
         goal_c.joint_constraints.append(joint_c)
     
     userdata.move_it_joint_goal.request.goal_constraints.append(goal_c)
     userdata.move_it_joint_goal.request.num_planning_attempts = 5
     userdata.move_it_joint_goal.request.allowed_planning_time = 5.0
     userdata.move_it_joint_goal.planning_options.plan_only = False #False = Plan + Execute ; True = Plan only
     userdata.move_it_joint_goal.planning_options.planning_scene_diff.is_diff = True
     userdata.move_it_joint_goal.request.group_name = userdata.manip_joint_group
     rospy.loginfo('Group Name: ' + userdata.manip_joint_group)
     rospy.loginfo('Joints name: ' + str(userdata.manip_joint_names))
     rospy.loginfo('Joints Values: ' + str(userdata.manip_goal_joint_pose))
     
     
     rospy.loginfo('GOAL TO SEND IS:... ' + str(userdata.move_it_joint_goal))
     return 'succeeded'
Beispiel #21
0
    def _create_get_motion_plan_request(self, start_point, goal_point, group_name, joint_names, planning_time):
        # Just puts together a MotionPlanRequest to send to the lightning node.
        req = GetMotionPlanRequest()
        req.motion_plan_request.group_name = group_name

        req.motion_plan_request.start_state.joint_state.name = joint_names
        req.motion_plan_request.start_state.joint_state.position = start_point

        req.motion_plan_request.goal_constraints.append(Constraints())
        req.motion_plan_request.goal_constraints[0].joint_constraints = []
        for i in xrange(len(joint_names)):
            tempConstraint = JointConstraint()
            tempConstraint.joint_name = joint_names[i]
            tempConstraint.position = goal_point[i]
            req.motion_plan_request.goal_constraints[0].joint_constraints.append(tempConstraint)

        req.motion_plan_request.allowed_planning_time = planning_time
        return req
Beispiel #22
0
def init_constraint():
    joint_constraint = JointConstraint()
    joint_constraint.joint_name = "shoulder_pan_joint"
    joint_constraint.position = 0
    joint_constraint.tolerance_above = 0.7854
    joint_constraint.tolerance_below = 0.7854
    joint_constraint.weight = 1
    base_constraint.joint_constraints.append(joint_constraint)
Beispiel #23
0
    def init_gripper(self):
        """
        Initialise gripper interface.
        """

        # Gripper
        self.gripper_group_name = "hand"
        self.gripper_joints = ["panda_finger_joint1", "panda_finger_joint2"]
        self.gripper_links = ["panda_leftfinger", "panda_rightfinger"]
        self.gripper_max_speed = 0.2

        # Service client for IK
        self.plan_gripper_path_client = self.create_client(
            GetMotionPlan, "plan_kinematic_path")
        while not self.plan_gripper_path_client.wait_for_service(
                timeout_sec=1.0):
            self.get_logger().info(
                "Service [plan_kinematic_path] not currently available, waiting..."
            )

        self.gripper_path_request = GetMotionPlan.Request()
        self.gripper_path_request.motion_plan_request.workspace_parameters.header.frame_id = \
            self.arm_base_link
        # self.gripper_path_request.motion_plan_request.workspace_parameters.header.stamp = \
        # "Set during request"
        self.gripper_path_request.motion_plan_request.workspace_parameters.min_corner.x = -0.855
        self.gripper_path_request.motion_plan_request.workspace_parameters.min_corner.y = -0.855
        self.gripper_path_request.motion_plan_request.workspace_parameters.min_corner.z = -0.36
        self.gripper_path_request.motion_plan_request.workspace_parameters.max_corner.x = 0.855
        self.gripper_path_request.motion_plan_request.workspace_parameters.max_corner.y = 0.855
        self.gripper_path_request.motion_plan_request.workspace_parameters.max_corner.z = 1.19
        # self.gripper_path_request.motion_plan_request.start_state = "Ignored"
        self.gripper_path_request.motion_plan_request.goal_constraints = \
            [Constraints()]
        (self.gripper_path_request.motion_plan_request.goal_constraints[0].
         joint_constraints.append(JointConstraint()))
        (self.gripper_path_request.motion_plan_request.goal_constraints[0].
         joint_constraints[0].joint_name) = self.gripper_joints[0]
        # (self.gripper_path_request.motion_plan_request.goal_constraints[0].joint_constraints[0]
        # .position) = "Set during request"
        # (self.gripper_path_request.motion_plan_request.goal_constraints[0].joint_constraints[0]
        # .tolerance_above) = "Ignored"
        # (self.gripper_path_request.motion_plan_request.goal_constraints[0].joint_constraints[0]
        # .tolerance_below) = "Ignored"
        self.gripper_path_request.motion_plan_request.goal_constraints[
            0].joint_constraints[0].weight = 1.0
        # self.gripper_path_request.motion_plan_request.path_constraints = "Ignored"
        # self.gripper_path_request.motion_plan_request.trajectory_constraints = "Ignored"
        # self.gripper_path_request.motion_plan_request.reference_trajectories = "Ignored"
        # self.gripper_path_request.motion_plan_request.planner_id = "Ignored"
        self.gripper_path_request.motion_plan_request.group_name = self.gripper_group_name
        self.gripper_path_request.motion_plan_request.num_planning_attempts = 1
        self.gripper_path_request.motion_plan_request.allowed_planning_time = 0.1
        # self.gripper_path_request.motion_plan_request.max_velocity_scaling_factor = \
        # "Set during request"
        self.gripper_path_request.motion_plan_request.max_acceleration_scaling_factor = 0.0
Beispiel #24
0
    def left_arm_go_to_pose_goal(self):
        # 设置动作对象变量,此处为arm
        left_arm = self.left_arm

        # 获取当前末端执行器位置姿态
        pose_goal = left_arm.get_current_pose().pose

        # 限制末端夹具运动
        left_joint_const = JointConstraint()
        left_joint_const.joint_name = "gripper_l_joint_r"
        # if Leftfinger > -60 :
        #     left_joint_const.position = 0.024
        # else:
        left_joint_const.position = 0
        left_joint_const.weight = 1.0

        # 施加全约束
        consts = Constraints()
        consts.joint_constraints = [left_joint_const]
        # consts.orientation_constraints = [left_orientation_const]
        # consts.position_constraints = [left_position_const]
        left_arm.set_path_constraints(consts)

        # 设置动作对象目标位置姿态
        pose_goal.orientation.x = -0.626215011187053
        pose_goal.orientation.y = -0.4552380340595104
        pose_goal.orientation.z = -0.48010690496799074
        pose_goal.orientation.w = 0.4124444834298159
        pose_goal.position.x = (Neurondata[11] - 0.05) * 1.48 + 0.053
        pose_goal.position.y = (Neurondata[9] - 0.18) * 1.48 + 0.12
        pose_goal.position.z = (Neurondata[10] - 0.53) * 1.48 + 0.47
        left_arm.set_pose_target(pose_goal)
        print "End effector pose %s" % pose_goal

        # 规划和输出动作
        traj = left_arm.plan()
        left_arm.execute(traj, wait=False)
        # 动作完成后清除目标信息
        left_arm.clear_pose_targets()
        # 清除路径约束
        left_arm.clear_path_constraints()
        # 确保没有剩余未完成动作在执行
        left_arm.stop()
Beispiel #25
0
def quick_motion_test_client():
  rospy.wait_for_service('/lightning/lightning_get_path')
  print "Working on it..."
  req = GetMotionPlanRequest()
  req.motion_plan_request.group_name = "torso"
  req.motion_plan_request.start_state.joint_state.name = ["torso_lift_joint"]
  req.motion_plan_request.start_state.joint_state.position = [float(0.2)]
  tempConstraint = JointConstraint()
  tempConstraint.joint_name = req.motion_plan_request.start_state.joint_state.name[0]
  tempConstraint.position = float(0.15)
  fullConstraint = Constraints()
  fullConstraint.joint_constraints = [tempConstraint]
  req.motion_plan_request.goal_constraints = [fullConstraint]
  req.motion_plan_request.allowed_planning_time = 50.0
  try:
    client_func = rospy.ServiceProxy('/lightning/lightning_get_path', GetMotionPlan)
    res = client_func(req)
  except rospy.ServiceException, e:
    print "Service call failed: %s"%e
Beispiel #26
0
    def plan_cartesian_path(self, waypoints):

        arm = self.arm

        # 限制末端夹具运动
        right_joint_const = JointConstraint()
        right_joint_const.joint_name = "gripper_r_joint_r"
        right_joint_const.position = 0
        right_joint_const.weight = 1.0
        # 施加全约束
        consts = Constraints()
        consts.joint_constraints = [right_joint_const]
        arm.set_path_constraints(consts)

        (plan, fraction) = arm.compute_cartesian_path(
            waypoints,  # waypoints to follow
            0.01,  # eef_step
            0.0)  # jump_threshold

        return plan, fraction
Beispiel #27
0
    def set_global_defaults( self, group ):
        """
        Initializes the proxy with default parameters to use with connections
        @param group : string move group name
        """

        # Default planning parameters for new connections
        num_planning_attempts=5
        allowed_planning_time=10.0
        plan_only=True
        planner_id='RRTConnectkConfigDefault'

        # Set the default plan request data
        plan_request = MotionPlanRequest()
        plan_request.start_state.is_diff = True # Flags start state as empty to use current state on server
        plan_request.num_planning_attempts  = num_planning_attempts
        plan_request.allowed_planning_time  = allowed_planning_time
        plan_request.planner_id             = planner_id
        plan_request.group_name             = group

        #@TODO - retrieve from ROS parameters
        ProxyMoveItClient._motion_plan_requests[group] = plan_request
        ProxyMoveItClient._default_motion_plan_requests[group] = copy.deepcopy(plan_request)

        planning_options = PlanningOptions()
        planning_options.plan_only     = plan_only
        planning_options.planning_scene_diff.robot_state.is_diff = True # Flags start state as empty to use current state on server

        #@TODO - retrieve from ROS parameters

        ProxyMoveItClient._planning_options[group] = planning_options
        ProxyMoveItClient._default_planning_options[group] = copy.deepcopy(planning_options)

        # Set up the default joint constraints
        joint_constraints = {}
        for name in ProxyMoveItClient._joint_names[group]:
            joint_constraints[name] = JointConstraint(joint_name=name, tolerance_above=0.05, tolerance_below=0.05,weight=1.0)

        #@TODO - retrieve from ROS parameters

        ProxyMoveItClient._joint_constraints[group]         = joint_constraints
        ProxyMoveItClient._default_joint_constraints[group] = copy.deepcopy(joint_constraints)

        # @TODO - add real constraints
        ProxyMoveItClient._position_constraints[group]            = []
        ProxyMoveItClient._default_position_constraints[group]    = []
        ProxyMoveItClient._orientation_constraints[group]         = []
        ProxyMoveItClient._default_orientation_constraints[group] = []
        ProxyMoveItClient._visibility_constraints[group]          = []
        ProxyMoveItClient._default_visibility_constraints[group]  = []

        ProxyMoveItClient._robot_states[group]          = RobotState()
        ProxyMoveItClient._default_robot_states[group]  = RobotState()
Beispiel #28
0
def quick_motion_test_client():
    rospy.wait_for_service('/lightning/lightning_get_path')
    print "Working on it..."
    req = GetMotionPlanRequest()
    req.motion_plan_request.group_name = "torso"
    req.motion_plan_request.start_state.joint_state.name = ["torso_lift_joint"]
    req.motion_plan_request.start_state.joint_state.position = [float(0.2)]
    tempConstraint = JointConstraint()
    tempConstraint.joint_name = req.motion_plan_request.start_state.joint_state.name[
        0]
    tempConstraint.position = float(0.15)
    fullConstraint = Constraints()
    fullConstraint.joint_constraints = [tempConstraint]
    req.motion_plan_request.goal_constraints = [fullConstraint]
    req.motion_plan_request.allowed_planning_time = 50.0
    try:
        client_func = rospy.ServiceProxy('/lightning/lightning_get_path',
                                         GetMotionPlan)
        res = client_func(req)
    except rospy.ServiceException, e:
        print "Service call failed: %s" % e
def create_move_group_joints_goal(joint_names, joint_values, group="right_arm_torso", plan_only=True):
    """ Creates a move_group goal based on pose.
    @arg joint_names list of strings of the joint names
    @arg joint_values list of digits with the joint values
    @arg group string representing the move_group group to use
    @arg plan_only bool to for only planning or planning and executing
    @return MoveGroupGoal with the desired contents"""
    
    header = Header()
    header.frame_id = 'base_link'
    header.stamp = rospy.Time.now()
    moveit_goal = MoveGroupGoal()
    goal_c = Constraints()
    for name, value in zip(joint_names, joint_values):
        joint_c = JointConstraint()
        joint_c.joint_name = name
        joint_c.position = value
        joint_c.tolerance_above = 0.01
        joint_c.tolerance_below = 0.01
        joint_c.weight = 1.0
        goal_c.joint_constraints.append(joint_c)

    moveit_goal.request.goal_constraints.append(goal_c)
    moveit_goal.request.num_planning_attempts = 1
    moveit_goal.request.allowed_planning_time = 5.0
    moveit_goal.planning_options.plan_only = plan_only
    moveit_goal.planning_options.planning_scene_diff.is_diff = True
    moveit_goal.request.group_name = group
    
    return moveit_goal
    def execute(self, userdata):
        header = Header()
        header.frame_id = "base_link"
        header.stamp = rospy.Time.now()
        userdata.move_it_joint_goal = MoveGroupGoal()
        goal_c = Constraints()
        for name, value in zip(userdata.manip_joint_names, userdata.manip_goal_joint_pose):
            joint_c = JointConstraint()
            joint_c.joint_name = name
            joint_c.position = value
            joint_c.tolerance_above = 0.01
            joint_c.tolerance_below = 0.01
            joint_c.weight = 1.0
            goal_c.joint_constraints.append(joint_c)

        userdata.move_it_joint_goal.request.goal_constraints.append(goal_c)
        userdata.move_it_joint_goal.request.num_planning_attempts = 5
        userdata.move_it_joint_goal.request.allowed_planning_time = 5.0
        userdata.move_it_joint_goal.planning_options.plan_only = False  # False = Plan + Execute ; True = Plan only
        userdata.move_it_joint_goal.planning_options.planning_scene_diff.is_diff = True
        userdata.move_it_joint_goal.request.group_name = userdata.manip_joint_group
        rospy.loginfo("Group Name: " + userdata.manip_joint_group)
        rospy.loginfo("Joints name: " + str(userdata.manip_joint_names))
        rospy.loginfo("Joints Values: " + str(userdata.manip_goal_joint_pose))

        rospy.loginfo("GOAL TO SEND IS:... " + str(userdata.move_it_joint_goal))
        return "succeeded"
Beispiel #31
0
    def plan_execute_pose_constraints_cb(self, goal):
        feedback = PlanExecutePoseConstraintsFeedback()
        result = PlanExecutePoseConstraintsResult()
        result.result = True

        #include default arm_base_joint // it is bug that moveit does not exclude passive joint in thier joint trajectory.
        js_base = JointConstraint()
        js_base.joint_name = "arm_base_joint"
        js_base.position = 0.0
        js_base.tolerance_above = 0.001
        js_base.tolerance_below = 0.001
        js_base.weight = 1.0

        self.contraints.name = "constraints"
        self.contraints.joint_constraints.append(js_base)
        print("==================== Joint Constraints ====================")
        for js in goal.joint_constraints:
            self.contraints.joint_constraints.append(js)
            print(js)
        self.group.set_path_constraints(self.contraints)
        print("============================================================")

        self.group.clear_pose_targets()
        self.group.set_start_state_to_current_state()

        try:
            self.group.set_pose_target(goal.target_pose)
        except MoveItCommanderException:
            result.result = False
            return

        rospy.loginfo('Planning goal pose...')
        plan1 = self.group.plan()

        if len(plan1.joint_trajectory.points) == 0:
            result.result = False
            return

        display_trajectory = moveit_msgs.msg.DisplayTrajectory()
        display_trajectory.trajectory_start = self.robot.get_current_state()
        display_trajectory.trajectory.append(plan1)
        self.traj_publisher.publish(display_trajectory)

        # rospy.sleep(0.5)

        rospy.loginfo('Start moving...')
        self.group.go(wait=True)
        rospy.loginfo('End moving')
        # rospy.sleep(2.0)
        self.group.set_path_constraints(None)
        self.contraints.joint_constraints = []

        rospy.loginfo('Planning goal pose succeeded.')
        self.action_plan_execute_pose_w_constraints.set_succeeded(result)
Beispiel #32
0
 def set_path_constraints(self, value):
     # In order to force planning in joint coordinates we add dummy joint
     # constrains.
     empty_joint_constraints = JointConstraint()
     empty_joint_constraints.joint_name = "r1_joint_grip"
     empty_joint_constraints.position = 0
     empty_joint_constraints.tolerance_above = 1.5
     empty_joint_constraints.tolerance_below = 1.5
     empty_joint_constraints.weight = 1
     value.joint_constraints.append(empty_joint_constraints)
     MoveGroupCommander.set_path_constraints(self, value)
Beispiel #33
0
    def _do_ik(self, px, py, pz, arm):
        """
          Does inverse kinematics for a given arm and given position.
          This solver is collision aware.

          Args:
            px, py, pz (float): Cartesian coordinates for position of arm end
              effector.
            arm (str): Which arm ("right_arm" or "left_arm") to do ik for.

          Returns:
            list: List of joint configuration for specific arm. Returns an
              empty list if unable to do IK.
        """
        IK_INFO_NAME = "/pr2_%s_kinematics/get_ik_solver_info" % (arm)
        IK_NAME = "/compute_ik"

        ik_solver_info_service_proxy = rospy.ServiceProxy(IK_INFO_NAME, GetKinematicSolverInfo)
        ik_info_req = GetKinematicSolverInfoRequest()
        rospy.loginfo("LightningTest: do_ik: Waiting for %s" % (IK_INFO_NAME))
        rospy.wait_for_service(IK_INFO_NAME)
        rospy.loginfo("About to get IK info.")
        ik_info_res = ik_solver_info_service_proxy(ik_info_req)
        rospy.loginfo("Got IK Solver info.")

        ik_solver_service_proxy = rospy.ServiceProxy(IK_NAME, GetPositionIK)
        ik_solve_req = GetPositionIKRequest()
        ik_solve_req.ik_request.group_name = arm
        ik_solve_req.ik_request.timeout = rospy.Duration(5.0)
        ik_solve_req.ik_request.ik_link_name = "%s_wrist_roll_link" % (arm[0])
        ik_solve_req.ik_request.pose_stamped.header.frame_id = "odom_combined"
        ik_solve_req.ik_request.pose_stamped.pose.position.x = px
        ik_solve_req.ik_request.pose_stamped.pose.position.y = py
        ik_solve_req.ik_request.pose_stamped.pose.position.z = pz
        ik_solve_req.ik_request.pose_stamped.pose.orientation.x = 0.0;
        ik_solve_req.ik_request.pose_stamped.pose.orientation.y = 0.0;
        ik_solve_req.ik_request.pose_stamped.pose.orientation.z = 0.0;
        ik_solve_req.ik_request.pose_stamped.pose.orientation.w = 1.0;
        # TODO: Consider retrieving current robto state.
        ik_solve_req.ik_request.robot_state.joint_state.name = ik_info_res.kinematic_solver_info.joint_names;
        for i in xrange(len(ik_info_res.kinematic_solver_info.joint_names)):
            joint_limits = ik_info_res.kinematic_solver_info.limits[i]
            ik_solve_req.ik_request.robot_state.joint_state.position.append((joint_limits.min_position + joint_limits.max_position)/2.0)
            joint_constraint = JointConstraint()
            joint_constraint.joint_name = ik_info_res.kinematic_solver_info.joint_names[i]
            joint_constraint.position = (joint_limits.max_position + joint_limits.min_position) / 2.0
            joint_constraint.tolerance_above = (joint_limits.max_position - joint_limits.min_position) / 2.0
            joint_constraint.tolerance_below = joint_constraint.tolerance_above
            ik_solve_req.ik_request.constraints.joint_constraints.append(joint_constraint)

        rospy.loginfo("LightningTest: do_ik: Waiting for IK service.")
        rospy.wait_for_service(IK_NAME)
        ik_solve_res = ik_solver_service_proxy(ik_solve_req)
        if ik_solve_res.error_code.val == ik_solve_res.error_code.SUCCESS:
            return ik_solve_res.solution.joint_state.position[30:37]
        else:
            rospy.loginfo("Lightning tester: cannot move to sampled position...trying another position")
            return []
    def plan_trajectory(self, start_point, goal_point, planner_number, joint_names, group_name, planning_time, planner_config_name, plan_type='pfs'):
        """
          Given a start and goal point, plan by classical planner.

          Args:
            start_point (list of float): A starting joint configuration.
            goal_point (list of float): A goal joint configuration.
            planner_number (int): The index of the planner to be used as
              returned by acquire_planner().
            joint_names (list of str): The name of the joints corresponding to
              start_point and goal_point.
            group_name (str): The name of the group to which the joint names
              correspond.
            planning_time (float): Maximum allowed time for planning, in seconds.
            planner_config_name (str): Type of planner to use.
            plan_type (str): either pfs or rr. If rr we don't use the path length threshold.
          Return:
            list of list of float: A sequence of points representing the joint
              configurations at each point on the path.
        """
        planner_client = rospy.ServiceProxy(self.planners[planner_number], GetMotionPlan)
        rospy.loginfo("%s Plan Trajectory Wrapper: got a plan_trajectory request for %s with start = %s and goal = %s"  \
                % (rospy.get_name(), self.planners[planner_number], start_point, goal_point))
        # Put together the service request.
        req = GetMotionPlanRequest()
        req.motion_plan_request.workspace_parameters.header.stamp = rospy.get_rostime()
        req.motion_plan_request.group_name = group_name
        req.motion_plan_request.num_planning_attempts = 1
        req.motion_plan_request.allowed_planning_time = planning_time
        req.motion_plan_request.planner_id = planner_config_name #using RRT planner by default

        req.motion_plan_request.start_state.joint_state.header.stamp = rospy.get_rostime()
        req.motion_plan_request.start_state.joint_state.name = joint_names
        req.motion_plan_request.start_state.joint_state.position = start_point

        req.motion_plan_request.goal_constraints.append(Constraints())
        req.motion_plan_request.goal_constraints[0].joint_constraints = []
        for i in xrange(len(joint_names)):
            temp_constraint = JointConstraint()
            temp_constraint.joint_name = joint_names[i]
            temp_constraint.position = goal_point[i]
            temp_constraint.tolerance_above = 0.05;
            temp_constraint.tolerance_below = 0.05;
            req.motion_plan_request.goal_constraints[0].joint_constraints.append(temp_constraint)

        #call the planner
        rospy.wait_for_service(self.planners[planner_number])
        rospy.loginfo("Plan Trajectory Wrapper: sent request to service %s" % planner_client.resolved_name)
        plan_time = np.inf
        try:
            plan_time = time.time()
            response = planner_client(req)
            plan_time = time.time() - plan_time
        except rospy.ServiceException, e:
            rospy.loginfo("%s Plan Trajectory Wrapper: service call failed: %s"
            % (rospy.get_name(), e))
            return plan_time, None
Beispiel #35
0
 def set_constraints(self):
     consts = Constraints()
     consts.joint_constraints.append(
         JointConstraint(joint_name='shoulder_pan_joint',
                         position=0.3,
                         tolerance_above=2.5,
                         tolerance_below=0.1,
                         weight=1))
     consts.joint_constraints.append(
         JointConstraint(joint_name='shoulder_lift_joint',
                         position=0,
                         tolerance_above=0.0,
                         tolerance_below=2.5,
                         weight=1))
     #consts.joint_constraints.append(
     #                  JointConstraint(joint_name='elbow_joint',
     #                  position=0, tolerance_above=pi,
     #                  tolerance_bel=pi, weight=0.5))
     consts.joint_constraints.append(
         JointConstraint(joint_name='wrist_1_joint',
                         position=-2.2,
                         tolerance_above=2.2,
                         tolerance_below=2.7,
                         weight=1))
     consts.joint_constraints.append(
         JointConstraint(joint_name='wrist_2_joint',
                         position=0.4,
                         tolerance_above=0.1,
                         tolerance_below=4.0,
                         weight=1))
     consts.joint_constraints.append(
         JointConstraint(joint_name='wrist_3_joint',
                         position=pi / 4.0,
                         tolerance_above=0.5,
                         tolerance_below=0.5,
                         weight=1))
     self.group.set_path_constraints(consts)
def createJointConstraints(pose_from_params, tolerances=0.1):
    """Create a JointConstraints message with its joint names and positions with some default tolerances
    @param pose_from_params dictionary with names of the joints and it's values
    @param tolerances the tolerance in radians for the joint positions, defaults to 0.1
    @return moveit_msgs/JointConstraints[] message with the joint names and positions"""
    joint_constraints = []
    for joint in pose_from_params:
        joint_constraint = JointConstraint()
        joint_constraint.joint_name = joint
        joint_constraint.position = pose_from_params[joint]
        joint_constraint.tolerance_above = tolerances
        joint_constraint.tolerance_below = tolerances
        joint_constraint.weight = 1.0
        joint_constraints.append(joint_constraint)
    return joint_constraints
def createJointConstraintsZero():
    joint_positions = [1.7567944054, 1.68571255762, -0.35731008621, 
                       1.06480870567, 1.36986326531, -0.662985424101,
                       -1.31376998814]
    joint_constraints = []
    for joint_num in range(1,8):
        joint_constraint = JointConstraint()
        joint_constraint.joint_name = 'arm_right_' + str(joint_num) + '_joint'
        joint_constraint.tolerance_above = 0.1
        joint_constraint.tolerance_below = 0.1
        joint_constraint.weight = 1.0
        
        joint_constraint.position = 0.0
        joint_constraints.append(joint_constraint)
        print str(joint_constraint)
    return joint_constraints
def createJointConstraints(joint_names, joint_positions, tolerances=0.1):
    """Create a JointConstraints message with its joint names and positions with some default tolerances
    @param joint_names names of the joints which will reference to values in param joint_positions
    @param joint_positions values for the joints specified in joint_names
    @param tolerances the tolerance in radians for the joint positions, defaults to 0.1
    @return moveit_msgs/JointConstraints[] message with the joint names and positions"""
    joint_constraints = []
    for joint, pos in zip(joint_names, joint_positions):
        joint_constraint = JointConstraint()
        joint_constraint.joint_name = joint
        joint_constraint.position = pos
        joint_constraint.tolerance_above = tolerances
        joint_constraint.tolerance_below = tolerances
        joint_constraint.weight = 1.0

        joint_constraints.append(joint_constraint)
    return joint_constraints
        msg = MotionPlanRequest()

        workspace_parameters = WorkspaceParameters()
        workspace_parameters.header.stamp = rospy.Time.now()
        workspace_parameters.header.frame_id = "/BASE"
        workspace_parameters.min_corner = Vector3(-1.0, -1.0, -1.0)
        workspace_parameters.max_corner = Vector3(1.0, 1.0, 1.0)

        start_state = RobotState()
#        start_state.joint_state.header.stamp = rospy.Time.now()
        start_state.joint_state.header.frame_id = "/BASE"
        start_state.joint_state.name =  ["j1", "j2", "j3", "j4", "j5", "flange"]
        start_state.joint_state.position = [-0.2569046038066598, -0.8442722962923348, 1.849082034218144, 0.26825374068443164, -0.04090683809444329, 5.745512865657193]
        start_state.joint_state.velocity =  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        jc2 = JointConstraint()
        jc2.joint_name = "j1"
        jc2.position = -1.37353344093
        jc2.tolerance_above = 0.0001
        jc2.tolerance_below = 0.0001
        jc2.weight = 1.0

        jc3 = JointConstraint()
        jc3.joint_name = "j2"
        jc3.position = -1.45013378543
        jc3.tolerance_above = 0.0001
        jc3.tolerance_below = 0.0001
        jc3.weight = 1.0

        jc4 = JointConstraint()
        jc4.joint_name = "j3"
def kinect_planner():
    global fresh_data
    global joint_target, pose_target, goal
    global joints_req, pose_req
    
    moveit_commander.roscpp_initialize(sys.argv)
    rospy.init_node('kinect_trajectory_planner', anonymous=True)
    rate = rospy.Rate(0.5)
    #rospy.sleep(3)
       
    # Instantiate a RobotCommander object. 
    robot = moveit_commander.RobotCommander()
    
    # Instantiate a PlanningSceneInterface object (interface to the world surrounding the robot).
    scene = moveit_commander.PlanningSceneInterface()
    print "Remember to disable firewall if it's not working"
    
    # Instantiate MoveGroupCommander objects for arms and Kinect2. 
    group = moveit_commander.MoveGroupCommander("Kinect2_Target")
    group_left_arm = moveit_commander.MoveGroupCommander("left_arm")
    group_right_arm = moveit_commander.MoveGroupCommander("right_arm")

    # We create this DisplayTrajectory publisher to publish
    # trajectories for RVIZ to visualize.
    display_trajectory_publisher = rospy.Publisher('planned_path',
                                        moveit_msgs.msg.DisplayTrajectory, queue_size=5)

    # Set the planner for Moveit
    group.set_planner_id("RRTConnectkConfigDefault")
    group.set_planning_time(8)
    group.set_pose_reference_frame('base_footprint')
    
    # Setting tolerance
    group.set_goal_tolerance(0.08)
    group.set_num_planning_attempts(10)
    
    # Suscribing to the desired pose topic
    target = rospy.Subscriber("desired_pose", PoseStamped, callback)
    target_joint = rospy.Subscriber("desired_joints", pose_w_joints, callback_joints)
    
    # Locating the arms and the Kinect2 sensor
    group_left_arm_values = group_left_arm.get_current_joint_values()
    group_right_arm_values = group_right_arm.get_current_joint_values()
    #group_kinect_values = group_kinect.get_current_joint_values()

    neck_init_joints = group.get_current_joint_values()
    neck_init_joints[0] = -1.346
    neck_init_joints[1] = -1.116
    neck_init_joints[2] = -2.121
    neck_init_joints[3] = 0.830
    neck_init_joints[4] = 1.490
    neck_init_joints[5] = 0.050
    neck_init_joints[6] = 0
    neck_init_joints[7] = 0
    neck_init_joints[8] = 0
    neck_init_joints[9] = 0

    # Creating a box to limit the arm position
    box_pose = PoseStamped()
    box_pose.pose.orientation.w = 1
    box_pose.pose.position.x =  0.6
    box_pose.pose.position.y =  0.03
    box_pose.pose.position.z =  1.5
    box_pose.header.frame_id = 'base_footprint'

    scene.add_box('box1', box_pose, (0.4, 0.4, 0.1))
    rospy.sleep(2)

    # Defining position constraints for the trajectory of the kinect
    neck_const = Constraints()
    neck_const.name = 'neck_constraints'
    target_const = JointConstraint()
    target_const.joint_name = "neck_joint_end"
    target_const.position = 0.95
    target_const.tolerance_above = 0.45
    target_const.tolerance_below = 0.05
    target_const.weight = 0.9 # Importance of this constraint
    neck_const.joint_constraints.append(target_const)

    # Talking to the robot
    #client = actionlib.SimpleActionClient('/Kinect2_Target_controller/follow_joint_trajectory', FollowJointTrajectoryAction)
    client = actionlib.SimpleActionClient('/neck/follow_joint_trajectory', FollowJointTrajectoryAction)
    print "====== Waiting for server..."
    client.wait_for_server()
    print "====== Connected to server"
   
     
    while not rospy.is_shutdown(): 
        print('.')
        skip_iter = False

        if fresh_data == True: #If a new pose is received, plan.
        
            # Update arms position
            group_left_arm_values = group_left_arm.get_current_joint_values()
            group_right_arm_values = group_right_arm.get_current_joint_values()
            
            # Set the target pose (or joint values) and generate a plan
            if pose_req:
                group.set_pose_target(pose_target)
            if joints_req:
                print('about to set joint target')
                print(joint_target)
                try:
                    if len(joint_target) == 6:
                      #Setting also values for the four virtual joints (one prismatic, and three rotational)
                      new_joint_target = joint_target + [0.1]*4
                    else:
                      new_joint_target = joint_target

                    print('setting: '),
                    print new_joint_target
                    group.set_joint_value_target(new_joint_target)
                except:
                    print('cannot set joint target')
                    skip_iter = True
 

            print "=========== Calculating trajectory... \n"

            # Generate several plans and compare them to get the shorter one
            plan_opt = dict()
            differ = dict()

            if not skip_iter:

                try:
                    num = 1
                    rep = 0

                    # Generate several plans and compare them to get the shortest one
                    #for num in range(1,8):
                    while num < 7:
                        num += 1
                        plan_temp = group.plan()
                        move(plan_temp)
                        plan_opt[num] = goal.trajectory
                        diff=0
                        for point in goal.trajectory.points:
                            # calculate the distance between initial pose and planned one
                            for i in range(0,6):
                                diff = abs(neck_init_joints[i] - point.positions[i])+abs(diff)
                            differ[num] = diff
                        # If the current plan is good, take it
                        if diff < 110:
                           break
                        # If plan is too bad, don't consider it
                        if diff > 400:
                            num = num - 1
                            print "Plan is too long. Replanning."
                            rep = rep + 1
                            if rep > 4:
                                num = num +1

                    # If no plan was found...
                    if differ == {}:
                        print "---- Fail: No motion plan found. No execution attempted. Probably robot joints are out of range."
                        break

                    else:
                        # Select the shortest plan
                        min_plan = min(differ.itervalues())
                        select = [k for k, value in differ.iteritems() if value == min_plan]
                        goal.trajectory = plan_opt[select[0]]
                        #print " Plan difference:======= ", differ
                        #print " Selected plan:========= ", select[0]

                        # Remove the last 4 names and data from each point (dummy joints) before sending the goal
                        goal.trajectory.joint_names = goal.trajectory.joint_names[:6]
                        for point in goal.trajectory.points:
                            point.positions = point.positions[:6]
                            point.velocities = point.velocities[:6]
                            point.accelerations = point.accelerations[:6]

                        print "Sending goal"
                        client.send_goal(goal)
                        print "Waiting for result"
                        client.wait_for_result()

                        # Change the position of the virtual joint to avoid collision
                        neck_joints = group.get_current_joint_values()
                        print('neck joints:')
                        print neck_joints
                        #neck_joints[6] = 0.7
                        #group.set_joint_value_target(neck_joints)
                        #group.go(wait=True)


                except (KeyboardInterrupt, SystemExit):
                    client.cancel_goal()
                    raise
            
            rate.sleep()
    
        fresh_data = False
    
        rate.sleep()
def joint_position_callback(joints):

    global plan_only
    fixed_frame = rospy.get_param("/fixed_frame")

    client = actionlib.SimpleActionClient('move_group', MoveGroupAction)
    client.wait_for_server()
    move_group_goal = MoveGroupGoal()

    try:

        msg = MotionPlanRequest()
        workspace_parameters = WorkspaceParameters()
        workspace_parameters.header.stamp = rospy.Time.now()
        workspace_parameters.header.frame_id = fixed_frame
        workspace_parameters.min_corner = Vector3(-1.0, -1.0, -1.0)
        workspace_parameters.max_corner = Vector3(1.0, 1.0, 1.0)

        start_state = RobotState()
#        start_state.joint_state.header.stamp = rospy.Time.now()
        start_state.joint_state.header.frame_id = fixed_frame
        start_state.joint_state.name =  []
        start_state.joint_state.position = []

        cons = Constraints()
        cons.name = ""
        i = 0
        for dim in joints.start_joint.layout.dim:
            start_state.joint_state.name.append(dim.label)
            start_state.joint_state.position.append(joints.start_joint.data[i])

            jc = JointConstraint()
            jc.joint_name = dim.label
            jc.position = joints.goal_joint.data[i]
            jc.tolerance_above = 0.0001
            jc.tolerance_below = 0.0001
            jc.weight = 1.0
            i = i + 1
            cons.joint_constraints.append(jc)


        msg.workspace_parameters = workspace_parameters
        msg.start_state = start_state
        msg.goal_constraints.append(cons)

        msg.num_planning_attempts = 1
        msg.allowed_planning_time = 5.0

        msg.group_name = joints.group_name
        move_group_goal.request = msg


        if joints.plan_only:
            plan_only = True
            move_group_goal.planning_options.plan_only = True
        else:
            plan_only = False

        client.send_goal(move_group_goal)
        client.wait_for_result(rospy.Duration.from_sec(5.0))


    except rospy.ROSInterruptException, e:
        print "failed: %s"%e
Beispiel #42
0
def main():
    #Initialize the node
    rospy.init_node('moveit_client')
    
    # Create the SimpleActionClient, passing the type of the action
    # (MoveGroupAction) to the constructor.
    client = actionlib.SimpleActionClient('move_group', MoveGroupAction)

    # Wait until the action server has started up and started
    # listening for goals.
    client.wait_for_server()

    # Creates a goal to send to the action server.
    goal = MoveGroupGoal()
    
    #----------------Construct the goal message (start)----------------
    joint_names = ['head_pan', 'left_s0', 'left_s1', 'left_e0', 'left_e1', 'left_w0', 'left_w1', 'left_w2', 'right_s0', 'right_s1', 'right_e0', 'right_e1', 'right_w0', 'right_w1', 'right_w2']
    
    #Set parameters for the planner    
    goal.request.group_name = 'both_arms'
    goal.request.num_planning_attempts = 1
    goal.request.allowed_planning_time = 5.0
    
    #Define the workspace in which the planner will search for solutions
    goal.request.workspace_parameters.min_corner.x = -1
    goal.request.workspace_parameters.min_corner.y = -1
    goal.request.workspace_parameters.min_corner.z = -1
    goal.request.workspace_parameters.max_corner.x = 1
    goal.request.workspace_parameters.max_corner.y = 1
    goal.request.workspace_parameters.max_corner.z = 1
    
    goal.request.start_state.joint_state.header.frame_id = "base"
    
    #Set the start state for the trajectory
    goal.request.start_state.joint_state.name = joint_names
    goal.request.start_state.joint_state.position = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    goal.request.start_state.joint_state.velocity = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    
    print 'Enter start state:'
    try:
      for i in range(len(joint_names)):
        val = float(raw_input(joint_names[i]+':'))
        goal.request.start_state.joint_state.position[i] = val
    except:
      print 'Using defaults for remaining joints'
      print goal.request.start_state.joint_state.position

    #Tell MoveIt whether to execute the trajectory after planning it
    goal.planning_options.plan_only = True
    
    #Set the goal position of the robot
    #Note that the goal is specified with a collection of individual
    #joint constraints, rather than a vector of joint angles
    arm_joint_names = joint_names[1:]
    target_joint_angles = [0.5, -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

    print 'Enter goal state:'
    try:
      for i in range(len(target_joint_angles)):
        val = float(raw_input(joint_names[i]+':'))
        target_joint_angles[i] = val
    except:
      print 'Using defaults for remaining joints'
      print target_joint_angles

    tolerance = 0.0001
    consts = []
    for i in range(len(arm_joint_names)):
        const = JointConstraint()
        const.joint_name = arm_joint_names[i]
        const.position = target_joint_angles[i]
        const.tolerance_above = tolerance
        const.tolerance_below = tolerance
        const.weight = 1.0
        consts.append(const)
        
    goal.request.goal_constraints.append(Constraints(name='', joint_constraints=consts))
    #---------------Construct the goal message (end)-----------------

    # Send the goal to the action server.
    client.send_goal(goal)

    # Wait for the server to finish performing the action.
    client.wait_for_result()

    # Print out the result of executing the action
    print(client.get_result())
Beispiel #43
0
def main():
    # Initialize the node
    rospy.init_node("moveit_client")

    # Create the SimpleActionClient, passing the type of the action
    # (MoveGroupAction) to the constructor.
    client = actionlib.SimpleActionClient("move_group", MoveGroupAction)

    # Wait until the action server has started up and started
    # listening for goals.
    client.wait_for_server()

    # Creates a goal to send to the action server.
    goal = MoveGroupGoal()

    # ----------------Construct the goal message (start)----------------
    joint_names = [
        "head_pan",
        "left_s0",
        "left_s1",
        "left_e0",
        "left_e1",
        "left_w0",
        "left_w1",
        "left_w2",
        "right_s0",
        "right_s1",
        "right_e0",
        "right_e1",
        "right_w0",
        "right_w1",
        "right_w2",
    ]

    # Set parameters for the planner
    goal.request.group_name = "both_arms"
    goal.request.num_planning_attempts = 1
    goal.request.allowed_planning_time = 5.0

    # Define the workspace in which the planner will search for solutions
    goal.request.workspace_parameters.min_corner.x = -1
    goal.request.workspace_parameters.min_corner.y = -1
    goal.request.workspace_parameters.min_corner.z = -1
    goal.request.workspace_parameters.max_corner.x = 1
    goal.request.workspace_parameters.max_corner.y = 1
    goal.request.workspace_parameters.max_corner.z = 1

    goal.request.start_state.joint_state.header.frame_id = "base"

    # Set the start state for the trajectory
    goal.request.start_state.joint_state.name = joint_names
    goal.request.start_state.joint_state.position = [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ]
    goal.request.start_state.joint_state.velocity = [
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
        0.0,
    ]

    # Tell MoveIt whether to execute the trajectory after planning it
    goal.planning_options.plan_only = True

    # Set the goal position of the robot
    # Note that the goal is specified with a collection of individual
    # joint constraints, rather than a vector of joint angles
    arm_joint_names = joint_names[1:]

    print("Joint angles...? Are coming one at a time.  Give them to me in radians")

    target_joint_angles = []
    for joint in joint_names:
        str = raw_input(joint + "\n-->")
        val = float(str)
        target_joint_angles.append(val)

    print("I think that you want me to go to...")
    print(target_joint_angles)

    raw_input("Press any key to continue")

    # target_joint_angles = [0.5, -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    tolerance = 0.0001
    consts = []
    for i in range(len(arm_joint_names)):
        const = JointConstraint()
        const.joint_name = arm_joint_names[i]
        const.position = target_joint_angles[i]
        const.tolerance_above = tolerance
        const.tolerance_below = tolerance
        const.weight = 1.0
        consts.append(const)

    goal.request.goal_constraints.append(Constraints(name="", joint_constraints=consts))
    # ---------------Construct the goal message (end)-----------------

    # Send the goal to the action server.
    client.send_goal(goal)

    # Wait for the server to finish performing the action.
    client.wait_for_result()

    # Print out the result of executing the action
    print(client.get_result())
    correct_js = copy.deepcopy(current_joint_states)


    result = fk.getFK('arm_right_7_link', current_joint_states.name, correct_js.position, 'base_link')
    rospy.loginfo("Result of current robot pose FK is: " + str(result))

    rs = RobotState()
    rs.joint_state = correct_js
    drs = DisplayRobotState()
    drs.state = rs
    rs_pub.publish(drs)
    rospy.loginfo("Published current robot state")
    rospy.sleep(2.0)

    c = Constraints()
    jc = JointConstraint()
    jc.joint_name = 'arm_right_1_link'
    jc.position = 0.0
    jc.tolerance_above = 0.00001
    jc.tolerance_below = 0.00001
    jc.weight = 1.0
    c.joint_constraints.append(jc)
    
    rospy.loginfo("Result without constraints:")
    resultik = ik.getIK("right_arm", "right_arm_7_link", result.pose_stamped[0], False, 0, rs)
    rospy.loginfo(str(resultik))
    
    rs = RobotState()
    rs.joint_state = resultik.solution.joint_state
    drs = DisplayRobotState()
    drs.state = rs