def set_pose_constraints(self, tol_joint1, tol_joint2, tol_joint3): angle_constraints = Constraints() joint_constraint = JointConstraint() angle_constraints.name = "angle" joint_constraint.position = self.joint1_con joint_constraint.tolerance_above = tol_joint1 joint_constraint.tolerance_below = tol_joint1 joint_constraint.weight = 0.1 joint_constraint.joint_name = "arm_shoulder_pan_joint" angle_constraints.joint_constraints.append(joint_constraint) joint_constraint2 = JointConstraint() joint_constraint2.position = self.joint2_con joint_constraint2.tolerance_above = tol_joint2 joint_constraint2.tolerance_below = tol_joint2 joint_constraint2.weight = 0.2 joint_constraint2.joint_name = "arm_wrist_2_joint" angle_constraints.joint_constraints.append(joint_constraint2) joint_constraint3 = JointConstraint() joint_constraint3.position = self.joint3_con joint_constraint3.tolerance_above = tol_joint3 joint_constraint3.tolerance_below = tol_joint3 joint_constraint3.weight = 0.3 joint_constraint3.joint_name = "arm_wrist_1_joint" angle_constraints.joint_constraints.append(joint_constraint3) group.set_path_constraints(angle_constraints)
def limit_base_joint_constraint(): ur5_constraints = Constraints() shoulder_pan_joint_constraint = JointConstraint() shoulder_lift_joint_constraint = JointConstraint() wrist_1_joint_constraint = JointConstraint() shoulder_pan_joint_constraint.joint_name = "shoulder_pan_joint" shoulder_pan_joint_constraint.position = 0 shoulder_pan_joint_constraint.tolerance_above = 3.14 shoulder_pan_joint_constraint.tolerance_below = 3.14 shoulder_pan_joint_constraint.weight = 1 shoulder_lift_joint_constraint.joint_name = "shoulder_lift_joint" shoulder_lift_joint_constraint.position = 0 shoulder_lift_joint_constraint.tolerance_above = 0 shoulder_lift_joint_constraint.tolerance_below = 3.14 shoulder_lift_joint_constraint.weight = 1 wrist_1_joint_constraint.joint_name = "wrist_1_joint" wrist_1_joint_constraint.position = 0 wrist_1_joint_constraint.tolerance_above = 3.14 wrist_1_joint_constraint.tolerance_below = 3.14 wrist_1_joint_constraint.weight = 1 ur5_constraints.joint_constraints.append(shoulder_pan_joint_constraint) ur5_constraints.joint_constraints.append(shoulder_lift_joint_constraint) ur5_constraints.joint_constraints.append(wrist_1_joint_constraint) return ur5_constraints
def main(argv): client = actionlib.SimpleActionClient( '/plan_and_execute_pose_w_joint_constraints', PlanExecutePoseConstraintsAction) client.wait_for_server() goal = PlanExecutePoseConstraintsGoal() try: goal.target_pose.header.frame_id = argv[0] goal.target_pose.pose.position.x = float(argv[1]) goal.target_pose.pose.position.y = float(argv[2]) goal.target_pose.pose.position.z = float(argv[3]) roll = float(argv[4]) * math.pi / 180.0 pitch = float(argv[5]) * math.pi / 180.0 yaw = float(argv[6]) * math.pi / 180.0 quat = quaternion_from_euler(roll, pitch, yaw) print quat goal.target_pose.pose.orientation.x = quat[0] goal.target_pose.pose.orientation.y = quat[1] goal.target_pose.pose.orientation.z = quat[2] goal.target_pose.pose.orientation.w = quat[3] joint_constraint_arm1_joint = JointConstraint() joint_constraint_arm1_joint.joint_name = "arm1_joint" joint_constraint_arm1_joint.position = float(0.0) joint_constraint_arm1_joint.tolerance_above = float( 30) * math.pi / 180.0 joint_constraint_arm1_joint.tolerance_below = float( 30) * math.pi / 180.0 joint_constraint_arm1_joint.weight = 1.0 joint_constraint_arm6_joint = JointConstraint() joint_constraint_arm6_joint.joint_name = "arm6_joint" joint_constraint_arm6_joint.position = float(0.0) joint_constraint_arm6_joint.tolerance_above = float( 10) * math.pi / 180.0 joint_constraint_arm6_joint.tolerance_below = float( 10) * math.pi / 180.0 joint_constraint_arm6_joint.weight = 1.0 goal.joint_constraints.append(joint_constraint_arm1_joint) goal.joint_constraints.append(joint_constraint_arm6_joint) except ValueError: quit() client.send_goal(goal) client.wait_for_result() print client.get_result()
def add_robot_constraints(): constraint = Constraints() constraint.name = "camera constraint" roll_constraint = OrientationConstraint() # 'base_link' is equal to the world link roll_constraint.header.frame_id = 'world' # The link that must be oriented upwards roll_constraint.link_name = "camera" roll_constraint.orientation = Quaternion(*tf.transformations.quaternion_from_euler(0,np.pi/3,0)) # Allow rotation of 45 degrees around the x and y axis roll_constraint.absolute_x_axis_tolerance = np.pi #Allow max rotation of x degrees roll_constraint.absolute_y_axis_tolerance = np.pi roll_constraint.absolute_z_axis_tolerance = np.pi/2 # The roll constraint is the only constraint roll_constraint.weight = 1 #constraint.orientation_constraints = [roll_constraint] joint_1_constraint = JointConstraint() joint_1_constraint.joint_name = "joint_1" joint_1_constraint.position = 0 joint_1_constraint.tolerance_above = np.pi/2 joint_1_constraint.tolerance_below = np.pi/2 joint_1_constraint.weight = 1 joint_4_constraint = JointConstraint() joint_4_constraint.joint_name = "joint_4" joint_4_constraint.position = 0 joint_4_constraint.tolerance_above = np.pi/2 joint_4_constraint.tolerance_below = np.pi/2 joint_4_constraint.weight = 1 joint_5_constraint = JointConstraint() joint_5_constraint.joint_name = "joint_5" joint_5_constraint.position = np.pi/2 joint_5_constraint.tolerance_above = np.pi/2 joint_5_constraint.tolerance_below = np.pi/2 joint_5_constraint.weight = 1 joint_6_constraint = JointConstraint() joint_6_constraint.joint_name = "joint_6" joint_6_constraint.position = np.pi-0.79 joint_6_constraint.tolerance_above = np.pi joint_6_constraint.tolerance_below = np.pi joint_6_constraint.weight = 1 constraint.joint_constraints = [joint_1_constraint, joint_6_constraint] return constraint
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"
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 _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
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'
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 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()
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
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)
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
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
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()
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)
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)
def build_joint_constraints(joint_state): joint_constraints = [] for i, joint_angle in enumerate(joint_state): jc = JointConstraint() jc.joint_name = self.JOINTS[i] jc.position = joint_angle jc.tolerance_above = np.radians( self.MAX_LINEAR_JOINT_FLUCTUATION) jc.tolerance_below = np.radians( self.MAX_LINEAR_JOINT_FLUCTUATION) jc.weight = 1.0 joint_constraints.append(jc) return joint_constraints
def setJointConstraints(goal_config, group_handle): constraints = []; names = group_handle.get_joints(); for num in range(0,len(names)): jnt_constraint = JointConstraint(); jnt_constraint.joint_name = names[num]; jnt_constraint.position = goal_config[num]; jnt_constraint.tolerance_above = 0.0001; jnt_constraint.tolerance_below = 0.0001; jnt_constraint.weight = 1.0; constraints.append(jnt_constraint); return constraints;
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
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
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 init_path_constraints(joint_no, upper_limit, lower_limit, weight): joint_constraint = JointConstraint() UpperArmPath.path_constraints.name = UpperArmPath.__GROUP_NAME upper_limit = upper_limit / 180.0 * math.pi lower_limit = lower_limit / 180.0 * math.pi joint_constraint.position = (upper_limit + lower_limit) / 2.0 joint_constraint.tolerance_above = (upper_limit - lower_limit) / 2.0 joint_constraint.tolerance_below = (upper_limit - lower_limit) / 2.0 joint_constraint.weight = weight joint_constraint.joint_name = "upper_joint%d" % (joint_no) UpperArmPath.path_constraints.joint_constraints.append( joint_constraint)
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 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 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
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_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
def plan_execute_named_pose_cb(self, goal): feedback = PlanExecuteNamedPoseFeedback() result = PlanExecuteNamedPoseResult() result.result = True self.group.clear_pose_targets() #self.group.set_start_state_to_current_state() #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) self.group.set_path_constraints(self.contraints) try: self.group.set_named_target(goal.target_name) except MoveItCommanderException: result.result = False self.action_plan_execute_named_pose.set_succeeded(result) return rospy.loginfo('Planning named [%s] pose...' % goal.target_name) plan1 = self.group.plan() # print("plan1 type : ", type(plan1)) # print("plan : ", plan1) 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('Planning named pose succeeded.') self.action_plan_execute_named_pose.set_succeeded(result)
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()
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
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" jc4.position = 2.18173030842
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
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())
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()
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 rs_pub.publish(drs)
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())