class ObjectServer(object): def __init__(self): self.scene = PlanningSceneInterface() self.robot = RobotCommander() self.p = PoseStamped() self.scene_srv = rospy.ServiceProxy('/get_planning_scene', GetPlanningScene) rospy.loginfo("Connecting to clear octomap service...") self.clear_octomap_srv = rospy.ServiceProxy('/clear_octomap', Empty) self.clear_octomap_srv.wait_for_service() rospy.loginfo("Connected!") def wait_for_planning_scene_object(self, object_name='part'): rospy.loginfo("Waiting for object '" + object_name + "'' to appear in planning scene...") gps_req = GetPlanningSceneRequest() gps_req.components.components = gps_req.components.WORLD_OBJECT_NAMES part_in_scene = False while not rospy.is_shutdown() and not part_in_scene: # This call takes a while when rgbd sensor is set gps_resp = self.scene_srv.call(gps_req) # check if 'part' is in the answer for collision_obj in gps_resp.scene.world.collision_objects: if collision_obj.id == object_name: part_in_scene = True break else: rospy.sleep(1.0) rospy.loginfo("'" + object_name + "'' is in scene!") def make_object(self,object_name,x,y,z,sx,sy,sz): rospy.loginfo("Removing any previous 'part' object") self.scene.remove_attached_object("arm_tool_link") self.scene.remove_world_object(object_name) rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) rospy.sleep(2.0) # Removing is fast rospy.loginfo("Adding new 'part' object") rospy.loginfo("Making "+object_name+"...") self.p.header.frame_id = self.robot.get_planning_frame() self.p.pose.position.x = x self.p.pose.position.y = y self.p.pose.position.z = z self.scene.add_box(object_name, self.p, (sx,sy,sz)) self.wait_for_planning_scene_object(object_name)
def main(): rospy.init_node('moveit_py_place', anonymous=True) #right_arm.set_planner_id("KPIECEkConfigDefault"); scene = PlanningSceneInterface() robot = RobotCommander() #group = MoveGroupCommander("head") right_arm = MoveGroupCommander("right_arm") #right_arm.set_planner_id("KPIECEkConfigDefault"); rospy.logwarn("cleaning world") GRIPPER_FRAME = 'gripper_bracket_f2' #scene.remove_world_object("table") scene.remove_world_object("part") scene.remove_attached_object(GRIPPER_FRAME, "part") p = PoseStamped() p.header.frame_id = robot.get_planning_frame() p.pose.position.x = 0.67 p.pose.position.y = -0. p.pose.position.z = 0.75 scene.add_box("part", p, (0.07, 0.01, 0.2)) # move to a random target #group.set_named_target("ahead") #group.go() #rospy.sleep(1) result = False n_attempts = 0 # repeat until will succeed while result == False: result = robot.right_arm.pick("part") n_attempts += 1 print "Attempts pickup: ", n_attempts rospy.sleep(0.2) #robot.right_arm.pick("part") #right_arm.go() rospy.sleep(5)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name table_id = 'table' box1_id = 'box1' box2_id = 'box2' target_id = 'target' tool_id = 'tool' # Remove leftover objects from a previous run scene.remove_world_object(table_id) scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(target_id) scene.remove_world_object(tool_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self, pickPos, placePos): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) # rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the right arm pick_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the momitive group for the right gripper pick_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = pick_arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) pick_arm.set_goal_position_tolerance(0.05) pick_arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution pick_arm.allow_replanning(True) # Set the right arm reference frame pick_arm.set_pose_reference_frame(REFERENCE_FRAME) #pick_arm.set_planner_id("RRTConnectkConfigDefault") #pick_arm.set_planner_id("RRTstarkConfigDefault") pick_arm.set_planner_id("RRTstarkConfigDefault") # Allow 5 seconds per planning attempt pick_arm.set_planning_time(3) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name base_table_id = 'base_table' target_id = 'target' limit_table_id = 'limit_table' #tool_id = 'tool' # Remove leftover objects from a previous run scene.remove_world_object(base_table_id) #scene.remove_world_object(table_id) #scene.remove_world_object(box1_id) #scene.remove_world_object(box2_id) scene.remove_world_object(target_id) #scene.remove_world_object(tool_id) scene.remove_world_object(limit_table_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Open the gripper to the neutral position # pick_gripper.set_joint_value_target(GRIPPER_NEUTRAL) # pick_gripper.go() rospy.sleep(1) # Set the height of the table off the ground # table_ground = 0.6 table_ground = 0.0 # Set the dimensions of the scene objects [l, w, h] base_table_size = [2, 2, 0.04] #table_size = [0.2, 0.7, 0.01] #box1_size = [0.1, 0.05, 0.05] #box2_size = [0.05, 0.05, 0.15] # Set the target size [l, w, h] target_size = [0.055, 0.055, 0.12] target_radius = 0.03305 target_height = 0.12310 limit_table_size = [0.6, 1.8, 0.04] # Add a base table to the scene base_table_pose = PoseStamped() base_table_pose.header.frame_id = REFERENCE_FRAME base_table_pose.pose.position.x = 0.0 base_table_pose.pose.position.y = 0.0 base_table_pose.pose.position.z = -0.3 base_table_pose.pose.orientation.w = 1.0 scene.add_box(base_table_id, base_table_pose, base_table_size) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "resting" pose stored in the SRDF file pick_arm.set_named_target(ARM_HOME_POSE) pick_arm.go() rospy.sleep(1) # Add a table top and two boxes to the scene #table_pose = PoseStamped() #table_pose.header.frame_id = REFERENCE_FRAME #table_pose.pose.position.x = 0.5 #table_pose.pose.position.y = -0.4 #table_pose.pose.position.z = table_ground + table_size[2] / 2.0 #table_pose.pose.orientation.w = 1.0 #scene.add_box(table_id, table_pose, table_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = pickPos.pose.position.x target_pose.pose.position.y = pickPos.pose.position.y target_pose.pose.position.z = pickPos.pose.position.z target_pose.pose.orientation.w = pickPos.pose.orientation.w # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) #scene.add_cylinder(target_id,target_pose,target_height,target_radius) #Add the limit_table object to the scene limit_table_pose = PoseStamped() limit_table_pose.header.frame_id = REFERENCE_FRAME limit_table_pose.pose.position.x = 0.58 limit_table_pose.pose.position.y = -0.4 limit_table_pose.pose.position.z = 0.18 limit_table_pose.pose.orientation.w = 1.0 #scene.add_box(limit_table_id, limit_table_pose, limit_table_size) self.setColor(limit_table_id, 0.6, 0.2, 0.2, 1.0) # Make the table red and the boxes orange #self.setColor(table_id, 0.8, 0, 0, 1.0) # self.setColor(box1_id, 0.8, 0.4, 0, 1.0) # self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object #pick_arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up #指定拾取后的放置目标姿态 place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = placePos.pose.position.x place_pose.pose.position.y = placePos.pose.position.y place_pose.pose.position.z = placePos.pose.position.z place_pose.pose.orientation.w = placePos.pose.orientation.w place_pose.pose.orientation.x = placePos.pose.orientation.x place_pose.pose.orientation.y = placePos.pose.orientation.y place_pose.pose.orientation.z = placePos.pose.orientation.z #设置机器人运行最大速度位百分之~ pick_arm.set_max_velocity_scaling_factor(0.5) # Initialize the grasp pose to the target pose #初始化抓取目标点位 grasp_pose = target_pose # Shift the grasp pose by half the width of the target to center it # this way is just used by PR2 robot #grasp_pose.pose.position.y -= target_size[1] / 2.0 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id]) # Publish the grasp poses so they can be viewed in RV for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts #重复直到成功或者超出尝试的次数 #while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: while result != 1 and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) #moveit中的pick接口,target_id为moveit添加场景的id,此处为目标物体,grasps为可尝试抓取的点位序列 result = pick_arm.pick(target_id, grasps) #打印信息 rospy.logerr("pick_arm.pick: " + str(result)) rospy.sleep(0.2) # If the pick was successful, attempt the place operation #如果抓取成功,尝试放置操作 result_g = None n_attempts = 2 #if result == MoveItErrorCodes.SUCCESS: while result_g != True and n_attempts < max_pick_attempts: #and result == 1: # Generate valid place poses #places = self.make_places(place_pose) n_attempts += 1 print("-------------------") print(place_pose) #更新当前的机械臂状态 pick_arm.set_start_state_to_current_state() #设置moveit运动的目标点位 pick_arm.set_pose_target(place_pose) # Repeat until we succeed or run out of attempts #while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: # n_attempts += 1 # rospy.loginfo("Place attempt: " + str(n_attempts)) # for place in places: # result = pick_arm.place(target_id, place) # if result == MoveItErrorCodes.SUCCESS: # break # rospy.sleep(0.2) #moveit的运动接口,wait=True表示等到执行完成才返回 result_g = pick_arm.go(wait=True) rospy.logerr("pick_arm.go: " + str(result_g)) #打开夹爪 open_client(500) rospy.sleep(0.2) #if result == "False" # rospy.logerr("Place operation failed after " + str(n_attempts) + " attempts.") #else: # rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") # Return the arm to the "home" pose stored in the SRDF file #将机械臂返回到SRDF中的“home”姿态 #scene.remove_world_object(target_id) #scene.remove_attached_object(GRIPPER_FRAME, target_id) #scene.remove_world_object(target_id) rospy.sleep(1) open_client(500) pick_arm.set_named_target(ARM_HOME_POSE) pick_arm.go() # Open the gripper to the neutral position # pick_gripper.set_joint_value_target(GRIPPER_NEUTRAL) # pick_gripper.go() rospy.sleep(1) rospy.logerr("pick_server over ")
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') #Initialize robot robot = moveit_commander.RobotCommander() # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # Create a publisher for displaying object frames self.object_frames_pub = rospy.Publisher('object_frames', PoseStamped, queue_size=10) ## Create a publisher for visualizing direction ### self.p_pub = rospy.Publisher('target', PoseStamped, latch=True, queue_size = 10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the MoveIt! commander for the arm right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the MoveIt! commander for the gripper right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Allow 5 seconds per planning attempt right_arm.set_planning_time(5) # Prepare Gripper and open it self.ac = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',pr2c.Pr2GripperCommandAction) self.ac.wait_for_server() g_open = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.088, 100)) g_close = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.0, 1)) self.ac.send_goal(g_open) # Give the scene a chance to catch up rospy.sleep(2) # Prepare Gazebo Subscriber self.pwh = None self.pwh_copy = None self.idx_targ = None self.gazebo_subscriber = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) rospy.sleep(2) # PREPARE THE SCENE while self.pwh is None: rospy.sleep(0.05) target_id = 'target' self.taid = self.pwh.name.index('wood_cube_5cm') table_id = 'table' self.tid = self.pwh.name.index('table') #obstacle1_id = 'obstacle1' #self.o1id = self.pwh.name.index('wood_block_10_2_1cm') # Remove leftover objects from a previous run scene.remove_world_object(target_id) scene.remove_world_object(table_id) #scene.remove_world_object(obstacle1_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Set the target size [l, w, h] target_size = [0.05, 0.05, 0.05] table_size = [1.5, 0.8, 0.03] #obstacle1_size = [0.1, 0.025, 0.01] ## Set the target pose on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose = self.pwh.pose[self.taid] target_pose.pose.position.z += 0.025 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose = self.pwh.pose[self.tid] table_pose.pose.position.z += 1 scene.add_box(table_id, table_pose, table_size) #obstacle1_pose = PoseStamped() #obstacle1_pose.header.frame_id = REFERENCE_FRAME #obstacle1_pose.pose = self.pwh.pose[self.o1id] ## Add the target object to the scene #scene.add_box(obstacle1_id, obstacle1_pose, obstacle1_size) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.50 place_pose.pose.position.y = -0.30 place_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) ### Make the target purple ### self.setColor(target_id, 0.6, 0, 1, 1.0) # Send the colors to the planning scene self.sendColors() #print target_pose self.object_frames_pub.publish(target_pose) rospy.sleep(2) print "==================== Generating Transformations ===========================" M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 1.57, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y M2[2,3] = 0.25 # about z T = np.dot(M1, M2) pre_grasping = deepcopy(target_pose) pre_grasping.pose.position.x = T[0,3] pre_grasping.pose.position.y = T[1,3] pre_grasping.pose.position.z = T[2,3] quat = transformations.quaternion_from_matrix(T) pre_grasping.pose.orientation.x = quat[0] pre_grasping.pose.orientation.y = quat[1] pre_grasping.pose.orientation.z = quat[2] pre_grasping.pose.orientation.w = quat[3] pre_grasping.header.frame_id = 'gazebo_world' # # Initialize the grasp object # g = Grasp() # grasps = [] # # Set the first grasp pose to the input pose # g.grasp_pose = pre_grasping # g.allowed_touch_objects = [target_id] # grasps.append(deepcopy(g)) # right_arm.pick(target_id, grasps) #Change the frame_id for the planning to take place! #target_pose.header.frame_id = 'gazebo_world' self.p_pub.publish(pre_grasping) right_arm.set_pose_target(pre_grasping, GRIPPER_FRAME) plan = right_arm.plan() rospy.sleep(2) right_arm.go(wait=True) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=5) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=5) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the right arm right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the move group for the right gripper right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = right_arm.get_end_effector_link() print(end_effector_link) # Allow some leeway in position (meters) and orientation (radians) right_arm.set_goal_position_tolerance(0.1) right_arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution right_arm.allow_replanning(True) # Set the right arm reference frame right_arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt right_arm.set_planning_time(5) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 2 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # clean the scene scene.remove_world_object("table") scene.remove_world_object("part") # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, "part") # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "grasp" pose stored in the SRDF file right_arm.set_named_target('default') right_arm.go() # Open the gripper to the neutral position right_gripper.set_joint_value_target(GRIPPER_OPEN) right_gripper.go() rospy.sleep(1) place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.240 place_pose.pose.position.y = 0.01 place_pose.pose.position.z = 0.3 scene.add_box("part", place_pose, (0.07, 0.01, 0.2)) # Specify a pose to place the target after being picked up target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME # start the gripper in a neutral pose part way to the target target_pose.pose.position.x = 0.0733923763037 target_pose.pose.position.y = 0.0129100652412 target_pose.pose.position.z = 0.3097191751 target_pose.pose.orientation.x = -0.524236500263 target_pose.pose.orientation.y = 0.440069645643 target_pose.pose.orientation.z = -0.468739062548 target_pose.pose.orientation.w = 0.558389186859 # Initialize the grasp pose to the target pose grasp_pose = target_pose print("going to start pose") right_arm.set_pose_target(target_pose) right_arm.go() rospy.sleep(2) # Shift the grasp pose by half the width of the target to center it #grasp_pose.pose.position.y -= target_size[1] / 2.0 #grasp_pose.pose.position.x = 0.12792118579 #grasp_pose.pose.position.y = -0.285290879999 #grasp_pose.pose.position.z = 0.120301181892 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, 'part') # Publish the grasp poses so they can be viewed in RViz print "Publishing grasps" for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) result = right_arm.pick('part', grasps) rospy.sleep(0.2) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: result = None n_attempts = 0 # Generate valid place poses places = self.make_places(place_pose) # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) for place in places: result = right_arm.place('part', place) if result == MoveItErrorCodes.SUCCESS: break rospy.sleep(0.2) if result != MoveItErrorCodes.SUCCESS: rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") else: # Return the arm to the "resting" pose stored in the SRDF file right_arm.set_named_target('right_arm_rest') right_arm.go() # Open the gripper to the open position right_gripper.set_joint_value_target(GRIPPER_OPEN) right_gripper.go() else: rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Construct the initial scene object scene = PlanningSceneInterface() # Pause for the scene to get ready rospy.sleep(1) # Initialize the MoveIt! commander for the right arm right_arm = MoveGroupCommander('right_arm') # Initialize the MoveIt! commander for the gripper right_gripper = MoveGroupCommander('right_gripper') # Get the name of the end-effector link end_effector_link = right_arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) right_arm.set_goal_position_tolerance(0.01) right_arm.set_goal_orientation_tolerance(0.05) # Allow replanning to increase the odds of a solution right_arm.allow_replanning(True) # Allow 5 seconds per planning attempt right_arm.set_planning_time(5) # Remove leftover objects from a previous run scene.remove_attached_object(end_effector_link, 'tool') scene.remove_world_object('table') scene.remove_world_object('box1') scene.remove_world_object('box2') scene.remove_world_object('target') # Set the height of the table off the ground table_ground = 0.75 # Set the length, width and height of the table table_size = [0.2, 0.7, 0.01] # Set the length, width and height of the object to attach tool_size = [0.3, 0.02, 0.02] # Create a pose for the tool relative to the end-effector p = PoseStamped() p.header.frame_id = end_effector_link scene.attach_mesh # Place the end of the object within the grasp of the gripper p.pose.position.x = tool_size[0] / 2.0 - 0.025 p.pose.position.y = 0.0 p.pose.position.z = 0.0 # Align the object with the gripper (straight out) p.pose.orientation.x = 0 p.pose.orientation.y = 0 p.pose.orientation.z = 0 p.pose.orientation.w = 1 # Attach the tool to the end-effector scene.attach_box(end_effector_link, 'tool', p, tool_size) # Add a floating table top table_pose = PoseStamped() table_pose.header.frame_id = 'base_footprint' table_pose.pose.position.x = 0.35 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box('table', table_pose, table_size) # Update the current state right_arm.set_start_state_to_current_state() # Move the arm with the attached object to the 'straight_forward' position right_arm.set_named_target('straight_forward') right_arm.go() rospy.sleep(2) # Return the arm in the "resting" pose stored in the SRDF file right_arm.set_named_target('resting') right_arm.go() rospy.sleep(2) scene.remove_attached_object(end_effector_link, 'tool') moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
class PlanningSceneHelper: def __init__(self, package=None, mesh_folder_path=None): # interface to the planning and collision scenes self.psi = PlanningSceneInterface() # self.scene_pub = Publisher("/collision_object", CollisionObject, # queue_size=1, latch=True) self.vis_pub = Publisher("/collision_scene", MarkerArray, queue_size=10) self.marker_array = MarkerArray() sleep(1.0) if package is not None and mesh_folder_path is not None: # Build folder path for use in load rospack = RosPack() self.package = package self.mesh_folder_path = mesh_folder_path self.package_path = rospack.get_path(package) self.folder_path = os.path.join(self.package_path, mesh_folder_path)\ + os.sep else: loginfo( "Missing package or mesh folder path supplied to planning_scene_helper; no meshes can be added" ) # Create dict of objects, for removing markers later self.objects = {} self.next_id = 1 # Loads the selected mesh file into collision scene at the desired location. def add_mesh(self, object_id, frame, filename, visual=None, pose=None, position=None, orientation=None, rpy=None, color=None): if self.package is None: logwarn("No package was provided; no meshes can be loaded.") if visual is None: visual = filename filename = self.folder_path + filename stamped_pose = self.make_stamped_pose(frame=frame, pose=pose, position=position, orientation=orientation, rpy=rpy) try: self.psi.add_mesh(object_id, stamped_pose, filename) loginfo("Loaded " + object_id + " from" + filename + " as collision object.") marker = self.make_marker_stub(stamped_pose, color=color) marker.type = Marker.MESH_RESOURCE # marker.mesh_resource = "file:/" + self.folder_path + visual marker.mesh_resource = "package://" + self.package + os.sep + self.mesh_folder_path + os.sep + visual self.marker_array = self.make_new_marker_array_msg() self.marker_array.markers.append(marker) self.vis_pub.publish(self.marker_array) self.objects[object_id] = marker loginfo("Loaded " + object_id + " from " + marker.mesh_resource + " as marker.") except ROSException as e: loginfo("Problem loading " + object_id + " collision object: " + str(e)) except AssimpError as ae: loginfo("Problem loading " + object_id + " collision object: " + str(ae)) def add_cylinder(self, object_id, frame, size, pose=None, position=None, orientation=None, rpy=None, color=None): try: stamped_pose = self.make_stamped_pose(frame=frame, pose=pose, position=position, orientation=orientation, rpy=rpy) # Cylinders are special - they are not supported directly by # moveit_commander. It must be published manually to collision scene cyl = CollisionObject() cyl.operation = CollisionObject.ADD cyl.id = object_id cyl.header = stamped_pose.header prim = SolidPrimitive() prim.type = SolidPrimitive.CYLINDER prim.dimensions = [size[0], size[1]] cyl.primitives = [prim] cyl.primitive_poses = [stamped_pose.pose] # self.scene_pub.publish(cyl) marker = self.make_marker_stub(stamped_pose, [size[1] * 2, size[2] * 2, size[0]], color=color) marker.type = Marker.CYLINDER self.publish_marker(object_id, marker) sleep(0.5) logdebug("Loaded " + object_id + " as cylindrical collision object.") except ROSException as e: loginfo("Problem loading " + object_id + " collision object: " + str(e)) def add_sphere(self, object_id, frame, size, pose=None, position=None, orientation=None, rpy=None, color=None): try: stamped_pose = self.make_stamped_pose(frame=frame, pose=pose, position=position, orientation=orientation, rpy=rpy) self.psi.add_sphere(object_id, stamped_pose, size[0]) loginfo("got past adding collision scene object") marker = self.make_marker_stub( stamped_pose, [size[0] * 2, size[1] * 2, size[2] * 2], color=color) marker.type = Marker.SPHERE self.publish_marker(object_id, marker) sleep(0.5) loginfo("Loaded " + object_id + " as collision object.") except ROSException as e: loginfo("Problem loading " + object_id + " collision object: " + str(e)) def add_box(self, object_id, frame, size, pose=None, position=None, orientation=None, rpy=None, color=None): try: stamped_pose = self.make_stamped_pose(frame=frame, pose=pose, position=position, orientation=orientation, rpy=rpy) self.psi.add_box(object_id, stamped_pose, size) marker = self.make_marker_stub(stamped_pose, size, color=color) marker.type = Marker.CUBE self.publish_marker(object_id, marker) sleep(0.5) loginfo("Loaded " + object_id + " as collision object.") except ROSException as e: loginfo("Problem loading " + object_id + " collision object: " + str(e)) def attach_box(self, link, object_id, frame, size, attach_to_link, pose=None, position=None, orientation=None, rpy=None): """TODO: color is not yet supported, since it's not internally supported by psi.attach_box. Basically duplicate this method but with color support.""" try: stamped_pose = self.make_stamped_pose(frame=frame, pose=pose, position=position, orientation=orientation, rpy=rpy), self.psi.attach_box(link, object_id, stamped_pose, size, attach_to_link) sleep(0.5) loginfo("Attached " + object_id + " as collision object.") except ROSException as e: loginfo("Problem attaching " + object_id + " collision object: " + str(e)) @staticmethod def make_stamped_pose(frame, pose=None, position=None, orientation=None, rpy=None): if orientation is not None and rpy is not None: logwarn("Collision object has both orientation (quaternion) and " "Rotation (rpy) defined! Defaulting to quaternion " "representation") stamped_pose = PoseStamped() stamped_pose.header.frame_id = frame stamped_pose.header.stamp = Time.now() # use a pose if one is provided, otherwise, make your own from the # position and orientation. if pose is not None: stamped_pose.pose = pose else: stamped_pose.pose.position.x = position[0] stamped_pose.pose.position.y = position[1] stamped_pose.pose.position.z = position[2] # for orientation, allow either quaternion or RPY specification if orientation is not None: stamped_pose.pose.orientation.x = orientation[0] stamped_pose.pose.orientation.y = orientation[1] stamped_pose.pose.orientation.z = orientation[2] stamped_pose.pose.orientation.w = orientation[3] elif rpy is not None: quaternion = transformations.quaternion_from_euler( rpy[0], rpy[1], rpy[2]) stamped_pose.pose.orientation.x = quaternion[0] stamped_pose.pose.orientation.y = quaternion[1] stamped_pose.pose.orientation.z = quaternion[2] stamped_pose.pose.orientation.w = quaternion[3] else: stamped_pose.pose.orientation.w = 1 # make basic quaternion return stamped_pose # Fill a ROS Marker message with the provided data def make_marker_stub(self, stamped_pose, size=None, color=None): if color is None: color = (0.5, 0.5, 0.5, 1.0) if size is None: size = (1, 1, 1) marker = Marker() marker.header = stamped_pose.header # marker.ns = "collision_scene" marker.id = self.next_id marker.lifetime = Time(0) # forever marker.action = Marker.ADD marker.pose = stamped_pose.pose marker.color.r = color[0] marker.color.g = color[1] marker.color.b = color[2] if len(color) == 4: alpha = color[3] else: alpha = 1.0 marker.color.a = alpha marker.scale.x = size[0] marker.scale.y = size[1] marker.scale.z = size[2] self.next_id += 1 return marker def make_new_marker_array_msg(self): ma = MarkerArray() return ma # publish a single marker def publish_marker(self, object_id, marker): loginfo("Publishing marker for object {}".format(object_id)) self.marker_array = self.make_new_marker_array_msg() self.marker_array.markers.append(marker) self.vis_pub.publish(self.marker_array) self.objects[object_id] = marker # Remove the provided object from the world. def remove(self, object_id): # if object_id not in self.objects: # logwarn("PlanningSceneHelper was not used to create object with id " # + object_id + ". Attempting to remove it anyway.") try: # first remove the actual collision object self.psi.remove_world_object(object_id) if object_id in self.objects: # then remove the marker associated with it marker = self.objects[object_id] marker.action = Marker.DELETE self.publish_marker(object_id, marker) self.objects.pop(object_id) logdebug("Marker for collision object " + object_id + " removed.") except ROSException as e: loginfo("Problem removing " + object_id + " from collision scene:" + str(e)) return except KeyError as e: loginfo("Problem removing " + object_id + " from collision scene:" + str(e)) return loginfo("Model " + object_id + " removed from collision scene.") # Remove the provided attached collision object. def remove_attached(self, link, object_id): try: self.psi.remove_attached_object(link=link, name=object_id) loginfo("Attached object '" + object_id + "' removed from collision scene.") except: loginfo("Problem attached object '" + object_id + "' removing from collision scene.")
def __init__(self): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') rospy.Subscriber('/aruco_single/pose', PoseStamped, self.pose_cb,queue_size=1) scene=PlanningSceneInterface() self.scene_pub=rospy.Publisher('planning_scene',PlanningScene) self.colors=dict() rospy.sleep(1) arm=MoveGroupCommander('arm') #gripper=MoveGroupCommander('gripper') end_effector_link=arm.get_end_effector_link() arm.set_goal_position_tolerance(0.005) arm.set_goal_orientation_tolerance(0.025) arm.allow_replanning(True) #gripper.set_goal_position_tolerance(0.005) #gripper.set_goal_orientation_tolerance(0.025) #gripper.allow_replanning(True) reference_frame='base_link' arm.set_pose_reference_frame(reference_frame) arm.set_planning_time(5) #scene planning table_id='table' #cylinder_id='cylinder' box2_id='box2' target_id='target_object' #scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(table_id) scene.remove_world_object(target_id) rospy.sleep(2) table_ground=0.59 table_size=[0.5,1,0.01] #box1_size=[0.1,0.05,0.03] box2_size=[0.15,0.15,0.02] r_tool_size=[0.05,0.04,0.22] l_tool_size=[0.05,0.04,0.22] target_size=[0.05,0.05,0.1] table_pose=PoseStamped() table_pose.header.frame_id=reference_frame table_pose.pose.position.x=0.7 table_pose.pose.position.y=0.0 table_pose.pose.position.z=table_ground+table_size[2]/2.0 table_pose.pose.orientation.w=1.0 scene.add_box(table_id,table_pose,table_size) ''' box1_pose=PoseStamped() box1_pose.header.frame_id=reference_frame box1_pose.pose.position.x=0.7 box1_pose.pose.position.y=-0.2 box1_pose.pose.position.z=table_ground+table_size[2]+box1_size[2]/2.0 box1_pose.pose.orientation.w=1.0 scene.add_box(box1_id,box1_pose,box1_size) ''' box2_pose=PoseStamped() box2_pose.header.frame_id=reference_frame box2_pose.pose.position.x=0.55 box2_pose.pose.position.y=-0.12 box2_pose.pose.position.z=table_ground+table_size[2]+box2_size[2]/2.0 box2_pose.pose.orientation.w=1.0 scene.add_box(box2_id,box2_pose,box2_size) target_pose=PoseStamped() target_pose.header.frame_id=reference_frame target_pose.pose.position.x=0.58 target_pose.pose.position.y=0.05 target_pose.pose.position.z=table_ground+table_size[2]+target_size[2]/2.0 target_pose.pose.orientation.x=0 target_pose.pose.orientation.y=0 target_pose.pose.orientation.z=0 target_pose.pose.orientation.w=1 scene.add_box(target_id,target_pose,target_size) #left gripper l_p=PoseStamped() l_p.header.frame_id=end_effector_link l_p.pose.position.x=0.00 l_p.pose.position.y=0.06 l_p.pose.position.z=0.11 l_p.pose.orientation.w=1 scene.attach_box(end_effector_link,'l_tool',l_p,l_tool_size) #right gripper r_p=PoseStamped() r_p.header.frame_id=end_effector_link r_p.pose.position.x=0.00 r_p.pose.position.y= -0.06 r_p.pose.position.z=0.11 r_p.pose.orientation.w=1 scene.attach_box(end_effector_link,'r_tool',r_p,r_tool_size) #grasp g_p=PoseStamped() g_p.header.frame_id=end_effector_link g_p.pose.position.x=0.00 g_p.pose.position.y= -0.00 g_p.pose.position.z=0.025 g_p.pose.orientation.w=0.707 g_p.pose.orientation.x=0 g_p.pose.orientation.y=-0.707 g_p.pose.orientation.z=0 self.setColor(table_id,0.8,0,0,1.0) #self.setColor(box1_id,0.8,0.4,0,1.0) self.setColor(box2_id,0.8,0.4,0,1.0) self.setColor('r_tool',0.8,0,0) self.setColor('l_tool',0.8,0,0) self.setColor('target_object',0,1,0) self.sendColors() #motion planning arm.set_named_target("initial_arm") arm.go() rospy.sleep(2) grasp_pose=target_pose grasp_pose.pose.position.x-=0.15 #grasp_pose.pose.position.z= grasp_pose.pose.orientation.x=0 grasp_pose.pose.orientation.y=0.707 grasp_pose.pose.orientation.z=0 grasp_pose.pose.orientation.w=0.707 #arm.set_start_state_to_current_state() ''' arm.set_pose_target(grasp_pose,end_effector_link) traj=arm.plan() arm.execute(traj) print arm.get_current_joint_values() ''' pre_joint_state=[0.16588150906995922, 1.7060146047438647, -0.00961761728757362, 1.8614674591892713, -2.9556667436476847, 1.7432451233907822, 3.1415] arm.set_joint_value_target(pre_joint_state) traj=arm.plan() arm.execute(traj) rospy.sleep(2) arm.shift_pose_target(0,0.09,end_effector_link) arm.go() rospy.sleep(2) scene.attach_box(end_effector_link,target_id,g_p,target_size) rospy.sleep(2) #grasping is over , from now is pouring arm.shift_pose_target(2,0.15,end_effector_link) arm.go() rospy.sleep(2) joint_state_1=arm.get_current_joint_values() joint_state_1[0]-=0.17 arm.set_joint_value_target(joint_state_1) arm.go() rospy.sleep(1) joint_state_2=arm.get_current_joint_values() joint_state_2[6]-=1.8 arm.set_joint_value_target(joint_state_2) arm.go() rospy.sleep(1) #print arm.get_current_joint_values() #pouring test for i in range(1,5): joint_state_2[6]+=0.087 arm.set_joint_value_target(joint_state_2) arm.go() time.sleep(0.05) joint_state_2[6]-=0.087 arm.set_joint_value_target(joint_state_2) arm.go() time.sleep(0.05) print i joint_state_2[6]+=1.8 arm.set_joint_value_target(joint_state_2) arm.go() rospy.sleep(2) joint_state_1[0]+=0.17 arm.set_joint_value_target(joint_state_1) arm.go() rospy.sleep(1) arm.shift_pose_target(2,-0.15,end_effector_link) arm.go() rospy.sleep(2) scene.remove_attached_object(end_effector_link,target_id) rospy.sleep(2) arm.set_named_target("initial_arm") arm.go() rospy.sleep(2) #remove and shut down scene.remove_attached_object(end_effector_link,'l_tool') rospy.sleep(1) scene.remove_attached_object(end_effector_link,'r_tool') rospy.sleep(1) moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
p.pose.position.x = gripper_pose.pose.position.x p.pose.position.y = gripper_pose.pose.position.y p.pose.position.z = gripper_pose.pose.position.z # add part scene.add_box(PICK_OBJECT, p, (0.07, 0.07, 0.1)) rospy.loginfo("Added object to world") # attach object manually arm.attach_object(PICK_OBJECT, arm.get_end_effector_link(), GRIPPER_JOINTS) rospy.sleep(1) # ===== place start ==== # place_result = place(PLANNING_GROUP, PICK_OBJECT, generate_place_pose()) rospy.loginfo("Place Result is:") rospy.loginfo("Human readable error: " + str(moveit_error_dict[place_result.error_code.val])) rospy.sleep(5) # remove part scene.remove_world_object(PICK_OBJECT) scene.remove_attached_object(arm.get_end_effector_link(), PICK_OBJECT) rospy.sleep(2) i += 1 # end moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
if __name__=='__main__': roscpp_initialize(sys.argv) rospy.init_node('moveit_py_demo', anonymous=True) GRIPPER_FRAME = 'right_gripper_link' scene = PlanningSceneInterface() robot = RobotCommander() right_arm = MoveGroupCommander("right_arm") right_gripper = MoveGroupCommander("right_gripper") right_arm.set_planner_id("KPIECEkConfigDefault"); rospy.sleep(1) # clean the scene scene.remove_world_object("table") scene.remove_world_object("part") scene.remove_attached_object(GRIPPER_FRAME, "part") #rospy.logwarn("cleaning world") #right_arm.set_named_target("r_start") #right_arm.go() #right_gripper.set_named_target("open") #right_gripper.go() rospy.sleep(3) # publish a demo scene p = PoseStamped() p.header.frame_id = robot.get_planning_frame() # add a table p.pose.position.x = 1.0
class BTMotion: def __init__(self, name): # create messages that are used to publish feedback/result self._feedback = amazon_challenge_bt_actions.msg.BTFeedback() self._result = amazon_challenge_bt_actions.msg.BTResult() self._action_name = name self._as = actionlib.SimpleActionServer(self._action_name, amazon_challenge_bt_actions.msg.BTAction, execute_cb=self.execute_cb, auto_start = False) self.pub_posed = rospy.Publisher('arm_posed', String, queue_size=10) self.pub_rate = rospy.Rate(30) self._planning_scene = PlanningSceneInterface() # get ROS parameters rospy.loginfo('Getting parameters...') while not rospy.is_shutdown(): try: self._base_move_params = rospy.get_param('/base_move') self._timeout = rospy.get_param(name + '/timeout') self._sim = rospy.get_param(name + '/sim') self._base_pos_dict = rospy.get_param('/base_pos_dict') self._left_arm_joint_pos_dict = rospy.get_param('/left_arm_joint_pos_dict') self._right_arm_joint_pos_dict = rospy.get_param('/right_arm_joint_pos_dict') break except: rospy.sleep(random.uniform(0,2)) continue self._exit = False while not rospy.is_shutdown(): try: self._robot = moveit_commander.RobotCommander() self._left_arm = self._robot.get_group('left_arm') self._right_arm = self._robot.get_group('right_arm') self._arms = self._robot.get_group('arms') self._torso = self._robot.get_group('torso') self._head = self._robot.get_group('head') self._arms_dict = {'left_arm': self._left_arm, 'right_arm': self._right_arm} break except: rospy.sleep(random.uniform(0,2)) continue self._tf_listener = tf.TransformListener() self._next_task_sub = rospy.Subscriber("/amazon_next_task", String, self.get_task) self._shelf_pose_sub = rospy.Subscriber("/pubShelfSep", PoseStamped, self.get_shelf_pose) self._got_shelf_pose = False self._l_gripper_pub = rospy.Publisher('/l_gripper_controller/command', Pr2GripperCommand) while not rospy.is_shutdown(): try: self._tool_size = rospy.get_param('/tool_size', [0.16, 0.02, 0.04]) self._contest = rospy.get_param('/contest', True) break except: rospy.sleep(random.uniform(0,1)) continue if self._contest: self._length_tool = 0.18 + self._tool_size[0] else: self._length_tool = 0.216 + self._tool_size[0] self._as.start() rospy.loginfo('['+rospy.get_name()+']: ready!') def get_shelf_pose(self, msg): self._shelf_pose = msg self._got_shelf_pose = True def get_bm_srv(self): while not rospy.is_shutdown(): try: rospy.wait_for_service('/base_move_server/move', 5.0) rospy.wait_for_service('/base_move_server/preempt', 5.0) break except: rospy.loginfo('[' + rospy.get_name() + ']: waiting for base move server') continue self._bm_move_srv = rospy.ServiceProxy('/base_move_server/move', BaseMove) self._bm_preempt_srv = rospy.ServiceProxy('/base_move_server/preempt', Empty) def timer_callback(self, event): self._timer_started = True rospy.logerr('[' + rospy.get_name() + ']: TIMED OUT!') self._planning_scene.remove_attached_object('l_wrist_roll_link', 'grasped_object') self._planning_scene.remove_world_object('grasped_object') # pull the base back 60 cm self._left_arm.stop() self._right_arm.stop() r = rospy.Rate(1.0) while not self._got_shelf_pose: rospy.loginfo('[' + rospy.get_name() + ']: waiting for shelf pose') r.sleep() base_pos_goal = [-1.42, -self._shelf_pose.pose.position.y, 0.0, 0.0, 0.0, 0.0] self.get_bm_srv() self._bm_preempt_srv.call(EmptyRequest()) while not self.go_base_pos_async(base_pos_goal): rospy.sleep(1.0) left_arm_joint_pos_goal = copy.deepcopy(self._left_arm_joint_pos_dict['start']) right_arm_joint_pos_goal = copy.deepcopy(self._right_arm_joint_pos_dict['start']) joint_pos_goal = left_arm_joint_pos_goal + right_arm_joint_pos_goal self._arms.set_joint_value_target(joint_pos_goal) self._arms.go() self._exit = True def execute_exit(self): if self._exit: self._success = False self.set_status('FAILURE') self._timer.shutdown() return True return False def execute_cb(self, goal): print 'bt motion execute callback' def shutdown_simtrack(self): # get simtrack switch objects service while not rospy.is_shutdown(): try: rospy.wait_for_service('/simtrack/switch_objects', 10.0) break except: rospy.loginfo('[' + rospy.get_name() + ']: waiting for simtrack switch object service') continue simtrack_switch_objects_srv = rospy.ServiceProxy('/simtrack/switch_objects', SwitchObjects) simtrack_switch_objects_srv.call() def init_as(self): self._planning_scene.remove_attached_object('l_wrist_roll_link', 'grasped_object') self._planning_scene.remove_world_object('grasped_object') self._timer_started = False self._exit=False self._timer = rospy.Timer(rospy.Duration(self._timeout), self.timer_callback, oneshot=True) self.shutdown_simtrack() rospy.sleep(2.0) def get_task(self, msg): text = msg.data text = text.replace('[','') text = text.replace(']','') words = text.split(',') self._bin = words[0] self._item = words[1] def get_row(self): ''' For setting the torso height and arm pose ''' while not rospy.is_shutdown(): try: if self._bin=='bin_A' or self._bin=='bin_B' or self._bin=='bin_C': return 'row_1' elif self._bin=='bin_D' or self._bin=='bin_E' or self._bin=='bin_F': return 'row_2' elif self._bin=='bin_G' or self._bin=='bin_H' or self._bin=='bin_I': return 'row_3' elif self._bin=='bin_J' or self._bin=='bin_K' or self._bin=='bin_L': return 'row_4' except: pass def get_column(self): ''' For setting the base pose ''' while not rospy.is_shutdown(): try: if self._bin=='bin_A' or self._bin=='bin_D' or self._bin=='bin_G' or self._bin=='bin_J': return 'column_1' elif self._bin=='bin_B' or self._bin=='bin_E' or self._bin=='bin_H' or self._bin=='bin_K': return 'column_2' elif self._bin=='bin_C' or self._bin=='bin_F' or self._bin=='bin_I' or self._bin=='bin_L': return 'column_3' except: pass def go_joint_goal_async(self, group, joint_pos_goal, normalize_angles=False): q_goal = np.array(joint_pos_goal) if normalize_angles: q_goal = self.normalize_angles(joint_pos_goal) group.set_joint_value_target(joint_pos_goal) if not group.go(wait=False): return False q_now = np.array(group.get_current_joint_values()) if normalize_angles: q_now = self.normalize_angles(q_now) q_tol = group.get_goal_joint_tolerance() if group.get_name()=='left_arm' or group.get_name()=='right_arm' or group.get_name()=='arms' or group.get_name()=='head': q_tol = 0.04 elif group.get_name()=='torso': q_tol = 0.003 t_print = rospy.Time.now() r = rospy.Rate(1.0) # check for preemption while the arm hasn't reach goal configuration while np.max(np.abs(q_goal-q_now)) > q_tol and not rospy.is_shutdown(): if self.execute_exit(): return False q_now = np.array(group.get_current_joint_values()) if normalize_angles: q_now = self.normalize_angles(q_now) # check that preempt has not been requested by the client if self._as.is_preempt_requested(): #HERE THE CODE TO EXECUTE WHEN THE BEHAVIOR TREE DOES HALT THE ACTION group.stop() rospy.loginfo('action halted') self._as.set_preempted() self._exit = True if self.execute_exit(): return False if (rospy.Time.now()-t_print).to_sec()>3.0: t_print = rospy.Time.now() rospy.loginfo('[' + rospy.get_name() + ']: executing action') #HERE THE CODE TO EXECUTE AS LONG AS THE BEHAVIOR TREE DOES NOT HALT THE ACTION r.sleep() if rospy.is_shutdown(): return False return True def normalize_angles(self, q): ''' normalize angles to -pi, pi ''' q_normalized = np.mod(q, 2*np.pi) for i in xrange(np.size(q)): if q_normalized[i] > np.pi: q_normalized[i] = -(2*np.pi - q_normalized[i]) return q_normalized def go_base_pos_async(self, base_pos_goal): angle = base_pos_goal[5] pos = base_pos_goal[0:2] r = rospy.Rate(20.0) req = BaseMoveRequest() req.x = pos[0] req.y = pos[1] req.theta = angle self.get_bm_srv() res = self._bm_move_srv.call(req) if self.execute_exit(): return False # check that preempt has not been requested by the client if self._as.is_preempt_requested(): #HERE THE CODE TO EXECUTE WHEN THE BEHAVIOR TREE DOES HALT THE ACTION rospy.loginfo('action halted while moving base') self._as.set_preempted() self._exit = True if self.execute_exit(): return False return res.result def go_base_moveit_group_pos_async(self, base_pos_goal, group, joint_pos_goal, normalize_angles=False): angle = base_pos_goal[5] pos = base_pos_goal[0:2] r = rospy.Rate(20.0) q_goal = np.array(joint_pos_goal) if normalize_angles: q_goal = self.normalize_angles(joint_pos_goal) group.set_joint_value_target(joint_pos_goal) group.go(wait=False) q_now = np.array(group.get_current_joint_values()) if normalize_angles: q_now = self.normalize_angles(q_now) q_tol = group.get_goal_joint_tolerance() if group.get_name()=='left_arm' or group.get_name()=='right_arm' or group.get_name()=='arms' or group.get_name()=='head': q_tol = 0.04 elif group.get_name()=='torso': q_tol = 0.003 t_print = rospy.Time.now() req = BaseMoveRequest() req.x = pos[0] req.y = pos[1] req.theta = angle self.get_bm_srv() res = self._bm_move_srv.call(req) if self.execute_exit(): return False # check that preempt has not been requested by the client if self._as.is_preempt_requested(): #HERE THE CODE TO EXECUTE WHEN THE BEHAVIOR TREE DOES HALT THE ACTION rospy.loginfo('action halted while moving base') self._as.set_preempted() self._exit = True if self.execute_exit(): return False # check for preemption while the arm hasn't reach goal configuration while np.max(np.abs(q_goal-q_now)) > q_tol and not rospy.is_shutdown(): if self.execute_exit(): return False q_now = np.array(group.get_current_joint_values()) if normalize_angles: q_now = self.normalize_angles(q_now) # check that preempt has not been requested by the client if self._as.is_preempt_requested(): #HERE THE CODE TO EXECUTE WHEN THE BEHAVIOR TREE DOES HALT THE ACTION group.stop() rospy.loginfo('action halted') self._as.set_preempted() self._exit = True if self.execute_exit(): return False if (rospy.Time.now()-t_print).to_sec()>3.0: t_print = rospy.Time.now() rospy.loginfo('[' + rospy.get_name() + ']: executing action') #HERE THE CODE TO EXECUTE AS LONG AS THE BEHAVIOR TREE DOES NOT HALT THE ACTION r.sleep() if rospy.is_shutdown(): return False return res.result def request_detection(self): client = actionlib.SimpleActionClient('amazon_detector', amazon_challenge_bt_actions.msg.DetectorAction) # Waits until the action server has started up and started # listening for goals. rospy.loginfo('Start Waiting') client.wait_for_server() # Creates a goal to send to the action server. goal = amazon_challenge_bt_actions.msg.DetectorGoal(parameter=1) # Sends the goal to the action server. client.send_goal(goal) rospy.loginfo('Goal Sent') # Waits for the server to finish performing the action. client.wait_for_result() def set_status(self,status): if status == 'SUCCESS': self.pub_posed.publish("SUCCESS") rospy.sleep(1) self._feedback.status = 1 self._result.status = self._feedback.status rospy.loginfo('Action %s: Succeeded' % self._action_name) self._as.set_succeeded(self._result) elif status == 'FAILURE': self._feedback.status = 2 self._result.status = self._feedback.status rospy.loginfo('Action %s: Failed' % self._action_name) self._as.set_succeeded(self._result) else: rospy.logerr('Action %s: has a wrong return status' % self._action_name) def open_l_gripper(self): gripper_command_msg = Pr2GripperCommand() gripper_command_msg.max_effort = 40.0 gripper_command_msg.position = 10.0 r = rospy.Rate(10.0) t_init = rospy.Time.now() while (rospy.Time.now()-t_init).to_sec()<3.0 and not rospy.is_shutdown(): if self.execute_exit(): return False self._l_gripper_pub.publish(gripper_command_msg) # check that preempt has not been requested by the client if self._as.is_preempt_requested(): #HERE THE CODE TO EXECUTE WHEN THE BEHAVIOR TREE DOES HALT THE ACTION rospy.loginfo('action halted while opening gripper') self._as.set_preempted() self._exit = True if self.execute_exit(): return False r.sleep() return True def move_l_arm_z(self, z_desired): ''' computes straight line cartesian path in z direction :param z_desired: of tool tip w.r.t. odom_combined :return: ''' waypoints = [] # waypoints.append(self._left_arm.get_current_pose().pose) wpose = copy.deepcopy(self._left_arm.get_current_pose().pose) wpose.position.z = z_desired + self._length_tool waypoints.append(copy.deepcopy(wpose)) (plan, fraction) = self._left_arm.compute_cartesian_path(waypoints, 0.05, 0.0) # TODO make this asynchronous self._left_arm.execute(plan) return True
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') #Initialize robot robot = moveit_commander.RobotCommander() # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # Create a publisher for displaying object frames self.object_frames_pub = rospy.Publisher('object_frames', PoseStamped, queue_size=10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the MoveIt! commander for the arm right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the MoveIt! commander for the gripper right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link eef = right_arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) # right_arm.set_goal_position_tolerance(0.05) # right_arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution right_arm.allow_replanning(True) # Set the right arm reference frame right_arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt right_arm.set_planning_time(5) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # Prepare Gazebo Subscriber self.pwh = None self.pwh_copy = None self.idx_targ = None self.gazebo_subscriber = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) # Prepare Gripper and open it self.ac = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',pr2c.Pr2GripperCommandAction) self.ac.wait_for_server() g_open = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.088, 100)) g_close = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.0, 1)) self.ac.send_goal(g_open) rospy.sleep(2) # PREPARE THE SCENE while self.pwh is None: rospy.sleep(0.05) target_id = 'target' self.taid = self.pwh.name.index('wood_cube_5cm') table_id = 'table' self.tid = self.pwh.name.index('table') #obstacle1_id = 'obstacle1' #self.o1id = self.pwh.name.index('wood_block_10_2_1cm') # Remove leftover objects from a previous run scene.remove_world_object(target_id) scene.remove_world_object(table_id) #scene.remove_world_object(obstacle1_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Set the target size [l, w, h] target_size = [0.05, 0.05, 0.05] table_size = [1.5, 0.8, 0.03] #obstacle1_size = [0.1, 0.025, 0.01] ## Set the target pose on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose = self.pwh.pose[self.taid] target_pose.pose.position.z += 0.025 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose = self.pwh.pose[self.tid] table_pose.pose.position.z += 1 scene.add_box(table_id, table_pose, table_size) #obstacle1_pose = PoseStamped() #obstacle1_pose.header.frame_id = REFERENCE_FRAME #obstacle1_pose.pose = self.pwh.pose[self.o1id] ## Add the target object to the scene #scene.add_box(obstacle1_id, obstacle1_pose, obstacle1_size) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.50 place_pose.pose.position.y = -0.30 place_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) ### Make the target purple ### self.setColor(target_id, 0.6, 0, 1, 1.0) # Send the colors to the planning scene self.sendColors() #print target_pose self.object_frames_pub.publish(target_pose) rospy.sleep(2) # Initialize the grasp pose to the target pose grasp_pose = target_pose #grasp_pose.header.frame_id = 'gazebo_wolrd' # Shift the grasp pose by half the width of the target to center it # grasp_pose.pose.position.y -= target_size[1] / 2.0 # grasp_pose.pose.position.x = target_pose.pose.position.x / 2.0 # grasp_pose.pose.position.x = target_pose.pose.position.x -0.07 # grasp_pose.pose.position.z += 0.18 #Allowed touch object list # ato = [target_id, 'r_forearm_link'] # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id]) #### [target_id] # Publish the grasp poses so they can be viewed in RViz for grasp in grasps: # print grasp.grasp_pose self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation success = False n_attempts = 0 #Allowed touch link list atl = ['r_forearm_link'] # Repeat until we succeed or run out of attempts while success == False and n_attempts < max_pick_attempts: success = right_arm.pick(target_id, grasps) n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) rospy.sleep(0.2) if success: self.ac.send_goal(g_close) rospy.sleep(3) ## If the pick was successful, attempt the place operation #if success: #success = False #n_attempts = 0 ## Generate valid place poses #places = self.make_places(place_pose) ## Repeat until we succeed or run out of attempts #while success == False and n_attempts < max_place_attempts: #for place in places: #success = right_arm.place(target_id, place) #if success: #break #n_attempts += 1 #rospy.loginfo("Place attempt: " + str(n_attempts)) #rospy.sleep(0.2) #if not success: #rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") #else: #rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") ## Return the arm to the "resting" pose stored in the SRDF file ##right_arm.set_named_target('resting') ##right_arm.go() ## Open the gripper to the neutral position #right_gripper.set_joint_value_target(GRIPPER_NEUTRAL) #right_gripper.go() #rospy.sleep(1) #rospy.spin() # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self): roscpp_initialize(sys.argv) rospy.init_node('moveit_py_demo', anonymous=True) scene = PlanningSceneInterface() robot = RobotCommander() right_arm = MoveGroupCommander(GROUP_NAME_ARM) #right_arm.set_planner_id("KPIECEkConfigDefault"); right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) eef = right_arm.get_end_effector_link() rospy.sleep(2) scene.remove_attached_object(GRIPPER_FRAME, "part") # clean the scene scene.remove_world_object("table") scene.remove_world_object("part") #right_arm.set_named_target("r_start") #right_arm.go() #right_gripper.set_named_target("right_gripper_open") #right_gripper.go() rospy.sleep(1) # publish a demo scene p = PoseStamped() p.header.frame_id = robot.get_planning_frame() # add a table #p.pose.position.x = 0.42 #p.pose.position.y = -0.2 #p.pose.position.z = 0.3 #scene.add_box("table", p, (0.5, 1.5, 0.6)) # add an object to be grasped p.pose.position.x = 0.7 p.pose.position.y = -0.2 p.pose.position.z = 0.85 scene.add_box("part", p, (0.07, 0.01, 0.2)) rospy.sleep(1) g = Grasp() g.id = "test" start_pose = PoseStamped() start_pose.header.frame_id = FIXED_FRAME # start the gripper in a neutral pose part way to the target start_pose.pose.position.x = 0.47636 start_pose.pose.position.y = -0.21886 start_pose.pose.position.z = 0.9 start_pose.pose.orientation.x = 0.00080331 start_pose.pose.orientation.y = 0.001589 start_pose.pose.orientation.z = -2.4165e-06 start_pose.pose.orientation.w = 1 right_arm.set_pose_target(start_pose) right_arm.go() rospy.sleep(2) # generate a list of grasps grasps = self.make_grasps(start_pose) result = False n_attempts = 0 # repeat until will succeed while result == False: result = robot.right_arm.pick("part", grasps) n_attempts += 1 print "Attempts: ", n_attempts rospy.sleep(0.3) rospy.spin() roscpp_shutdown()
class MoveItDemo: def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') #Initialize robot robot = moveit_commander.RobotCommander() # Use the planning scene object to add or remove objects self.scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # Create a publisher for displaying object frames self.object_frames_pub = rospy.Publisher('object_frames', PoseStamped, queue_size=10) ### Create a publisher for visualizing direction ### self.p_pub = rospy.Publisher('target', PoseStamped, latch=True, queue_size = 10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the MoveIt! commander for the arm self.right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the MoveIt! commander for the gripper self.right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # eel = len(self.right_arm.get_end_effector_link()) # print eel # Allow 5 seconds per planning attempt # self.right_arm.set_planning_time(5) # Prepare Action Controller for gripper self.ac = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',pr2c.Pr2GripperCommandAction) self.ac.wait_for_server() # Give the scene a chance to catch up rospy.sleep(2) # Prepare Gazebo Subscriber self.pwh = None self.pwh_copy = None self.idx_targ = None self.gazebo_subscriber = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) # self.m_error = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) ### OPEN THE GRIPPER ### self.open_gripper() ### Attach / Remove Object ### self.aro = None # PREPARE THE SCENE while self.pwh is None: rospy.sleep(0.05) # Run and keep in the BG the scene generator also add the ability to kill the code with ctrl^c timerThread = threading.Thread(target=self.scene_generator) timerThread.daemon = True timerThread.start() ### GIVE SCENE TIME TO CATCH UP ### rospy.sleep(5) print "==================== Executing ===========================" blist = ['target','custom_2','custom_3', 'custom_table'] self.idx_list = [] for name in obj_id: print name if name not in blist: self.idx_list.append(obj_id.index(name)) ################################## TESTING AREA ##################################### # ga = self.grasp_attempt() # print ga # print obj_id success = False i=0 while success == False: idx = self.idx_list[i] print idx new_pose, ds = self.declutter_scene(idx) if ds == True: self.post_grasp(new_pose, obj_id[idx]) i+=1 ################# GRASPING ATTEMPTS ################### # ga = self.grasp_attempt() # print ga rospy.sleep(5) # # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # # Exit the script moveit_commander.os._exit(0) ################################################################# FUNCTIONS ################################################################################# def grasp_attempt(self): init_poses = [] grasp_poses = [] for axis in range(0,5): pg = self.grasp_pose(obj_pose[obj_id.index('target')], axis, 'pg') gp = self.grasp_pose(obj_pose[obj_id.index('target')], axis, 'gp') init_poses.append(pg) grasp_poses.append(gp) gid, grasps = self.grasp_generator(grasp_poses) for i in range(0, len(gid)): self.gripper_pose_pub.publish(grasps[i]) rospy.sleep(0.1) success = False for pg in range(0,5): print pg plp = self.right_arm.plan(init_poses[pg].pose) print len(plp.joint_trajectory.points) if len(plp.joint_trajectory.points) == 0: print "No valid pregrasp Position, continuing on next one" continue self.right_arm.plan(init_poses[pg].pose) self.right_arm.go() if pg == 0: idx = gid.index('front') elif pg == 1: idx = gid.index('right') elif pg == 2: idx = gid.index('left') elif pg == 3: idx = gid.index('topx') else: idx = gid.index('topy') print ("idx = ",idx) for g in range(idx, len(gid)): ### TODO: fix the loop here, we dont want to check every single grasp after the index print g pl2 = self.right_arm.plan(grasps[g].pose) print len(pl2.joint_trajectory.points) if len(pl2.joint_trajectory.points) == 0: print "No Valid Grasp, continuing on next one" continue self.right_arm.plan(grasps[g].pose) self.right_arm.go() success = True break if success == True: break return success def declutter_scene(self,index): print obj_id[index] init_poses = [] grasp_poses = [] for axis in range(0,5): pg = self.grasp_pose(obj_pose[index], axis, 'pg') gp = self.grasp_pose(obj_pose[index], axis, 'gp') init_poses.append(pg) grasp_poses.append(gp) gid, grasps = self.grasp_generator(grasp_poses) for i in range(0, len(gid)): self.gripper_pose_pub.publish(grasps[i]) rospy.sleep(0.1) success = False for pg in range(0,5): print pg plp = self.right_arm.plan(init_poses[pg].pose) print len(plp.joint_trajectory.points) if len(plp.joint_trajectory.points) == 0: print "No valid pregrasp Position, continuing on next one" continue self.right_arm.plan(init_poses[pg].pose) self.right_arm.go() if pg == 0: idx = gid.index('front') elif pg == 1: idx = gid.index('right') elif pg == 2: idx = gid.index('left') elif pg == 3: idx = gid.index('topx') else: idx = gid.index('topy') print ("idx = ",idx) for g in range(idx, len(gid)): ### TODO: fix the loop here, we dont want to check every single grasp after the index print g pl2 = self.right_arm.plan(grasps[g].pose) print len(pl2.joint_trajectory.points) if len(pl2.joint_trajectory.points) == 0: print "No Valid Grasp, continuing on next one" continue self.right_arm.plan(grasps[g].pose) self.right_arm.go() new_pose = grasps[g] success = True break if success == True: break return (new_pose,success) def post_grasp(self,new_pose, obj_to_grasp): ######### GRASP OBJECT/ REMOVE FROM SCENE ######. self.close_gripper() self.aro = obj_to_grasp print self.aro # ### POST GRASP RETREAT ### # M1 = transformations.quaternion_matrix([new_pose.pose.orientation.x, new_pose.pose.orientation.y, new_pose.pose.orientation.z, new_pose.pose.orientation.w]) # M1[0,3] = new_pose.pose.position.x # M1[1,3] = new_pose.pose.position.y # M1[2,3] = new_pose.pose.position.z # M2 = transformations.euler_matrix(0, 0, 0) # M2[0,3] = 0.0 # offset about x # M2[1,3] = 0.0 # about y # M2[2,3] = 0.3 # about z # T1 = np.dot(M1, M2) # npo = deepcopy(new_pose) # npo.pose.position.x = T1[0,3] # npo.pose.position.y = T1[1,3] # npo.pose.position.z = T1[2,3] # quat = transformations.quaternion_from_matrix(T1) # npo.pose.orientation.x = quat[0] # npo.pose.orientation.y = quat[1] # npo.pose.orientation.z = quat[2] # npo.pose.orientation.w = quat[3] # npo.header.frame_id = REFERENCE_FRAME # self.right_arm.plan(npo.pose) # self.right_arm.go() ### PLACE THE OBJECT place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.80 place_pose.pose.position.y = -0.33 place_pose.pose.position.z = 0.53 place_pose.pose.orientation.w = 1.0 def grasp_pose(self, target_pose, axis, stage): ############ TODO : GENERATE AUTOMATED PRE-GRASPING POSITIONS BASED ON THE PRIMITIVE ######### if axis == 0: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, 0) if stage == 'pg': M2[0,3] = -0.25 # offset about x elif stage == 'gp': M2[0,3] = -0.18 # offset about x M2[1,3] = 0.0 # about y M2[2,3] = 0.0 # about z elif axis == 1: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, 1.57) M2[0,3] = 0.0 # offset about x if stage == 'pg': M2[1,3] = -0.25 # about y elif stage == 'gp': M2[1,3] = -0.18 # about y M2[2,3] = 0.0 # about z elif axis ==2: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, -1.57) M2[0,3] = 0.0 # offset about x if stage == 'pg': M2[1,3] = 0.25 # about y elif stage == 'gp': M2[1,3] = 0.18 # about y M2[2,3] = 0.0 # about z elif axis ==3: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 1.57, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y if stage == 'pg': M2[2,3] = 0.30 # about z elif stage == 'gp': M2[2,3] = 0.23 # about z else: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(1.57, 1.57, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y if stage == 'pg': M2[2,3] = 0.30 # about z elif stage == 'gp': M2[2,3] = 0.23 # about z T1 = np.dot(M1, M2) grasp_pose = deepcopy(target_pose) grasp_pose.pose.position.x = T1[0,3] grasp_pose.pose.position.y = T1[1,3] grasp_pose.pose.position.z = T1[2,3] quat = transformations.quaternion_from_matrix(T1) grasp_pose.pose.orientation.x = quat[0] grasp_pose.pose.orientation.y = quat[1] grasp_pose.pose.orientation.z = quat[2] grasp_pose.pose.orientation.w = quat[3] grasp_pose.header.frame_id = REFERENCE_FRAME return grasp_pose def grasp_generator(self, initial_poses): # A list to hold the grasps grasps = [] o = [] # Original Pose of the object (o) O=[] gid = [] i= 0 while i < len(initial_poses): o.append(initial_poses[i]) i+=1 G = transformations.euler_matrix(0, 0, 0) # Generate a grasps for along z axis (x and y directions) k = 0 while k <= 4: O.append(transformations.quaternion_matrix([o[k].pose.orientation.x, o[k].pose.orientation.y, o[k].pose.orientation.z, o[k].pose.orientation.w])) O[k][0,3] = o[k].pose.position.x O[k][1,3] = o[k].pose.position.y O[k][2,3] = o[k].pose.position.z if k in range(0,3): for z in self.drange(-obj_size[obj_id.index('target')][2]/2, obj_size[obj_id.index('target')][2]/2, 0.02): # print z T = np.dot(O[k], G) grasp = deepcopy(o[k]) grasp.pose.position.x = T[0,3] grasp.pose.position.y = T[1,3] grasp.pose.position.z = T[2,3] +z quat = transformations.quaternion_from_matrix(T) grasp.pose.orientation.x = quat[0] grasp.pose.orientation.y = quat[1] grasp.pose.orientation.z = quat[2] grasp.pose.orientation.w = quat[3] grasp.header.frame_id = REFERENCE_FRAME # Append the grasp to the list grasps.append(deepcopy(grasp)) if k ==0: gid.append('front') elif k ==1: gid.append('right') elif k ==2: gid.append('left') elif k == 3: for x in self.drange(-obj_size[obj_id.index('target')][1]/2, obj_size[obj_id.index('target')][1]/2, 0.01): # print z T = np.dot(O[k], G) grasp = deepcopy(o[k]) grasp.pose.position.x = T[0,3] +x grasp.pose.position.y = T[1,3] grasp.pose.position.z = T[2,3] quat = transformations.quaternion_from_matrix(T) grasp.pose.orientation.x = quat[0] grasp.pose.orientation.y = quat[1] grasp.pose.orientation.z = quat[2] grasp.pose.orientation.w = quat[3] grasp.header.frame_id = REFERENCE_FRAME # Append the grasp to the list grasps.append(deepcopy(grasp)) gid.append('topx') else: for y in self.drange(-obj_size[obj_id.index('target')][1]/2, obj_size[obj_id.index('target')][1]/2, 0.01): # print z T = np.dot(O[k], G) grasp = deepcopy(o[k]) grasp.pose.position.x = T[0,3] grasp.pose.position.y = T[1,3] +y grasp.pose.position.z = T[2,3] quat = transformations.quaternion_from_matrix(T) grasp.pose.orientation.x = quat[0] grasp.pose.orientation.y = quat[1] grasp.pose.orientation.z = quat[2] grasp.pose.orientation.w = quat[3] grasp.header.frame_id = REFERENCE_FRAME # Append the grasp to the list grasps.append(deepcopy(grasp)) gid.append('topy') k+=1 # Return the list return (gid,grasps) def scene_generator(self): obj_pose =[] obj_id = [] obj_size = [] bl = ['ground_plane','pr2'] global obj_pose, obj_id , obj_size ops = PoseStamped() ops.header.frame_id = REFERENCE_FRAME for model_name in self.pwh.name: if model_name not in bl: obj_id.append(model_name) ops.pose = self.pwh.pose[self.pwh.name.index(model_name)] obj_pose.append(deepcopy(ops)) obj_size.append([0.05, 0.05, 0.15]) obj_id[obj_id.index('custom_1')] = 'target' obj_size[obj_id.index('custom_2')] = [0.05, 0.05, 0.10] obj_size[obj_id.index('custom_3')] = [0.05, 0.05, 0.05] obj_size[obj_id.index('custom_table')] = [1.5, 0.8, 0.03] ### REMOVE OBJECT FROM PREVIOUS RUNS ### for i in range(0, len(obj_id)): self.scene.remove_world_object(obj_id[i]) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, obj_id[obj_id.index('target')]) next_call = time.time() while True: next_call = next_call+1 if self.aro is None: for i in range(0, len(obj_id)): ### CREATE THE SCENE ### self.scene.add_box(obj_id[i], obj_pose[i], obj_size[i]) ### Make the target purple and obstacles orange ### self.setColor(obj_id[obj_id.index('target')], 0.6, 0, 1, 1.0) self.setColor(obj_id[obj_id.index('custom_2')], 1, 0.623, 0, 1.0) self.setColor(obj_id[obj_id.index('custom_3')], 1, 0.623, 0, 1.0) self.setColor(obj_id[obj_id.index('custom_1_0')], 1, 0.623, 0, 1.0) # Send the colors to the planning scene self.sendColors() else: ###### ATTACH ITEM TO GRIPPER ###### touch_links = [GRIPPER_FRAME, 'r_gripper_l_finger_tip_link','r_gripper_r_finger_tip_link', 'r_gripper_r_finger_link', 'r_gripper_l_finger_link'] #print touch_links self.scene.attach_box(GRIPPER_FRAME, obj_id[self.aro], obj_pose[self.aro], obj_size[self.aro], touch_links) ### REMOVE SPECIFIC OBJECT AFTER IT HAS BEEN ATTACHED TO GRIPPER ### self.scene.remove_world_object(obj_id[self.aro]) time.sleep(next_call - time.time()) def model_state_callback(self,msg): self.pwh = ModelStates() self.pwh = msg def drange(self, start, stop, step): r = start while r < stop: yield r r += step def close_gripper(self): g_close = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.035, 100)) self.ac.send_goal(g_close) self.ac.wait_for_result() rospy.sleep(15) # Gazebo requires up to 15 seconds to attach object def open_gripper(self): g_open = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.088, 100)) self.ac.send_goal(g_open) self.ac.wait_for_result() rospy.sleep(5) # And up to 20 to detach it # Set the color of an object def setColor(self, name, r, g, b, a = 0.9): # Initialize a MoveIt color object color = ObjectColor() # Set the id to the name given as an argument color.id = name # Set the rgb and alpha values given as input color.color.r = r color.color.g = g color.color.b = b color.color.a = a # Update the global color dictionary self.colors[name] = color # Actually send the colors to MoveIt! def sendColors(self): # Initialize a planning scene object p = PlanningScene() # Need to publish a planning scene diff p.is_diff = True # Append the colors from the global color dictionary for color in self.colors.values(): p.object_colors.append(color) # Publish the scene diff self.scene_pub.publish(p)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) # Initialize the ROS node rospy.init_node('moveit_demo', anonymous=True) # Construct the initial scene object scene = PlanningSceneInterface() rospy.sleep(1) # Connect to the right_arm move group right_arm = moveit_commander.MoveGroupCommander('arm') # Get the name of the end-effector link end_effector_link = right_arm.get_end_effector_link() # Display the name of the end_effector link rospy.loginfo("The end effector link is: " + str(end_effector_link)) right_arm.allow_replanning(True) # Set a small tolerance on joint angles right_arm.set_goal_joint_tolerance(0.001) right_arm.set_goal_position_tolerance(0.0001) for i in range(5): scene.remove_attached_object('block' + str(i + 1)) scene.remove_world_object('block' + str(i + 1)) rospy.sleep(0.5) # Start the arm target in "right" pose stored in the SRDF file right_arm.set_named_target('right') # Plan a trajectory to the goal configuration traj = right_arm.plan() # Execute the planned trajectory right_arm.execute(traj) # Pause for a moment rospy.sleep(1) target_pose = right_arm.get_current_pose() target_pose.pose.position.x -= 0.2 target_pose.pose.position.y += 0.4 target_pose.pose.position.z -= 0.5 target_pose.pose.orientation.w = 1 object_pose = target_pose #object_pose.pose.position.x -= 0.08 q = quaternion_from_euler(0, 0, -1.5707) place_pose = PoseStamped() place_pose.header.frame_id = 'base_footprint' place_pose.pose.position.x = 0.3 place_pose.pose.position.y = -0.3 place_pose.pose.position.z = 0.25 place_pose.pose.orientation.x = q[0] place_pose.pose.orientation.y = q[1] place_pose.pose.orientation.z = q[2] place_pose.pose.orientation.w = q[3] count = 0 while count < 1: # Set the size of block block_size = [0.01, 0.05, 0.05] count += 1 # scene.add_box('block'+str(count), object_pose, block_size) # rospy.sleep(1) #right_arm.set_joint_value_target(target_pose, end_effector_link, True) right_arm.set_pose_target(target_pose) right_arm.go() rospy.sleep(2) # Create a pose for the block relative to the end-effector p = PoseStamped() p.header.frame_id = end_effector_link # Place the end of the object within the grasp of the gripper p.pose.position.x = -0.015 p.pose.position.y = 0.0 p.pose.position.z = 0.0 # Align the object with the gripper (straight out) p.pose.orientation.x = 0 p.pose.orientation.y = 0 p.pose.orientation.z = 0 p.pose.orientation.w = 1 # Attach the tool to the end-effector # scene.attach_box(end_effector_link, 'block'+str(count), p, block_size) rospy.sleep(1) right_arm.set_pose_target(place_pose) right_arm.go() rospy.sleep(5) scene.remove_attached_object(end_effector_link, 'block' + str(count)) rospy.sleep(2) # Return the arm to the named "resting" pose stored in the SRDF file right_arm.set_named_target('right') right_arm.go() rospy.sleep(1) # Cleanly shut down MoveIt moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
class MoveIt(object): def __init__(self): moveit_commander.roscpp_initialize(sys.argv) self.scene = PlanningSceneInterface() self.add_table() # self.clear_octomap = rospy.ServiceProxy("/clear_octomap", Empty) self.arm = MoveGroupCommander("arm") # self.arm.set_goal_joint_tolerance(0.1) self.gripper = MoveGroupCommander("gripper") # already default self.arm.set_planner_id("RRTConnectkConfigDefault") self.end_effector_link = self.arm.get_end_effector_link() self.arm.allow_replanning(True) self.arm.set_planning_time(5) self.transformer = tf.TransformListener() rospy.sleep(2) # allow some time for initialization of moveit def __del__(self): moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0) def _open_gripper(self): joint_trajectory = JointTrajectory() joint_trajectory.header.stamp = rospy.get_rostime() joint_trajectory.joint_names = [ "m1n6s200_joint_finger_1", "m1n6s200_joint_finger_2" ] joint_trajectory_point = JointTrajectoryPoint() joint_trajectory_point.positions = [0, 0] joint_trajectory_point.time_from_start = rospy.Duration(5.0) joint_trajectory.points.append(joint_trajectory_point) return joint_trajectory def _set_gripper_width(self, width): joint_trajectory = JointTrajectory() joint_trajectory.header.stamp = rospy.get_rostime() joint_trajectory.joint_names = [ "m1n6s200_joint_finger_1", "m1n6s200_joint_finger_2" ] joint_trajectory_point = JointTrajectoryPoint() joint_trajectory_point.positions = [0, 0] joint_trajectory_point.time_from_start = rospy.Duration(5.0) joint_trajectory.points.append(joint_trajectory_point) return joint_trajectory def _close_gripper(self): joint_trajectory = JointTrajectory() joint_trajectory.header.stamp = rospy.get_rostime() joint_trajectory.joint_names = [ "m1n6s200_joint_finger_1", "m1n6s200_joint_finger_2" ] joint_trajectory_point = JointTrajectoryPoint() joint_trajectory_point.positions = [1.2, 1.2] joint_trajectory_point.time_from_start = rospy.Duration(5.0) joint_trajectory.points.append(joint_trajectory_point) return joint_trajectory # Template function for creating the Grasps def _create_grasp(self, x, y, z, roll, pitch, yaw): grasp = Grasp() # pre_grasp grasp.pre_grasp_posture = self._open_gripper() grasp.pre_grasp_approach.direction.header.frame_id = self.end_effector_link grasp.pre_grasp_approach.direction.vector.z = 1.0 grasp.pre_grasp_approach.direction.vector.y = 0.0 grasp.pre_grasp_approach.direction.vector.x = 0.0 grasp.pre_grasp_approach.min_distance = 0.05 grasp.pre_grasp_approach.desired_distance = 0.1 # grasp grasp.grasp_posture = self._close_gripper() grasp.grasp_pose.pose.position.x = x grasp.grasp_pose.pose.position.y = y grasp.grasp_pose.pose.position.z = z q = quaternion_from_euler(roll, pitch, yaw) grasp.grasp_pose.pose.orientation.x = q[0] grasp.grasp_pose.pose.orientation.y = q[1] grasp.grasp_pose.pose.orientation.z = q[2] grasp.grasp_pose.pose.orientation.w = q[3] grasp.grasp_pose.header.frame_id = "m1n6s200_link_base" # post_grasp grasp.post_grasp_retreat.direction.header.frame_id = self.end_effector_link grasp.post_grasp_retreat.direction.vector.z = -1.0 grasp.post_grasp_retreat.direction.vector.x = 0.0 grasp.post_grasp_retreat.direction.vector.y = 0.0 grasp.post_grasp_retreat.min_distance = 0.05 grasp.post_grasp_retreat.desired_distance = 0.25 return [grasp] # Template function, you can add parameters if needed! def grasp(self, x, y, z, roll, pitch, yaw, width): self.add_object('object', [0.37, -0.24, 0.1, math.pi, 0., 0.], [0.1, 0.1, 0.1]) grasps = self._create_grasp(x, y, z, roll, pitch, yaw) result = self.arm.pick('object', grasps) self.remove_object() if result == MoveItErrorCodes.SUCCESS: print 'Success grasp' return True else: print 'Failed grasp' return False def open_fingers(self): self.gripper.set_joint_value_target([0.0, 0.0]) self.gripper.go(wait=True) rospy.sleep(2.0) def close_fingers(self): self.gripper.set_joint_value_target([1.3, 1.3]) self.gripper.go(wait=True) rospy.sleep(2.0) def move_to(self, x, y, z, roll, pitch, yaw, frame_id="m1n6s200_link_base"): q = quaternion_from_euler(roll, pitch, yaw) pose = PoseStamped() pose.header.frame_id = frame_id pose.pose.position.x = x pose.pose.position.y = y pose.pose.position.z = z pose.pose.orientation.x = q[0] pose.pose.orientation.y = q[1] pose.pose.orientation.z = q[2] pose.pose.orientation.w = q[3] self.arm.set_pose_target(pose, self.end_effector_link) plan = self.arm.plan() success = True success = self.arm.go(wait=True) self.arm.stop() self.arm.clear_pose_targets() return success def remove_object(self, object='object'): self.scene.remove_attached_object(self.end_effector_link, object) self.scene.remove_world_object(object) rospy.loginfo("Object removed") def add_object(self, name, pose, size): object_pose = PoseStamped() object_pose.header.frame_id = "m1n6s200_link_base" object_pose.pose.position.x = pose[0] object_pose.pose.position.y = pose[1] object_pose.pose.position.z = pose[2] q = quaternion_from_euler(*pose[3:]) object_pose.pose.orientation.x = q[0] object_pose.pose.orientation.y = q[1] object_pose.pose.orientation.z = q[2] object_pose.pose.orientation.w = q[3] self.scene.add_box(name, object_pose, size) def add_table(self): self.add_object('table', [0, 0, -0.005, 0, 0, 0], (2, 2, 0.01))
class MoveItDemo: def __init__(self): global obj_att # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') #Initialize robot robot = moveit_commander.RobotCommander() # Use the planning scene object to add or remove objects self.scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # Create a publisher for displaying object frames self.object_frames_pub = rospy.Publisher('object_frames', PoseStamped, queue_size=10) ### Create a publisher for visualizing direction ### self.p_pub = rospy.Publisher('target', PoseStamped, latch=True, queue_size = 10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the MoveIt! commander for the arm self.right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the MoveIt! commander for the gripper self.right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Allow 5 seconds per planning attempt self.right_arm.set_planning_time(5) # Prepare Action Controller for gripper self.ac = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',pr2c.Pr2GripperCommandAction) self.ac.wait_for_server() # Give the scene a chance to catch up rospy.sleep(2) # Prepare Gazebo Subscriber self.pwh = None self.pwh_copy = None self.idx_targ = None self.gazebo_subscriber = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) ### OPEN THE GRIPPER ### self.open_gripper() # PREPARE THE SCENE while self.pwh is None: rospy.sleep(0.05) ############## CLEAR THE SCENE ################ # planning_scene.world.collision_objects.remove('target') # Remove leftover objects from a previous run self.scene.remove_world_object('target') self.scene.remove_world_object('table') # self.scene.remove_world_object(obstacle1_id) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, 'target') # Run and keep in the BG the scene generator also add the ability to kill the code with ctrl^c timerThread = threading.Thread(target=self.scene_generator) timerThread.daemon = True timerThread.start() initial_pose = PoseStamped() initial_pose.header.frame_id = 'gazebo_world' initial_pose.pose = target_pose.pose print "==================== Generating Transformations ===========================" #################### PRE GRASPING POSE ######################### M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 1.57, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y M2[2,3] = 0.25 # about z T = np.dot(M1, M2) pre_grasping = deepcopy(target_pose) pre_grasping.pose.position.x = T[0,3] pre_grasping.pose.position.y = T[1,3] pre_grasping.pose.position.z = T[2,3] quat = transformations.quaternion_from_matrix(T) pre_grasping.pose.orientation.x = quat[0] pre_grasping.pose.orientation.y = quat[1] pre_grasping.pose.orientation.z = quat[2] pre_grasping.pose.orientation.w = quat[3] pre_grasping.header.frame_id = 'gazebo_world' self.plan_exec(pre_grasping) #################### GRASPING POSE ######################### M3 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M3[0,3] = target_pose.pose.position.x M3[1,3] = target_pose.pose.position.y M3[2,3] = target_pose.pose.position.z M4 = transformations.euler_matrix(0, 1.57, 0) M4[0,3] = 0.0 # offset about x M4[1,3] = 0.0 # about y M4[2,3] = 0.18 # about z T2 = np.dot(M3, M4) grasping = deepcopy(target_pose) grasping.pose.position.x = T2[0,3] grasping.pose.position.y = T2[1,3] grasping.pose.position.z = T2[2,3] quat2 = transformations.quaternion_from_matrix(T2) grasping.pose.orientation.x = quat2[0] grasping.pose.orientation.y = quat2[1] grasping.pose.orientation.z = quat2[2] grasping.pose.orientation.w = quat2[3] grasping.header.frame_id = 'gazebo_world' self.plan_exec(grasping) #Close the gripper print "========== Waiting for gazebo to catch up ==========" self.close_gripper() #################### ATTACH OBJECT ###################### touch_links = [GRIPPER_FRAME, 'r_gripper_l_finger_tip_link','r_gripper_r_finger_tip_link', 'r_gripper_r_finger_link', 'r_gripper_l_finger_link'] #print touch_links self.scene.attach_box(GRIPPER_FRAME, target_id, target_pose, target_size, touch_links) # counter to let the planning scene know when to remove the object obj_att = 1 #self.scene.remove_world_object(target_id) #################### POST-GRASP RETREAT ######################### M5 = transformations.quaternion_matrix([initial_pose.pose.orientation.x, initial_pose.pose.orientation.y, initial_pose.pose.orientation.z, initial_pose.pose.orientation.w]) M5[0,3] = initial_pose.pose.position.x M5[1,3] = initial_pose.pose.position.y M5[2,3] = initial_pose.pose.position.z M6 = transformations.euler_matrix(0, 1.57, 0) M6[0,3] = 0.0 # offset about x M6[1,3] = 0.0 # about y M6[2,3] = 0.3 # about z T3 = np.dot(M5, M6) post_grasping = deepcopy(initial_pose) post_grasping.pose.position.x = T3[0,3] post_grasping.pose.position.y = T3[1,3] post_grasping.pose.position.z = T3[2,3] quat3 = transformations.quaternion_from_matrix(T3) post_grasping.pose.orientation.x = quat3[0] post_grasping.pose.orientation.y = quat3[1] post_grasping.pose.orientation.z = quat3[2] post_grasping.pose.orientation.w = quat3[3] post_grasping.header.frame_id = 'gazebo_world' self.plan_exec(post_grasping) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.52 place_pose.pose.position.y = -0.48 place_pose.pose.position.z = 0.48 place_pose.pose.orientation.w = 1.0 n_attempts = 0 max_place_attempts = 2 # Generate valid place poses places = self.make_places(place_pose) success = False # Repeat until we succeed or run out of attempts while success == False and n_attempts < max_place_attempts: for place in places: success = self.right_arm.place(target_id, place) if success: break n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) rospy.sleep(0.2) self.open_gripper() obj_att = None rospy.sleep(3) ## # Initialize the grasp object ## g = Grasp() ## grasps = [] ## # Set the first grasp pose to the input pose ## g.grasp_pose = pre_grasping ## g.allowed_touch_objects = [target_id] ## grasps.append(deepcopy(g)) ## right_arm.pick(target_id, grasps) # #Change the frame_id for the planning to take place! # #target_pose.header.frame_id = 'gazebo_world' # # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # # Exit the script moveit_commander.os._exit(0) ################################################################################################################## #Get pose from Gazebo def model_state_callback(self,msg): self.pwh = ModelStates() self.pwh = msg # Generate a list of possible place poses def make_places(self, init_pose): # Initialize the place location as a PoseStamped message place = PoseStamped() # Start with the input place pose place = init_pose # A list of x shifts (meters) to try x_vals = [0, 0.005, 0.01, 0.015, -0.005, -0.01, -0.015] # A list of y shifts (meters) to try y_vals = [0, 0.005, 0.01, 0.015, -0.005, -0.01, -0.015] # A list of pitch angles to try #pitch_vals = [0, 0.005, -0.005, 0.01, -0.01, 0.02, -0.02] pitch_vals = [0] # A list of yaw angles to try yaw_vals = [0] # A list to hold the places places = [] # Generate a place pose for each angle and translation for y in yaw_vals: for p in pitch_vals: for y in y_vals: for x in x_vals: place.pose.position.x = init_pose.pose.position.x + x place.pose.position.y = init_pose.pose.position.y + y # Create a quaternion from the Euler angles q = quaternion_from_euler(0, p, y) # Set the place pose orientation accordingly place.pose.orientation.x = q[0] place.pose.orientation.y = q[1] place.pose.orientation.z = q[2] place.pose.orientation.w = q[3] # Append this place pose to the list places.append(deepcopy(place)) # Return the list return places def plan_exec(self, pose): self.right_arm.clear_pose_targets() self.right_arm.set_pose_target(pose, GRIPPER_FRAME) self.right_arm.plan() rospy.sleep(5) self.right_arm.go(wait=True) def close_gripper(self): g_close = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.035, 100)) self.ac.send_goal(g_close) self.ac.wait_for_result() rospy.sleep(15) # Gazebo requires up to 15 seconds to attach object def open_gripper(self): g_open = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.088, 100)) self.ac.send_goal(g_open) self.ac.wait_for_result() rospy.sleep(5) # And up to 20 to detach it def scene_generator(self): # print obj_att global target_pose global target_id global target_size target_id = 'target' self.taid = self.pwh.name.index('wood_cube_5cm') table_id = 'table' self.tid = self.pwh.name.index('table') #obstacle1_id = 'obstacle1' #self.o1id = self.pwh.name.index('wood_block_10_2_1cm') # Set the target size [l, w, h] target_size = [0.05, 0.05, 0.05] table_size = [1.5, 0.8, 0.03] #obstacle1_size = [0.1, 0.025, 0.01] ## Set the target pose on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose = self.pwh.pose[self.taid] target_pose.pose.position.z += 0.025 # Add the target object to the scene if obj_att is None: self.scene.add_box(target_id, target_pose, target_size) table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose = self.pwh.pose[self.tid] table_pose.pose.position.z += 1 self.scene.add_box(table_id, table_pose, table_size) #obstacle1_pose = PoseStamped() #obstacle1_pose.header.frame_id = REFERENCE_FRAME #obstacle1_pose.pose = self.pwh.pose[self.o1id] ## Add the target object to the scene #scene.add_box(obstacle1_id, obstacle1_pose, obstacle1_size) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.50 place_pose.pose.position.y = -0.30 place_pose.pose.orientation.w = 1.0 # Add the target object to the scene self.scene.add_box(target_id, target_pose, target_size) ### Make the target purple ### self.setColor(target_id, 0.6, 0, 1, 1.0) # Send the colors to the planning scene self.sendColors() else: self.scene.remove_world_object('target') # Publish targe's frame #self.object_frames_pub.publish(target_pose) threading.Timer(0.5, self.scene_generator).start() # Set the color of an object def setColor(self, name, r, g, b, a = 0.9): # Initialize a MoveIt color object color = ObjectColor() # Set the id to the name given as an argument color.id = name # Set the rgb and alpha values given as input color.color.r = r color.color.g = g color.color.b = b color.color.a = a # Update the global color dictionary self.colors[name] = color # Actually send the colors to MoveIt! def sendColors(self): # Initialize a planning scene object p = PlanningScene() # Need to publish a planning scene diff p.is_diff = True # Append the colors from the global color dictionary for color in self.colors.values(): p.object_colors.append(color) # Publish the scene diff self.scene_pub.publish(p)
class MoveIt(object): def __init__(self): moveit_commander.roscpp_initialize(sys.argv) self.scene = PlanningSceneInterface() self.clear_octomap = rospy.ServiceProxy("/clear_octomap", Empty) self.arm = MoveGroupCommander("arm") # self.arm.set_goal_joint_tolerance(0.1) self.gripper = MoveGroupCommander("gripper") # already default self.arm.set_planner_id("RRTConnectkConfigDefault") self.end_effector_link = self.arm.get_end_effector_link() self.arm.allow_replanning(True) self.arm.set_planning_time(5) self.transformer = tf.TransformListener() rospy.sleep(2) # allow some time for initialization of moveit def __del__(self): moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0) def _open_gripper(self): joint_trajectory = JointTrajectory() joint_trajectory.header.stamp = rospy.get_rostime() joint_trajectory.joint_names = [ "m1n6s200_joint_finger_1", "m1n6s200_joint_finger_2" ] joint_trajectory_point = JointTrajectoryPoint() joint_trajectory_point.positions = [0, 0] joint_trajectory_point.time_from_start = rospy.Duration(5.0) joint_trajectory.points.append(joint_trajectory_point) return joint_trajectory def _close_gripper(self): joint_trajectory = JointTrajectory() joint_trajectory.header.stamp = rospy.get_rostime() joint_trajectory.joint_names = [ "m1n6s200_joint_finger_1", "m1n6s200_joint_finger_2" ] joint_trajectory_point = JointTrajectoryPoint() joint_trajectory_point.positions = [1.2, 1.2] joint_trajectory_point.time_from_start = rospy.Duration(5.0) joint_trajectory.points.append(joint_trajectory_point) return joint_trajectory # Template function for creating the Grasps def _create_grasps(self, x, y, z, z_max, rotation): grasps = [] # You can create multiple grasps and add them to the grasps list grasp = Grasp() # create a new grasp # Set the pre grasp posture (the fingers) grasp.pre_grasp_posture = self._open_gripper() # Set the grasp posture (the fingers) grasp.grasp_posture = self._close_gripper() # Set the position of where to grasp grasp.grasp_pose.pose.position.x = x grasp.grasp_pose.pose.position.y = y grasp.grasp_pose.pose.position.z = z # Set the orientation of the end effector q = quaternion_from_euler(math.pi, 0.0, rotation) grasp.grasp_pose.pose.orientation.x = q[0] grasp.grasp_pose.pose.orientation.y = q[1] grasp.grasp_pose.pose.orientation.z = q[2] grasp.grasp_pose.pose.orientation.w = q[3] grasp.grasp_pose.header.frame_id = "m1n6s200_link_base" # Set the pre_grasp_approach grasp.pre_grasp_approach.direction.header.frame_id = self.end_effector_link grasp.pre_grasp_approach.direction.vector.z = 1.0 grasp.pre_grasp_approach.direction.vector.y = 0.0 grasp.pre_grasp_approach.direction.vector.x = 0.0 grasp.pre_grasp_approach.min_distance = 0.05 grasp.pre_grasp_approach.desired_distance = 0.1 # # Set the post_grasp_approach grasp.post_grasp_retreat.direction.header.frame_id = self.end_effector_link grasp.post_grasp_retreat.direction.vector.z = -1.0 grasp.post_grasp_retreat.direction.vector.x = 0.0 grasp.post_grasp_retreat.direction.vector.y = 0.0 grasp.post_grasp_retreat.min_distance = 0.05 grasp.post_grasp_retreat.desired_distance = 0.25 grasp.grasp_pose.header.frame_id = "m1n6s200_link_base" # setting the planning frame (Positive x is to the left, negative Y is to the front of the arm) grasps.append( grasp ) # add all your grasps in the grasps list, MoveIT will pick the best one for z_offset in np.arange(z + 0.02, z_max, 0.01): new_grasp = copy.deepcopy(grasp) new_grasp.grasp_pose.pose.position.z = z_offset grasps.append(new_grasp) return grasps # Template function, you can add parameters if needed! def grasp(self, x, y, z, z_max, rotation, size): print '******************* grasp' # Object distance: obj_dist = np.linalg.norm(np.asarray((x, y, z))) if obj_dist > 0.5: rospy.loginfo( "Object too far appart ({} m), skipping pick".format(obj_dist)) return False # Add collision object, easiest to name the object, "object" object_pose = PoseStamped() object_pose.header.frame_id = "m1n6s200_link_base" object_pose.pose.position.x = x object_pose.pose.position.y = y object_pose.pose.position.z = z q = quaternion_from_euler(math.pi, 0.0, rotation) object_pose.pose.orientation.x = q[0] object_pose.pose.orientation.y = q[1] object_pose.pose.orientation.z = q[2] object_pose.pose.orientation.w = q[3] self.scene.add_box("object", object_pose, size) rospy.sleep(0.5) self.clear_octomap() rospy.sleep(1.0) # Create and return grasps # z += size[2]/2 # Focus on the top of the object only # z += size[2]/2 + 0.02 # Focus on the top of the object only grasps = self._create_grasps(x, y, z, z_max, rotation) print '******************************************************************************' result = self.arm.pick( 'object', grasps) # Perform pick on "object", returns result print '******************************************************************************' # self.move_to(x, y, z + 0.15, rotation) if result == MoveItErrorCodes.SUCCESS: print 'Success grasp' return True else: print 'Failed grasp' return False def clear_object(self, x, y, z, z_max, rotation, size): print '******************* clear_object' self.move_to_waypoint() success = self.grasp(x, y, z, z_max, rotation, size) if success: self.move_to_waypoint() success = self.move_to_drop_zone() if success: print 'success move to drop zone' else: print 'failed move to drop zone' self.open_fingers() self.remove_object() rospy.sleep(1.0) self.close_fingers() return success def open_fingers(self): print '******************* open_fingers' self.gripper.set_joint_value_target([0.0, 0.0]) self.gripper.go(wait=True) rospy.sleep(2.0) def close_fingers(self): print '******************* close_fingers' self.gripper.set_joint_value_target([1.3, 1.3]) self.gripper.go(wait=True) rospy.sleep(2.0) def move_to(self, x, y, z, rotation, frame_id="m1n6s200_link_base"): print '******************* move_to' q = quaternion_from_euler(math.pi, 0.0, rotation) pose = PoseStamped() pose.header.frame_id = frame_id pose.pose.position.x = x pose.pose.position.y = y pose.pose.position.z = z pose.pose.orientation.x = q[0] pose.pose.orientation.y = q[1] pose.pose.orientation.z = q[2] pose.pose.orientation.w = q[3] self.arm.set_pose_target(pose, self.end_effector_link) plan = self.arm.plan() success = self.arm.go(wait=True) self.arm.stop() self.arm.clear_pose_targets() return success def move_to_waypoint(self): print '******************* move_to_waypoint' return self.move_to(0.35, 0, 0.25, 1.57) def rtb(self): print '******************* rtb' self.move_to_drop_zone() # pose = PoseStamped() # pose.header.frame_id = 'base_footprint' # pose.pose.position.x = -0.191258927921 # pose.pose.position.y = 0.1849306168113 # pose.pose.position.z = 0.813729734732 # pose.pose.orientation.x = -0.934842026356 # pose.pose.orientation.y = 0.350652799078 # pose.pose.orientation.z = -0.00168532388516 # pose.pose.orientation.w = 0.0557688079539 # # self.arm.set_pose_target(pose, self.end_effector_link) # plan = self.arm.plan() # self.arm.go(wait=True) # self.arm.stop() # self.arm.clear_pose_targets() def move_to_drop_zone(self): print '******************* move_to_drop_zone' pose = PoseStamped() pose.header.frame_id = "m1n6s200_link_base" pose.pose.position.x = 0.2175546259709541 pose.pose.position.y = 0.18347985269448372 pose.pose.position.z = 0.16757751444136426 pose.pose.orientation.x = 0.6934210704552356 pose.pose.orientation.y = 0.6589390059796749 pose.pose.orientation.z = -0.23223137602833943 pose.pose.orientation.w = -0.17616808290725341 self.arm.set_pose_target(pose, self.end_effector_link) plan = self.arm.plan() success = self.arm.go(wait=True) self.arm.stop() self.arm.clear_pose_targets() return success def print_position(self): pose = self.arm.get_current_pose() self.transformer.waitForTransform("m1n6s200_link_base", "base_footprint", rospy.Time.now(), rospy.Duration(10)) eef_pose = self.transformer.transformPose("m1n6s200_link_base", pose) orientation = eef_pose.pose.orientation orientation = [ orientation.x, orientation.y, orientation.z, orientation.w ] euler = euler_from_quaternion(orientation) print "z:", eef_pose.pose.position.x print "y:", eef_pose.pose.position.y print "z:", eef_pose.pose.position.z print "yaw (degrees):", math.degrees(euler[2]) def remove_object(self): self.scene.remove_attached_object(self.end_effector_link, "object") self.scene.remove_world_object("object") rospy.loginfo("Object removed")
def __init__(self): roscpp_initialize(sys.argv) rospy.init_node('moveit_py_demo', anonymous=True) scene = PlanningSceneInterface() robot = RobotCommander() right_arm = MoveGroupCommander("right_arm") right_gripper = MoveGroupCommander("right_gripper") eef = right_arm.get_end_effector_link() rospy.sleep(2) scene.remove_attached_object("right_gripper_link", "part") # clean the scene scene.remove_world_object("table") scene.remove_world_object("part") right_arm.set_named_target("start1") right_arm.go() right_gripper.set_named_target("open") right_gripper.go() rospy.sleep(1) # publish a demo scene p = PoseStamped() p.header.frame_id = robot.get_planning_frame() # add a table #p.pose.position.x = 0.42 #p.pose.position.y = -0.2 #p.pose.position.z = 0.3 #scene.add_box("table", p, (0.5, 1.5, 0.6)) # add an object to be grasped p.pose.position.x = 0.15 p.pose.position.y = -0.12 p.pose.position.z = 0.7 scene.add_box("part", p, (0.07, 0.01, 0.2)) rospy.sleep(1) g = Grasp() g.id = "test" start_pose = PoseStamped() start_pose.header.frame_id = FIXED_FRAME # start the gripper in a neutral pose part way to the target start_pose.pose.position.x = 0.0130178 start_pose.pose.position.y = -0.125155 start_pose.pose.position.z = 0.597653 start_pose.pose.orientation.x = 0.0 start_pose.pose.orientation.y = 0.388109 start_pose.pose.orientation.z = 0.0 start_pose.pose.orientation.w = 0.921613 right_arm.set_pose_target(start_pose) right_arm.go() rospy.sleep(2) # generate a list of grasps #grasps = self.make_grasps(start_pose) #result = False #n_attempts = 0 # repeat until will succeed #while result == False: #result = robot.right_arm.pick("part", grasps) #n_attempts += 1 #print "Attempts: ", n_attempts #rospy.sleep(0.2) rospy.spin() roscpp_shutdown()
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') self.gripper_opened = [rospy.get_param(GRIPPER_PARAM + "/max_opening")] self.gripper_closed = [rospy.get_param(GRIPPER_PARAM + "/min_opening")] self.gripper_neutral = [rospy.get_param(GRIPPER_PARAM + "/neutral")] self.gripper_tighten = rospy.get_param(GRIPPER_PARAM + "/tighten") # We need a tf listener to convert poses into arm reference base self.tf_listener = tf.TransformListener() # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('target_pose', PoseStamped, queue_size=10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the right arm arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the move group for the right gripper gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) arm.set_goal_position_tolerance(0.04) arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution arm.allow_replanning(True) # Set the right arm reference frame arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt arm.set_planning_time(5) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 3 # Set a limit on the number of place attempts max_place_attempts = 3 rospy.loginfo("Scaling for MoveIt timeout=" + str( rospy.get_param( '/move_group/trajectory_execution/allowed_execution_duration_scaling' ))) # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name #table_id = 'table' We also remove the table object in order to run a test #box1_id = 'box1' These boxes are commented as we do not need them #box2_id = 'box2' target_id = 'target' tool_id = 'tool' # Remove leftover objects from a previous run #scene.remove_world_object(table_id) #scene.remove_world_object(box1_id) These boxes are commented as we do not need them #scene.remove_world_object(box2_id) scene.remove_world_object(target_id) scene.remove_world_object(tool_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "arm_up" pose stored in the SRDF file rospy.loginfo("Set Arm: right_up") arm.set_named_target('right_up') if arm.go() != True: rospy.logwarn(" Go failed") rospy.sleep(2) # Move the gripper to the closed position rospy.loginfo("Set Gripper: Close " + str(self.gripper_closed)) gripper.set_joint_value_target(self.gripper_closed) if gripper.go() != True: rospy.logwarn(" Go failed") rospy.sleep(2) # Move the gripper to the neutral position rospy.loginfo("Set Gripper: Neutral " + str(self.gripper_neutral)) gripper.set_joint_value_target(self.gripper_neutral) if gripper.go() != True: rospy.logwarn(" Go failed") rospy.sleep(2) # Move the gripper to the open position rospy.loginfo("Set Gripper: Open " + str(self.gripper_opened)) gripper.set_joint_value_target(self.gripper_opened) if gripper.go() != True: rospy.logwarn(" Go failed") rospy.sleep(2) # Set the height of the table off the ground #table_ground = 0.4 # Set the dimensions of the scene objects [l, w, h] #table_size = [0.2, 0.7, 0.01] #box1_size = [0.1, 0.05, 0.05] commented for the same reasons as previously #box2_size = [0.05, 0.05, 0.15] # Set the target size [l, w, h] target_size = [ 0.018, 0.018, 0.018 ] #[0.02, 0.005, 0.12] original object dimensions in meters # Add a table top and two boxes to the scene #table_pose = PoseStamped() #table_pose.header.frame_id = REFERENCE_FRAME #table_pose.pose.position.x = 0.36 #table_pose.pose.position.y = 0.0 #table_pose.pose.position.z = table_ground + table_size[2] -0.08 / 2.0 #0.4+0.01/2 aka table_ground + table_size[2] + target_size[2] / 2.0 #table_pose.pose.orientation.w = 1.0 #scene.add_box(table_id, table_pose, table_size) #box1_pose = PoseStamped() These two blocks of code are commented as they assign postion to unwanted boxes #box1_pose.header.frame_id = REFERENCE_FRAME #box1_pose.pose.position.x = table_pose.pose.position.x - 0.04 #box1_pose.pose.position.y = 0.0 #box1_pose.pose.position.z = table_ground + table_size[2] + box1_size[2] / 2.0 #box1_pose.pose.orientation.w = 1.0 #scene.add_box(box1_id, box1_pose, box1_size) #box2_pose = PoseStamped() #box2_pose.header.frame_id = REFERENCE_FRAME #box2_pose.pose.position.x = table_pose.pose.position.x - 0.06 #box2_pose.pose.position.y = 0.2 #box2_pose.pose.position.z = table_ground + table_size[2] + box2_size[2] / 2.0 #box2_pose.pose.orientation.w = 1.0 #scene.add_box(box2_id, box2_pose, box2_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = -0.03 #table_pose.pose.position.x - 0.03 target_pose.pose.position.y = 0.1 target_pose.pose.position.z = 0.4 + 0.01 + 0.018 - 0.08 / 2 #table_ground + table_size[2] + target_size[2] / 2.0 table_ground + table_size[2] + target_size[2] -0.08 / 2.0 target_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) # Make the table red and the boxes orange #self.setColor(table_id, 0.8, 0, 0, 1.0) #self.setColor(box1_id, 0.8, 0.4, 0, 1.0) #self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object #arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = -0.03 #table_pose.pose.position.x - 0.03 place_pose.pose.position.y = -0.15 place_pose.pose.position.z = 0.4 + 0.01 + 0.018 - 0.08 / 2 #table_ground + table_size[2] + target_size[2] -0.08 / 2.0 0.4+0.01+0.018/2 aka table_ground + table_size[2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 # Initialize the grasp pose to the target pose grasp_pose = target_pose # Shift the grasp pose by half the width of the target to center it grasp_pose.pose.position.y -= target_size[1] / 2.0 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id], [target_size[1] - self.gripper_tighten]) # Track success/failure and number of attempts for pick operation result = MoveItErrorCodes.FAILURE n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: rospy.loginfo("Pick attempt #" + str(n_attempts)) for grasp in grasps: # Publish the grasp poses so they can be viewed in RViz self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) result = arm.pick(target_id, grasps) if result == MoveItErrorCodes.SUCCESS: break n_attempts += 1 rospy.sleep(0.2) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: rospy.loginfo(" Pick: Done!") # Generate valid place poses places = self.make_places(place_pose) success = False #from here we are forcing the success cases by stting and making it always true it makes an error appear and the arm stays to the middle position n_attempts = 0 # Repeat until we succeed or run out of attempts while not success and n_attempts < max_place_attempts: #while not has been removed added = after operator < rospy.loginfo("Place attempt #" + str(n_attempts)) for place in places: # Publish the place poses so they can be viewed in RViz self.gripper_pose_pub.publish(place) rospy.sleep(0.2) success = arm.place(target_id, place) break if success: break n_attempts += 1 rospy.sleep(0.2) if not success: rospy.logerr("Place operation failed after " + str(n_attempts) + " attempts.") else: #end of forcing rospy.loginfo(" Place: Done!") else: rospy.logerr("Pick operation failed after " + str(n_attempts) + " attempts.") # Return the arm to the "resting" pose stored in the SRDF file (passing through right_up) arm.set_named_target('right_up') arm.go() arm.set_named_target('resting') arm.go() # Open the gripper to the neutral position gripper.set_joint_value_target(self.gripper_neutral) gripper.go() rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
class MoveItDemo: def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') #Initialize robot robot = moveit_commander.RobotCommander() # Use the planning scene object to add or remove objects self.scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # Create a publisher for displaying object frames self.object_frames_pub = rospy.Publisher('object_frames', PoseStamped, queue_size=10) ### Create a publisher for visualizing direction ### self.p_pub = rospy.Publisher('target', PoseStamped, latch=True, queue_size = 10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the MoveIt! commander for the arm self.right_arm = MoveGroupCommander(GROUP_NAME_ARM) self.left_arm = MoveGroupCommander('left_arm') # Initialize the MoveIt! commander for the gripper self.right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) self.left_gripper = MoveGroupCommander('left_gripper') # eel = len(self.right_arm.get_end_effector_link()) # print eel # Allow 5 seconds per planning attempt # self.right_arm.set_planning_time(5) # Prepare Action Controller for gripper self.ac = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',pr2c.Pr2GripperCommandAction) self.ac.wait_for_server() # Give the scene a chance to catch up rospy.sleep(2) # Prepare Gazebo Subscriber self.pwh = None self.pwh_copy = None self.idx_targ = None self.gazebo_subscriber = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) ### OPEN THE GRIPPER ### self.open_gripper() # PREPARE THE SCENE while self.pwh is None: rospy.sleep(0.05) ### Attach / Remove Object Flag ### self.aro = None # Run and keep in the BG the scene generator with ctrl^c kill ### timerThread = threading.Thread(target=self.scene_generator) timerThread.daemon = True timerThread.start() ## Give some time to ensure the thread starts!! ## rospy.sleep(5) ### GENERATE THE BLACKLIST AND REMOVE ATTACHED OBJECTS FROM PREVIOUS RUNS ### self.idx_list = self.bl() ### GIVE SCENE TIME TO CATCH UP ### rospy.sleep(5) ################################## GRASP EXECUTION ##################################### print "==================== Executing ===========================" start_time = time.time() ### PERSONAL REMINDER!!! WHAT IS WHAT!!! ### # print obj_id[obj_id.index('target')] # print obj_id.index('target') ### MOVE LEFT ARM OUT OF THE WAY ### self.lasp() success = False while success == False and len(self.idx_list)>0: success, pgr_target = self.grasp_attempt() print ("GA Returns:", success) if success is not False: self.flag = 0 # To let the planning scene know when to remove the object self.post_grasp(pgr_target, obj_id.index('target'),'true') self.place_object(obj_id.index('target')) break else: idx = self.idx_list[0] ds, pgr_col_obj = self.declutter_scene(idx) print ("DS Returns:", ds) if ds == True: self.flag = 0 # To let the planning scene know when to remove the object self.post_grasp(pgr_col_obj, obj_id.index(obj_id[idx]),'true') self.place_object(obj_id.index(obj_id[idx])) self.idx_list.pop(0) print "==================== THE END! ======================" print("--- %s seconds ---" % (time.time() - start_time)) rospy.sleep(5) # # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # # Exit the script moveit_commander.os._exit(0) ################################################################# FUNCTIONS ################################################################################# def grasp_attempt(self): # start_time = time.time() retreat = None init_poses = [] grasp_poses = [] for axis in range(0,6): # while obj_id[obj_id.index('target')] is not 'target': # print '!!!!!' # rospy.sleep(0.05) pg = self.grasp_pose(obj_pose[obj_id.index('target')], axis, 'pg') gp = self.grasp_pose(obj_pose[obj_id.index('target')], axis, 'gp') init_poses.append(pg) grasp_poses.append(gp) pre_grasps = self.grasp_generator(init_poses) grasps = self.grasp_generator(grasp_poses) for grasp in grasps: self.gripper_pose_pub.publish(grasp) rospy.sleep(0.05) success = False i = 1 for pg, gr in izip(pre_grasps, grasps): self.gripper_pose_pub.publish(gr) print ("G Attempt: ", i) plp = self.right_arm.plan(pg.pose) if len(plp.joint_trajectory.points) == 0: print "No valid pregrasp Position, continuing on next one" i+=1 continue i+=1 self.right_arm.plan(pg.pose) self.right_arm.go(wait=True) rospy.sleep(5) plg = self.right_arm.plan(gr.pose) if len(plg.joint_trajectory.points) >= 10: self.right_arm.go() success = True retreat = gr print "Grasping" break # print("--- %s seconds ---" % (time.time() - start_time)) return success , retreat def declutter_scene(self,index): retreat = None init_poses = [] grasp_poses = [] for axis in range(0,6): pg = self.grasp_pose(obj_pose[index], axis, 'pg') gp = self.grasp_pose(obj_pose[index], axis, 'gp') init_poses.append(pg) grasp_poses.append(gp) pre_grasps = self.grasp_generator(init_poses) grasps = self.grasp_generator(grasp_poses) for grasp in grasps: self.gripper_pose_pub.publish(grasp) rospy.sleep(0.05) success = False i= 1 for pg, gr in izip(pre_grasps, grasps): plp = self.right_arm.plan(pg.pose) print (" DS Attempt: ", i) self.gripper_pose_pub.publish(gr) self.right_arm.plan(pg.pose) if len(plp.joint_trajectory.points) == 0: print "No valid pregrasp Position, continuing on next one" i+=1 continue i+=1 self.right_arm.plan(pg.pose) self.right_arm.go() rospy.sleep(5) plg = self.right_arm.plan(gr.pose) if len(plg.joint_trajectory.points) >= 10: self.right_arm.go() print "Grasping" success = True retreat = gr break return success, retreat def place_object(self, obj_idx): self.aro = obj_idx ### GENERATE PLACE POSES ### places = self.place_generator() ### TRY THESE POSES ### i = 1 for place in places: print (" Place Attempt: ", i) plpl = self.right_arm.plan(place.pose) print len(plpl.joint_trajectory.points) if len(plpl.joint_trajectory.points) == 0: i+=1 continue self.right_arm.plan(plpl) self.right_arm.go(wait=True) ### INFORM SCENE ### # self.open_gripper() # self.aro = None ### RETURN HAND TO STARTING POSITION ### self.post_grasp(place,obj_idx, 'false') self.rasp() break def post_grasp(self,new_pose, obj_idx, fl): ######### GRASP OBJECT/ REMOVE FROM SCENE ######. if fl == 'true': self.close_gripper() self.aro = obj_idx else: self.open_gripper() self.aro = None rospy.sleep(2) ### POST GRASP RETREAT ### M1 = transformations.quaternion_matrix([new_pose.pose.orientation.x, new_pose.pose.orientation.y, new_pose.pose.orientation.z, new_pose.pose.orientation.w]) M1[0,3] = new_pose.pose.position.x M1[1,3] = new_pose.pose.position.y M1[2,3] = new_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y M2[2,3] = 0.25 # about z T1 = np.dot(M2, M1) npo = deepcopy(new_pose) npo.pose.position.x = T1[0,3] npo.pose.position.y = T1[1,3] npo.pose.position.z = T1[2,3] quat = transformations.quaternion_from_matrix(T1) npo.pose.orientation.x = quat[0] npo.pose.orientation.y = quat[1] npo.pose.orientation.z = quat[2] npo.pose.orientation.w = quat[3] npo.header.frame_id = REFERENCE_FRAME self.right_arm.plan(npo.pose) self.right_arm.go(wait=True) def place_generator(self): place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.57 place_pose.pose.position.y = 0.16 place_pose.pose.position.z = 0.56 place_pose.pose.orientation.w = 1.0 P = transformations.quaternion_matrix([place_pose.pose.orientation.x, place_pose.pose.orientation.y, place_pose.pose.orientation.z, place_pose.pose.orientation.w]) P[0,3] = place_pose.pose.position.x P[1,3] = place_pose.pose.position.y P[2,3] = place_pose.pose.position.z places =[] yaw_angles = [0, 1,57, -1,57 , 3,14] x_vals = [0, 0.05 ,0.1 , 0.15] z_vals = [0.05 ,0.1 , 0.15] for y in yaw_angles: G = transformations.euler_matrix(0, 0, y) G[0,3] = 0.0 # offset about x G[1,3] = 0.0 # about y G[2,3] = 0.0 # about z for z in z_vals: for x in x_vals: TM = np.dot(P, G) pl = deepcopy(place_pose) pl.pose.position.x = TM[0,3] +x pl.pose.position.y = TM[1,3] pl.pose.position.z = TM[2,3] +z quat = transformations.quaternion_from_matrix(TM) pl.pose.orientation.x = quat[0] pl.pose.orientation.y = quat[1] pl.pose.orientation.z = quat[2] pl.pose.orientation.w = quat[3] pl.header.frame_id = REFERENCE_FRAME places.append(deepcopy(pl)) return places def grasp_pose(self, target_pose, axis, stage): ############ TODO : GENERATE AUTOMATED PRE-GRASPING POSITIONS BASED ON THE PRIMITIVE ######### if axis == 0: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, 0) if stage == 'pg': M2[0,3] = -0.25 # offset about x elif stage == 'gp': M2[0,3] = -0.18 # offset about x M2[1,3] = 0.0 # about y M2[2,3] = 0.0 # about z elif axis == 1: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, 1.57) M2[0,3] = 0.0 # offset about x if stage == 'pg': M2[1,3] = -0.25 # about y elif stage == 'gp': M2[1,3] = -0.18 # about y M2[2,3] = 0.0 # about z elif axis == 2: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, -1.57) M2[0,3] = 0.0 # offset about x if stage == 'pg': M2[1,3] = 0.25 # about y elif stage == 'gp': M2[1,3] = 0.18 # about y M2[2,3] = 0.0 # about z elif axis == 3: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 0, 3.14) if stage == 'pg': M2[0,3] = 0.25 # offset about x elif stage == 'gp': M2[0,3] = 0.18 # offset about x M2[1,3] = 0.0 # about y M2[2,3] = 0.0 # about z elif axis == 4: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(0, 1.57, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y if stage == 'pg': M2[2,3] = 0.30 # about z elif stage == 'gp': M2[2,3] = 0.23 # about z else: M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) M1[0,3] = target_pose.pose.position.x M1[1,3] = target_pose.pose.position.y M1[2,3] = target_pose.pose.position.z M2 = transformations.euler_matrix(1.57, 1.57, 0) M2[0,3] = 0.0 # offset about x M2[1,3] = 0.0 # about y if stage == 'pg': M2[2,3] = 0.30 # about z elif stage == 'gp': M2[2,3] = 0.23 # about z T1 = np.dot(M1, M2) grasp_pose = deepcopy(target_pose) grasp_pose.pose.position.x = T1[0,3] grasp_pose.pose.position.y = T1[1,3] grasp_pose.pose.position.z = T1[2,3] quat = transformations.quaternion_from_matrix(T1) grasp_pose.pose.orientation.x = quat[0] grasp_pose.pose.orientation.y = quat[1] grasp_pose.pose.orientation.z = quat[2] grasp_pose.pose.orientation.w = quat[3] grasp_pose.header.frame_id = REFERENCE_FRAME return grasp_pose def grasp_generator(self, initial_poses): # A list to hold the grasps grasps = [] o = [] # Original Pose of the object (o) O=[] i= 0 while i < len(initial_poses): o.append(initial_poses[i]) i+=1 G = transformations.euler_matrix(0, 0, 0) # Generate a grasps for along z axis (x and y directions) k = 0 while k <= 5: O.append(transformations.quaternion_matrix([o[k].pose.orientation.x, o[k].pose.orientation.y, o[k].pose.orientation.z, o[k].pose.orientation.w])) O[k][0,3] = o[k].pose.position.x O[k][1,3] = o[k].pose.position.y O[k][2,3] = o[k].pose.position.z if k in range(0,4): for z in self.drange(0.005-obj_size[obj_id.index('target')][2]/2,-0.005 + obj_size[obj_id.index('target')][2]/2, 0.02): ### TODO: USE EACH OBJECTS SIZE NOT ONLY THE TARGETS ### # print z T = np.dot(O[k], G) grasp = deepcopy(o[k]) grasp.pose.position.x = T[0,3] grasp.pose.position.y = T[1,3] grasp.pose.position.z = T[2,3] +z quat = transformations.quaternion_from_matrix(T) grasp.pose.orientation.x = quat[0] grasp.pose.orientation.y = quat[1] grasp.pose.orientation.z = quat[2] grasp.pose.orientation.w = quat[3] grasp.header.frame_id = REFERENCE_FRAME # Append the grasp to the list grasps.append(deepcopy(grasp)) elif k == 4: for x in self.drange(-obj_size[obj_id.index('target')][1]/2, obj_size[obj_id.index('target')][1]/2, 0.02): # print z T = np.dot(O[k], G) grasp = deepcopy(o[k]) grasp.pose.position.x = T[0,3] +x grasp.pose.position.y = T[1,3] grasp.pose.position.z = T[2,3] quat = transformations.quaternion_from_matrix(T) grasp.pose.orientation.x = quat[0] grasp.pose.orientation.y = quat[1] grasp.pose.orientation.z = quat[2] grasp.pose.orientation.w = quat[3] grasp.header.frame_id = REFERENCE_FRAME # Append the grasp to the list grasps.append(deepcopy(grasp)) else: for y in self.drange(-obj_size[obj_id.index('target')][1]/2, obj_size[obj_id.index('target')][1]/2, 0.02): # print z T = np.dot(O[k], G) grasp = deepcopy(o[k]) grasp.pose.position.x = T[0,3] grasp.pose.position.y = T[1,3] +y grasp.pose.position.z = T[2,3] quat = transformations.quaternion_from_matrix(T) grasp.pose.orientation.x = quat[0] grasp.pose.orientation.y = quat[1] grasp.pose.orientation.z = quat[2] grasp.pose.orientation.w = quat[3] grasp.header.frame_id = REFERENCE_FRAME # Append the grasp to the list grasps.append(deepcopy(grasp)) k+=1 print len(grasps) # Return the list return grasps def scene_generator(self): while True: # print "happening" obj_pose =[] obj_id = [] obj_size = [] bl = ['ground_plane','pr2'] global obj_pose, obj_id , obj_size ops = PoseStamped() ops.header.frame_id = REFERENCE_FRAME for model_name in self.pwh.name: if model_name not in bl: obj_id.append(model_name) ops.pose = self.pwh.pose[self.pwh.name.index(model_name)] obj_pose.append(deepcopy(ops)) obj_size.append([0.05, 0.05, 0.15]) # obj_id[obj_id.index('custom_1')] = 'target' obj_size[obj_id.index('custom_2')] = [0.05, 0.05, 0.10] obj_size[obj_id.index('custom_3')] = [0.05, 0.05, 0.05] obj_size[obj_id.index('custom_table')] = [1.5, 0.8, 0.03] if self.aro is None: for i in range(0, len(obj_id)): ### CREATE THE SCENE ### self.scene.add_box(obj_id[i], obj_pose[i], obj_size[i]) self.setColor(obj_id[i], 1, 0.623, 0, 1.0) ### Make the target purple and table green ### self.setColor(obj_id[obj_id.index('target')], 0.6, 0, 1, 1.0) self.setColor(obj_id[obj_id.index('custom_table')], 0.3, 1, 0.3, 1.0) self.scene.remove_attached_object(GRIPPER_FRAME) # Send the colors to the planning scene self.sendColors() else: if self.flag == 0: touch_links = [GRIPPER_FRAME, 'r_gripper_l_finger_tip_link','r_gripper_r_finger_tip_link', 'r_gripper_r_finger_link', 'r_gripper_l_finger_link', 'r_wrist_roll_link', 'r_upper_arm_link'] #print touch_links self.scene.attach_box(GRIPPER_FRAME, obj_id[self.aro], obj_pose[self.aro], obj_size[self.aro], touch_links) ### REMOVE SPECIFIC OBJECT AFTER IT HAS BEEN ATTACHED TO GRIPPER ### self.scene.remove_world_object(obj_id[self.aro]) self.flag +=1 time.sleep(0.5) def model_state_callback(self,msg): self.pwh = ModelStates() self.pwh = msg def bl(self): blist = ['target','custom_2','custom_3', 'custom_table'] self.blist = [] for name in obj_id: if name not in blist: self.blist.append(obj_id.index(name)) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, obj_id[obj_id.index(name)]) self.scene.remove_attached_object(GRIPPER_FRAME, 'target') return self.blist def drange(self, start, stop, step): r = start while r < stop: yield r r += step def close_gripper(self): g_close = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.044, 100)) self.ac.send_goal(g_close) self.ac.wait_for_result() rospy.sleep(15) # Gazebo requires up to 15 seconds to attach object def open_gripper(self): g_open = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.0899, 100)) self.ac.send_goal(g_open) self.ac.wait_for_result() rospy.sleep(5) # And up to 20 to detach it # Set the color of an object def setColor(self, name, r, g, b, a = 0.9): # Initialize a MoveIt color object color = ObjectColor() # Set the id to the name given as an argument color.id = name # Set the rgb and alpha values given as input color.color.r = r color.color.g = g color.color.b = b color.color.a = a # Update the global color dictionary self.colors[name] = color # Actually send the colors to MoveIt! def sendColors(self): # Initialize a planning scene object p = PlanningScene() # Need to publish a planning scene diff p.is_diff = True # Append the colors from the global color dictionary for color in self.colors.values(): p.object_colors.append(color) # Publish the scene diff self.scene_pub.publish(p) def lasp(self): sp = PoseStamped() sp.header.frame_id = REFERENCE_FRAME sp.pose.position.x = 0.3665 sp.pose.position.y = 0.74094 sp.pose.position.z = 1.1449 sp.pose.orientation.x = 0.80503 sp.pose.orientation.y = -0.18319 sp.pose.orientation.z = 0.31988 sp.pose.orientation.w = 0.46481 self.left_arm.plan(sp) self.left_arm.go(wait=True) def rasp(self): sp = PoseStamped() sp.header.frame_id = REFERENCE_FRAME sp.pose.position.x = 0.39571 sp.pose.position.y = -0.40201 sp.pose.position.z = 1.1128 sp.pose.orientation.x =0.00044829 sp.pose.orientation.y = 0.57956 sp.pose.orientation.z = 9.4878e-05 sp.pose.orientation.w = 0.81493 self.right_arm.plan(sp) self.right_arm.go(wait=True)
def __init__(self): # 初始化move_group的API moveit_commander.roscpp_initialize(sys.argv) # 初始化ROS节点 rospy.init_node('moveit_pick_and_place_demo') # 初始化场景对象 scene = PlanningSceneInterface() # 创建一个发布场景变化信息的发布者 self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # 创建一个发布抓取姿态的发布者 self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # 创建一个存储物体颜色的字典对象 self.colors = dict() # 初始化需要使用move group控制的机械臂中的arm group arm = MoveGroupCommander(GROUP_NAME_ARM) # 初始化需要使用move group控制的机械臂中的gripper group gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # 获取终端link的名称 end_effector_link = arm.get_end_effector_link() # 设置位置(单位:米)和姿态(单位:弧度)的允许误差 arm.set_goal_position_tolerance(0.05) arm.set_goal_orientation_tolerance(0.1) # 当运动规划失败后,允许重新规划 arm.allow_replanning(True) # 设置目标位置所使用的参考坐标系 arm.set_pose_reference_frame(REFERENCE_FRAME) # 设置每次运动规划的时间限制:5s arm.set_planning_time(5) # 设置pick和place阶段的最大尝试次数 max_pick_attempts = 5 max_place_attempts = 5 rospy.sleep(2) # 设置场景物体的名称 table_id = 'table' box1_id = 'box1' box2_id = 'box2' target_id = 'target' # 移除场景中之前运行残留的物体 scene.remove_world_object(table_id) scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(target_id) # 移除场景中之前与机器臂绑定的物体 scene.remove_attached_object(GRIPPER_FRAME, target_id) rospy.sleep(1) # 控制机械臂先回到初始化位置 arm.set_named_target('home') arm.go() # 控制夹爪张开 gripper.set_joint_value_target(GRIPPER_OPEN) gripper.go() rospy.sleep(1) # 设置桌面的高度 table_ground = 0.2 # 设置table、box1和box2的三维尺寸[长, 宽, 高] table_size = [0.2, 0.7, 0.01] box1_size = [0.1, 0.05, 0.05] box2_size = [0.05, 0.05, 0.15] # 将三个物体加入场景当中 table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose.position.x = 0.35 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box(table_id, table_pose, table_size) box1_pose = PoseStamped() box1_pose.header.frame_id = REFERENCE_FRAME box1_pose.pose.position.x = 0.31 box1_pose.pose.position.y = -0.1 box1_pose.pose.position.z = table_ground + table_size[ 2] + box1_size[2] / 2.0 box1_pose.pose.orientation.w = 1.0 scene.add_box(box1_id, box1_pose, box1_size) box2_pose = PoseStamped() box2_pose.header.frame_id = REFERENCE_FRAME box2_pose.pose.position.x = 0.29 box2_pose.pose.position.y = -0.4 box2_pose.pose.position.z = table_ground + table_size[ 2] + box2_size[2] / 2.0 box2_pose.pose.orientation.w = 1.0 scene.add_box(box2_id, box2_pose, box2_size) # 将桌子设置成红色,两个box设置成橙色 self.setColor(table_id, 0.8, 0, 0, 1.0) self.setColor(box1_id, 0.8, 0.4, 0, 1.0) self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # 设置目标物体的尺寸 target_size = [0.04, 0.04, 0.05] # 设置目标物体的位置,位于桌面之上两个盒子之间 target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = 0.32 target_pose.pose.position.y = 0.0 target_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.w = 1.0 # 将抓取的目标物体加入场景中 scene.add_box(target_id, target_pose, target_size) # 将目标物体设置为黄色 self.setColor(target_id, 0.9, 0.9, 0, 1.0) # 将场景中的颜色设置发布 self.sendColors() # 设置支持的外观 arm.set_support_surface_name(table_id) # 设置一个place阶段需要放置物体的目标位置 place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.32 place_pose.pose.position.y = -0.2 place_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 # 将目标位置设置为机器人的抓取目标位置 grasp_pose = target_pose # 生成抓取姿态 grasps = self.make_grasps(grasp_pose, [target_id]) # 将抓取姿态发布,可以在rviz中显示 for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # 追踪抓取成功与否,以及抓取的尝试次数 result = None n_attempts = 0 # 重复尝试抓取,直道成功或者超多最大尝试次数 while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) result = arm.pick(target_id, grasps) rospy.sleep(0.2) # 如果pick成功,则进入place阶段 if result == MoveItErrorCodes.SUCCESS: result = None n_attempts = 0 # 生成放置姿态 places = self.make_places(place_pose) # 重复尝试放置,直道成功或者超多最大尝试次数 while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) for place in places: result = arm.place(target_id, place) if result == MoveItErrorCodes.SUCCESS: break rospy.sleep(0.2) if result != MoveItErrorCodes.SUCCESS: rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") else: rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") # 控制机械臂回到初始化位置 arm.set_named_target('home') arm.go() # 控制夹爪回到张开的状态 gripper.set_joint_value_target(GRIPPER_OPEN) gripper.go() rospy.sleep(1) # 关闭并退出moveit moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('AttachMesh') # Construct the initial scene object scene = PlanningSceneInterface() # Pause for the scene to get ready rospy.sleep(1) # Initialize the MoveIt! commander for the right wam and fingers right_wam = moveit_commander.MoveGroupCommander('right_wam') right_wam_finger_1 = moveit_commander.MoveGroupCommander('right_wam_finger_1') right_wam_finger_2 = moveit_commander.MoveGroupCommander('right_wam_finger_2') right_wam_finger_3 = moveit_commander.MoveGroupCommander('right_wam_finger_3') # Get the name of the end-effector link end_effector_link = right_wam.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) right_wam.set_goal_position_tolerance(0.01) right_wam.set_goal_orientation_tolerance(0.05) # Allow replanning to increase the odds of a solution right_wam.allow_replanning(True) # Allow 5 seconds per planning attempt right_wam.set_planning_time(5) # Remove leftover objects from a previous run scene.remove_attached_object(end_effector_link, 'spoon') right_wam.set_named_target('right_wam_start') right_wam.go() rospy.sleep(2) # Closing the hand first # Closing the hand right_wam_finger_1.set_named_target("right_wam_finger_1_grasp") right_wam_finger_2.set_named_target("right_wam_finger_2_grasp") right_wam_finger_3.set_named_target("right_wam_finger_3_grasp") right_wam_finger_1.execute(right_wam_finger_1.plan()) rospy.sleep(5) right_wam_finger_2.execute(right_wam_finger_2.plan()) rospy.sleep(5) right_wam_finger_3.execute(right_wam_finger_3.plan()) rospy.sleep(5) # Set the length, width and height of the object to attach #tool_size = [0.3, 0.02, 0.02] # Create a pose for the tool relative to the end-effector p = PoseStamped() p.header.frame_id = end_effector_link # Place the end of the object within the grasp of the gripper p.pose.position.x = 0.0 p.pose.position.y = 0.0 p.pose.position.z = -0.02 # Align the object with the gripper (straight out) p.pose.orientation.x = -0.5 p.pose.orientation.y = 0.5 p.pose.orientation.z = -0.5 p.pose.orientation.w = 0.5 scene.attach_mesh(end_effector_link, 'spoon', p, '/home/yzheng/catkin_ws/src/manipulation_scenarios/ycb_object_models/models/stl/spoon.stl') moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the right arm right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the move group for the right gripper right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = right_arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) right_arm.set_goal_position_tolerance(0.05) right_arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution right_arm.allow_replanning(True) # Set the right arm reference frame right_arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 10 seconds per planning attempt right_arm.set_planning_time(10) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 10 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name table_id = 'table' box1_id = 'box1' box2_id = 'box2' target_id = 'target' tool_id = 'tool' # Remove leftover objects from a previous run scene.remove_world_object(table_id) scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(target_id) scene.remove_world_object(tool_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "resting" pose stored in the SRDF file right_arm.set_named_target('right_start') right_arm.go() # Open the gripper to the neutral position right_gripper.set_joint_value_target(GRIPPER_NEUTRAL) right_gripper.go() rospy.sleep(1) # Set the height of the table off the ground table_ground = 0.65 # Set the dimensions of the scene objects [l, w, h] table_size = [0.2, 0.7, 0.01] box1_size = [0.1, 0.05, 0.05] box2_size = [0.05, 0.05, 0.15] # Set the target size [l, w, h] target_size = [0.02, 0.01, 0.12] # Add a table top and two boxes to the scene table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose.position.x = 0.55 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box(table_id, table_pose, table_size) box1_pose = PoseStamped() box1_pose.header.frame_id = REFERENCE_FRAME box1_pose.pose.position.x = 0.55 box1_pose.pose.position.y = -0.1 box1_pose.pose.position.z = table_ground + table_size[2] + box1_size[2] / 2.0 box1_pose.pose.orientation.w = 1.0 scene.add_box(box1_id, box1_pose, box1_size) box2_pose = PoseStamped() box2_pose.header.frame_id = REFERENCE_FRAME box2_pose.pose.position.x = 0.54 box2_pose.pose.position.y = 0.13 box2_pose.pose.position.z = table_ground + table_size[2] + box2_size[2] / 2.0 box2_pose.pose.orientation.w = 1.0 scene.add_box(box2_id, box2_pose, box2_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = 0.60 target_pose.pose.position.y = 0.0 target_pose.pose.position.z = table_ground + table_size[2] + target_size[2] / 2.0 target_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) # Make the table red and the boxes orange self.setColor(table_id, 0.8, 0, 0, 1.0) self.setColor(box1_id, 0.8, 0.4, 0, 1.0) self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object right_arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.50 place_pose.pose.position.y = -0.25 place_pose.pose.position.z = table_ground + table_size[2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 # Initialize the grasp pose to the target pose grasp_pose = target_pose # Shift the grasp pose by half the width of the target to center it grasp_pose.pose.position.y -= target_size[1] / 2.0 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id]) # Publish the grasp poses so they can be viewed in RViz for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) result = right_arm.pick(target_id, grasps) rospy.sleep(0.2) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: result = None n_attempts = 0 #_------------------------now we move to the other table__________------------------------------------------- #_------------------------now we move to the other table__________------------------------------------------- # Generate valid place poses places = self.make_places(place_pose) # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) for place in places: result = right_arm.place(target_id, place) if result == MoveItErrorCodes.SUCCESS: break rospy.sleep(0.2) if result != MoveItErrorCodes.SUCCESS: rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") else: rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") # Return the arm to the "resting" pose stored in the SRDF file right_arm.set_named_target('right_start') right_arm.go() # Open the gripper to the neutral position right_gripper.set_joint_value_target(GRIPPER_NEUTRAL) right_gripper.go() rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
class PickAndPlaceServer(object): def __init__(self): rospy.loginfo("Initalizing PickAndPlaceServer...") self.sg = SphericalGrasps() rospy.loginfo("Connecting to pickup AS") self.pickup_ac = SimpleActionClient('/pickup', PickupAction) self.pickup_ac.wait_for_server() rospy.loginfo("Succesfully connected.") '''rospy.loginfo("Connecting to place AS") self.place_ac = SimpleActionClient('/place', PlaceAction) self.place_ac.wait_for_server() rospy.loginfo("Succesfully connected.")''' self.scene = PlanningSceneInterface() rospy.loginfo("Connecting to /get_planning_scene service") self.scene_srv = rospy.ServiceProxy( '/get_planning_scene', GetPlanningScene) self.scene_srv.wait_for_service() rospy.loginfo("Connected.") rospy.loginfo("Connecting to clear octomap service...") self.clear_octomap_srv = rospy.ServiceProxy( '/clear_octomap', Empty) self.clear_octomap_srv.wait_for_service() rospy.loginfo("Connected!") def set_height(height): self.object_height = height.data rospy.loginfo("Object height set to " + str(self.object_height)) rospy.Subscriber("height", Float64, set_height) # Get the object size self.object_height = rospy.get_param('~object_height') self.object_width = rospy.get_param('~object_width') self.object_depth = rospy.get_param('~object_depth') # Get the links of the end effector exclude from collisions self.links_to_allow_contact = rospy.get_param('~links_to_allow_contact', None) if self.links_to_allow_contact is None: rospy.logwarn("Didn't find any links to allow contacts... at param ~links_to_allow_contact") else: rospy.loginfo("Found links to allow contacts: " + str(self.links_to_allow_contact)) self.pick_as = SimpleActionServer( '/pickup_pose', PickUpPoseAction, execute_cb=self.pick_cb, auto_start=False) self.pick_as.start() '''self.place_as = SimpleActionServer( '/place_pose', PickUpPoseAction, execute_cb=self.place_cb, auto_start=False) self.place_as.start()''' def pick_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.grasp_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.pick_as.set_aborted(p_res) else: self.pick_as.set_succeeded(p_res) '''def place_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.place_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.place_as.set_aborted(p_res) else: self.place_as.set_succeeded(p_res)''' def wait_for_planning_scene_object(self, object_name='part'): rospy.loginfo( "Waiting for object '" + object_name + "'' to appear in planning scene...") gps_req = GetPlanningSceneRequest() gps_req.components.components = gps_req.components.WORLD_OBJECT_NAMES part_in_scene = False while not rospy.is_shutdown() and not part_in_scene: # This call takes a while when rgbd sensor is set gps_resp = self.scene_srv.call(gps_req) # check if 'part' is in the answer for collision_obj in gps_resp.scene.world.collision_objects: if collision_obj.id == object_name: part_in_scene = True break else: rospy.sleep(1.0) rospy.loginfo("'" + object_name + "'' is in scene!") #HEARTS tried inputting multiple cubes to approximate cylinder #TODO re-investigate if time allows #def rotate_quat(self,quat,angle_deg,axis_euler): ''' Rotate about axis_euler by angle_deg,the quaternion quat, returned as a quaternion ''' #euler = tf.transformations.euler_from_quaternion(quat) #euler(2) = euler(0.5*np.pi) def grasp_object(self, object_pose): rospy.loginfo("Removing any previous 'part' object") self.scene.remove_attached_object("arm_tool_link") self.scene.remove_world_object("part") self.scene.remove_world_object("table") rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) rospy.sleep(2.0) # Removing is fast rospy.loginfo("Adding new 'part' object") rospy.loginfo("Object pose: %s", object_pose.pose) part_pose = copy.deepcopy(object_pose) part_pose.pose.position.z -= self.object_height/4 #Add object description in scene self.scene.add_box("part", part_pose, (self.object_depth, self.object_width, self.object_height)) # Add rotated boxes (for collision avoidance) #box1_pose = copy.deepcopy(object_pose) rospy.loginfo("Second%s", object_pose.pose) table_pose = copy.deepcopy(object_pose) #define a virtual table below the object table_height = object_pose.pose.position.z - self.object_height table_width = 1.8 table_depth = 0.5 #TODO update so it works when detecting centre of object table_pose.pose.position.z += -(self.object_height)/2 -table_height/2 table_height -= 0.008 #remove few milimeters to prevent contact between the object and the table self.scene.add_box("table", table_pose, (table_depth, table_width, table_height)) # # We need to wait for the object part to appear self.wait_for_planning_scene_object("part") self.wait_for_planning_scene_object("table") # compute grasps possible_grasps = self.sg.create_grasps_from_object_pose(object_pose) self.pickup_ac goal = createPickupGoal( "arm_torso", "part", object_pose, possible_grasps, self.links_to_allow_contact) rospy.loginfo("Waiting for final pick instruction") rospy.wait_for_message('/pick_it',String) rospy.loginfo("Sending goal") self.pickup_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.pickup_ac.wait_for_result() result = self.pickup_ac.get_result() rospy.logdebug("Using torso result: " + str(result)) rospy.loginfo( "Pick result: " + str(moveit_error_dict[result.error_code.val])) return result.error_code.val '''def place_object(self, object_pose):
gripper_pose = arm.get_current_pose(arm.get_end_effector_link()) # part p.pose.position.x = gripper_pose.pose.position.x p.pose.position.y = gripper_pose.pose.position.y p.pose.position.z = gripper_pose.pose.position.z # add part scene.add_box(PICK_OBJECT, p, (0.07, 0.07, 0.1)) rospy.loginfo("Added object to world") # attach object manually arm.attach_object(PICK_OBJECT, arm.get_end_effector_link(), GRIPPER_JOINTS) rospy.sleep(1) # ===== place start ==== # place_result = place(PLANNING_GROUP, PICK_OBJECT, generate_place_pose()) rospy.loginfo("Place Result is:") rospy.loginfo("Human readable error: " + str(moveit_error_dict[place_result.error_code.val])) rospy.sleep(5) # remove part scene.remove_world_object(PICK_OBJECT) scene.remove_attached_object(arm.get_end_effector_link(), PICK_OBJECT) rospy.sleep(2) i += 1 # end moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped) # Initialize the move group for the right arm Arm = MoveGroupCommander(GROUP_NAME_ARM) Arm.set_planner_id("RRTstarkConfigDefault") # Initialize the move group for the right gripper Hand = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = Arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) Arm.set_goal_position_tolerance(0.05) Arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution Arm.allow_replanning(True) # Set the right arm reference frame Arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt Arm.set_planning_time(10) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 3 # Set a limit on the number of place attempts max_place_attempts = 3 # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name target_id = 'target' # Remove leftover objects from a previous run scene.remove_world_object(target_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Open the gripper to the neutral position #Hand.set_joint_value_target(GRIPPER_NEUTRAL) #Hand.go() #rospy.sleep(1) target_size = [0.01, 0.01, 0.01] # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = 0.3 target_pose.pose.position.y = 0.03 target_pose.pose.position.z = -0.3 target_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) # Initialize the grasp pose to the target pose grasp_pose = PoseStamped() grasp_pose.header.frame_id = REFERENCE_FRAME grasp_pose.pose = target_pose.pose grasp_pose.pose.position.y = 0.2 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id]) # Publish the grasp poses so they can be viewed in RViz for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) result = Arm.pick(target_id, grasps) rospy.sleep(0.2) rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') scene = PlanningSceneInterface() self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) self.colors = dict() rospy.sleep(1) arm = MoveGroupCommander('arm') end_effector_link = arm.get_end_effector_link() arm.set_goal_position_tolerance(0.005) arm.set_goal_orientation_tolerance(0.025) arm.allow_replanning(True) reference_frame = 'base_link' arm.set_pose_reference_frame(reference_frame) arm.set_planning_time(5) #scene planning table_id = 'table' #cylinder_id='cylinder' #box1_id='box1' box2_id = 'box2' target_id = 'target_object' #scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(table_id) scene.remove_world_object(target_id) rospy.sleep(2) table_ground = 0.68 table_size = [0.5, 1, 0.01] #box1_size=[0.1,0.05,0.03] box2_size = [0.05, 0.05, 0.1] r_tool_size = [0.03, 0.01, 0.06] l_tool_size = [0.03, 0.01, 0.06] target_size = [0.05, 0.05, 0.1] table_pose = PoseStamped() table_pose.header.frame_id = reference_frame table_pose.pose.position.x = 0.75 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box(table_id, table_pose, table_size) ''' box1_pose=PoseStamped() box1_pose.header.frame_id=reference_frame box1_pose.pose.position.x=0.7 box1_pose.pose.position.y=-0.2 box1_pose.pose.position.z=table_ground+table_size[2]+box1_size[2]/2.0 box1_pose.pose.orientation.w=1.0 scene.add_box(box1_id,box1_pose,box1_size) ''' box2_pose = PoseStamped() box2_pose.header.frame_id = reference_frame box2_pose.pose.position.x = 0.6 box2_pose.pose.position.y = -0.05 box2_pose.pose.position.z = table_ground + table_size[ 2] + box2_size[2] / 2.0 box2_pose.pose.orientation.w = 1.0 scene.add_box(box2_id, box2_pose, box2_size) target_pose = PoseStamped() target_pose.header.frame_id = reference_frame target_pose.pose.position.x = 0.6 target_pose.pose.position.y = 0.05 target_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.x = 0 target_pose.pose.orientation.y = 0 target_pose.pose.orientation.z = 0 target_pose.pose.orientation.w = 1 scene.add_box(target_id, target_pose, target_size) #left gripper l_p = PoseStamped() l_p.header.frame_id = end_effector_link l_p.pose.position.x = 0.00 l_p.pose.position.y = 0.04 l_p.pose.position.z = 0.04 l_p.pose.orientation.w = 1 scene.attach_box(end_effector_link, 'l_tool', l_p, l_tool_size) #right gripper r_p = PoseStamped() r_p.header.frame_id = end_effector_link r_p.pose.position.x = 0.00 r_p.pose.position.y = -0.04 r_p.pose.position.z = 0.04 r_p.pose.orientation.w = 1 scene.attach_box(end_effector_link, 'r_tool', r_p, r_tool_size) #grasp g_p = PoseStamped() g_p.header.frame_id = end_effector_link g_p.pose.position.x = 0.00 g_p.pose.position.y = -0.00 g_p.pose.position.z = 0.025 g_p.pose.orientation.w = 0.707 g_p.pose.orientation.x = 0 g_p.pose.orientation.y = -0.707 g_p.pose.orientation.z = 0 #set color self.setColor(table_id, 0.8, 0, 0, 1.0) #self.setColor(box1_id,0.8,0.4,0,1.0) self.setColor(box2_id, 0.8, 0.4, 0, 1.0) self.setColor('r_tool', 0.8, 0, 0) self.setColor('l_tool', 0.8, 0, 0) self.setColor('target_object', 0, 1, 0) self.sendColors() #motion planning arm.set_named_target("initial_arm1") arm.go() rospy.sleep(2) grasp_pose = target_pose grasp_pose.pose.position.x -= 0.15 #grasp_pose.pose.position.z= grasp_pose.pose.orientation.x = 0 grasp_pose.pose.orientation.y = 0.707 grasp_pose.pose.orientation.z = 0 grasp_pose.pose.orientation.w = 0.707 arm.set_start_state_to_current_state() arm.set_pose_target(grasp_pose, end_effector_link) traj = arm.plan() arm.execute(traj) rospy.sleep(2) print arm.get_current_joint_values() #arm.shift_pose_target(4,1.57,end_effector_link) #arm.go() #rospy.sleep(2) arm.shift_pose_target(0, 0.11, end_effector_link) arm.go() rospy.sleep(2) print arm.get_current_joint_values() saved_target_pose = arm.get_current_pose(end_effector_link) #arm.set_named_target("initial_arm2") #grasp scene.attach_box(end_effector_link, target_id, g_p, target_size) rospy.sleep(2) #grasping is over , from now is placing arm.shift_pose_target(2, 0.15, end_effector_link) arm.go() rospy.sleep(2) print arm.get_current_joint_values() arm.shift_pose_target(1, -0.2, end_effector_link) arm.go() rospy.sleep(2) print arm.get_current_joint_values() arm.shift_pose_target(2, -0.15, end_effector_link) arm.go() rospy.sleep(2) print arm.get_current_joint_values() scene.remove_attached_object(end_effector_link, target_id) rospy.sleep(2) #arm.set_pose_target(saved_target_pose,end_effector_link) #arm.go() #rospy.sleep(2) arm.set_named_target("initial_arm1") arm.go() rospy.sleep(2) #remove and shut down scene.remove_attached_object(end_effector_link, 'l_tool') scene.remove_attached_object(end_effector_link, 'r_tool') moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('MotionSequence') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) # Create a publisher for displaying left wam finger poses self.left_wam_finger_1_pub = rospy.Publisher('left_wam_finger_1', PoseStamped) self.left_wam_finger_2_pub = rospy.Publisher('left_wam_finger_2', PoseStamped) self.left_wam_finger_3_pub = rospy.Publisher('left_wam_finger_3', PoseStamped) # Create a dictionary to hold object colors self.colors = dict() # Define move group comander for each moveit group left_wam = moveit_commander.MoveGroupCommander('left_wam') right_wam = moveit_commander.MoveGroupCommander('right_wam') left_wam_finger_1 = moveit_commander.MoveGroupCommander('left_wam_finger_1') left_wam_finger_2 = moveit_commander.MoveGroupCommander('left_wam_finger_2') left_wam_finger_3 = moveit_commander.MoveGroupCommander('left_wam_finger_3') right_wam_finger_1 = moveit_commander.MoveGroupCommander('right_wam_finger_1') right_wam_finger_2 = moveit_commander.MoveGroupCommander('right_wam_finger_2') right_wam_finger_3 = moveit_commander.MoveGroupCommander('right_wam_finger_3') left_wam.set_planner_id("PRMstarkConfigDefault") right_wam.set_planner_id("PRMstarkConfigDefault") #left_wam_finger_1.set_planner_id("RRTstarkConfigDefault") #left_wam_finger_2.set_planner_id("RRTstarkConfigDefault") #left_wam_finger_3.set_planner_id("RRTstarkConfigDefault") #right_wam_finger_1.set_planner_id("RRTstarkConfigDefault") #right_wam_finger_2.set_planner_id("RRTstarkConfigDefault") #right_wam_finger_3.set_planner_id("RRTstarkConfigDefault") # Get the name of the end-effector link left_end_effector_link = left_wam.get_end_effector_link() right_end_effector_link = right_wam.get_end_effector_link() # Display the name of the end_effector link rospy.loginfo("The end effector link of left wam is: " + str(left_end_effector_link)) rospy.loginfo("The end effector link of right wam is: " + str(right_end_effector_link)) # Allow some leeway in position (meters) and orientation (radians) right_wam.set_goal_position_tolerance(0.01) right_wam.set_goal_orientation_tolerance(0.05) left_wam.set_goal_position_tolerance(0.01) left_wam.set_goal_orientation_tolerance(0.05) # Allow replanning to increase the odds of a solution right_wam.allow_replanning(True) left_wam.allow_replanning(True) # Allow 5 seconds per planning attempt right_wam.set_planning_time(15) left_wam.set_planning_time(25) # Allow replanning to increase the odds of a solution right_wam.allow_replanning(True) left_wam.allow_replanning(True) # Set the reference frame for wam arms left_wam.set_pose_reference_frame(REFERENCE_FRAME) right_wam.set_pose_reference_frame(REFERENCE_FRAME) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name table_id = 'table' bowl_id = 'bowl' pitcher_id = 'pitcher' spoon_id = 'spoon' # Remove leftover objects from a previous run scene.remove_world_object(table_id) scene.remove_world_object(bowl_id) scene.remove_world_object(pitcher_id) scene.remove_world_object(spoon_id) # Remove leftover objects from a previous run scene.remove_attached_object(right_end_effector_link, 'spoon') #right_wam.set_named_target('right_wam_start') #right_wam.go() #rospy.sleep(2) # Closing the hand first # Closing the hand #right_wam_finger_1.set_named_target("right_wam_finger_1_grasp") #right_wam_finger_2.set_named_target("right_wam_finger_2_grasp") #right_wam_finger_3.set_named_target("right_wam_finger_3_grasp") #right_wam_finger_1.execute(right_wam_finger_1.plan()) #rospy.sleep(5) #right_wam_finger_2.execute(right_wam_finger_2.plan()) #rospy.sleep(5) #right_wam_finger_3.execute(right_wam_finger_3.plan()) #rospy.sleep(5) # Create a pose for the tool relative to the end-effector p = PoseStamped() p.header.frame_id = right_end_effector_link # Place the end of the object within the grasp of the gripper p.pose.position.x = 0.0 p.pose.position.y = 0.0 p.pose.position.z = -0.02 # Align the object with the gripper (straight out) p.pose.orientation.x = -0.5 p.pose.orientation.y = 0.5 p.pose.orientation.z = -0.5 p.pose.orientation.w = 0.5 # Attach the tool to the end-effector # Set the height of the table off the ground table_ground = 0.5762625 # Set the length, width and height of the table and boxes table_size = [0.90128, 0.381, 0.0238125] table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose.position.x = 0 table_pose.pose.position.y = 0.847725 table_pose.pose.position.z = table_ground scene.add_box(table_id, table_pose, table_size) # Set the height of the bowl bowl_ground = 0.57816875 bowl_pose = PoseStamped() bowl_pose.header.frame_id = REFERENCE_FRAME bowl_pose.pose.position.x = 0.015 bowl_pose.pose.position.y = 0.847725 bowl_pose.pose.position.z = bowl_ground scene.add_mesh(bowl_id, bowl_pose, '/home/yzheng/catkin_ws/src/manipulation_scenarios/ycb_object_models/models/stl/bowl.stl') # Set the height of the pitcher #pitcher_ground = 0.57816875 #pitcher_pose = PoseStamped() #pitcher_pose.header.frame_id = REFERENCE_FRAME #pitcher_pose.pose.position.x = 0.25 #pitcher_pose.pose.position.y = 0.847725 #pitcher_pose.pose.position.z = pitcher_ground #pitcher_pose.pose.orientation.w = -0.5 #pitcher_pose.pose.orientation.z = 0.707 #scene.add_mesh(pitcher_id, pitcher_pose, '/home/yzheng/catkin_ws/src/manipulation_scenarios/ycb_object_models/models/stl/pitcher.stl') # Make the table red and the boxes orange self.setColor(table_id, 0.8, 0.4, 0, 1.0) self.setColor(bowl_id, 0, 0.4, 0.8, 1.0) #self.setColor(pitcher_id, 0.9, 0.9, 0, 1.0) self.sendColors() rospy.sleep(2) start = input("Start left_wam planning ? ") # Set the support surface name to the table object #left_wam.set_support_surface_name(table_id) #right_wam.set_support_surface_name(table_id) # Set the target pose. target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.header.stamp = rospy.Time.now() target_pose.pose.position.x = 0.40363476287 target_pose.pose.position.y = 0.847725 target_pose.pose.position.z = 0.721472317843 target_pose.pose.orientation.x = 0.707 target_pose.pose.orientation.y = 0 target_pose.pose.orientation.z = -0.707 target_pose.pose.orientation.w = 0 # Set the start state to the current state left_wam.set_start_state_to_current_state() # Set the goal pose of the end effector to the stored pose left_wam.set_pose_target(target_pose, left_end_effector_link) left_wam.execute(left_wam.plan()) left_wam.shift_pose_target(5, 0, left_end_effector_link) start = input("Left wam starting position ") # Pause for a second # Closing the hand left_wam_finger_1.set_named_target("left_wam_finger_1_grasp") left_wam_finger_2.set_named_target("left_wam_finger_2_grasp") left_wam_finger_3.set_named_target("left_wam_finger_3_grasp") left_wam_finger_1.execute(left_wam_finger_1.plan()) #rospy.sleep(3) left_wam_finger_2.execute(left_wam_finger_2.plan()) #rospy.sleep(3) left_wam_finger_3.execute(left_wam_finger_3.plan()) #rospy.sleep(3) start = input("Left wam hand closing ") end_pose = deepcopy(left_wam.get_current_pose(left_end_effector_link).pose) intermidiate_pose = deepcopy(end_pose) intermidiate_pose.position.z = intermidiate_pose.position.z + 0.05 plan = self.StraightPath(end_pose, intermidiate_pose, left_wam) left_wam.set_start_state_to_current_state() left_wam.execute(plan) start = input("Hold up the Pitcher ") end_pose = deepcopy(left_wam.get_current_pose(left_end_effector_link).pose) intermidiate_pose = deepcopy(end_pose) intermidiate_pose.position.x = intermidiate_pose.position.x - 0.1 plan = self.StraightPath(end_pose, intermidiate_pose, left_wam) left_wam.set_start_state_to_current_state() left_wam.execute(plan) start = input("left_wam into pouring position ") end_pose = deepcopy(left_wam.get_current_pose(left_end_effector_link)) back_pose = deepcopy(end_pose) end_pose.pose.orientation.x = 0.97773401145 end_pose.pose.orientation.y = 0 end_pose.pose.orientation.z = -0.209726592658 end_pose.pose.orientation.w = 0 # Set the start state to the current state left_wam.set_start_state_to_current_state() # Set the goal pose of the end effector to the stored pose left_wam.set_pose_target(end_pose, left_end_effector_link) left_wam.execute(left_wam.plan()) start = input("Pour the water ") # Set the start state to the current state left_wam.set_start_state_to_current_state() # Set the goal pose of the end effector to the stored pose left_wam.set_pose_target(back_pose, left_end_effector_link) left_wam.execute(left_wam.plan()) end_pose = deepcopy(left_wam.get_current_pose(left_end_effector_link)) end_pose.pose.position.x = end_pose.pose.position.x + 0.1 # Set the start state to the current state left_wam.set_start_state_to_current_state() # Set the goal pose of the end effector to the stored pose left_wam.set_pose_target(end_pose, left_end_effector_link) left_wam.execute(left_wam.plan()) start = input("Left_wam back to prep position") target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.header.stamp = rospy.Time.now() target_pose.pose.position.x = -0.600350195463908 target_pose.pose.position.y = 0.80576308041 target_pose.pose.position.z = 0.794775212132 target_pose.pose.orientation.x = 3.01203251908e-05 target_pose.pose.orientation.y = 0.705562870053 target_pose.pose.orientation.z = 4.55236739937e-05 target_pose.pose.orientation.w = 0.708647326547 start = input("Start right_wam planning ? ") right_wam.set_start_state_to_current_state() right_wam.set_pose_target(target_pose, right_end_effector_link) right_wam.execute(right_wam.plan()) start = input("right_wam into position. ") start_pose = deepcopy(right_wam.get_current_pose(right_end_effector_link).pose) intermidiate_pose = deepcopy(right_wam.get_current_pose(right_end_effector_link).pose) intermidiate_pose.position.x = intermidiate_pose.position.x + 0.6 plan = self.StraightPath(start_pose, intermidiate_pose, right_wam) right_wam.set_start_state_to_current_state() right_wam.execute(plan) rospy.sleep(3) # Closing the hand right_wam_finger_1.set_named_target("right_wam_finger_1_grasp") right_wam_finger_2.set_named_target("right_wam_finger_2_grasp") right_wam_finger_3.set_named_target("right_wam_finger_3_grasp") right_wam_finger_1.execute(right_wam_finger_1.plan()) #rospy.sleep(3) right_wam_finger_2.execute(right_wam_finger_2.plan()) #rospy.sleep(3) right_wam_finger_3.execute(right_wam_finger_3.plan()) rospy.sleep(1) scene.attach_mesh(right_end_effector_link, 'spoon', p, '/home/yzheng/catkin_ws/src/manipulation_scenarios/ycb_object_models/models/stl/spoon.stl') #create a circle path circles = input("How many circles you want the wam to mix ? ") start_pose = deepcopy(right_wam.get_current_pose(right_end_effector_link).pose) plan = self.CircularPath(start_pose, circles, right_wam) #execute the circle path right_wam.set_start_state_to_current_state() right_wam.execute(plan) pause = input("Mix the oatmeal ") #put the right_wam back to preparation pose end_pose = deepcopy(right_wam.get_current_pose(right_end_effector_link).pose) intermidiate_pose1 = deepcopy(end_pose) intermidiate_pose1.position.z = intermidiate_pose1.position.z + 0.1 plan = self.StraightPath(end_pose, intermidiate_pose1, right_wam) right_wam.set_start_state_to_current_state() right_wam.execute(plan) pause = input("wait for the execution of straight path ") end_pose = deepcopy(right_wam.get_current_pose(right_end_effector_link).pose) intermidiate_pose2 = deepcopy(end_pose) intermidiate_pose2.position.x = intermidiate_pose2.position.x - 0.25 plan = self.StraightPath(end_pose, intermidiate_pose2, right_wam) right_wam.set_start_state_to_current_state() right_wam.execute(plan) pause = input("right_wam back into prep position ") #left_wam.shift_pose_target(5, 0, left_end_effector_link) #left_wam.go() #rospy.sleep(2) #left_wam.shift_pose_target(0, -0.05, left_end_effector_link) #left_wam.go() #rospy.sleep(2) # Initialize the grasp pose to the target pose #grasp_pose = target_pose # Generate a list of grasps #grasps = self.make_grasps(grasp_pose, [pitcher_id]) # Publish the grasp poses so they can be viewed in RViz #for grasp in grasps: # self.left_wam_finger_1_pub.publish(grasp.grasp_pose) # rospy.sleep(0.2) # self.left_wam_finger_2_pub.publish(grasp.grasp_pose) # rospy.sleep(0.2) # self.left_wam_finger_3_pub.publish(grasp.grasp_pose) # rospy.sleep(0.2) moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
class PickAndPlace: def setColor(self, name, r, g, b, a=0.9): color = ObjectColor() color.id = name color.color.r = r color.color.g = g color.color.b = b color.color.a = a self.colors[name] = color def sendColors(self): p = PlanningScene() p.is_diff = True for color in self.colors.values(): p.object_colors.append(color) self.scene_pub.publish(p) def add_point(self, traj, time, positions, velocities=None): point = trajectory_msgs.msg.JointTrajectoryPoint() point.positions = copy.deepcopy(positions) if velocities is not None: point.velocities = copy.deepcopy(velocities) point.time_from_start = rospy.Duration(time) traj.points.append(point) def FollowQTraj(self, q_traj, t_traj): assert (len(q_traj) == len(t_traj)) #Insert current position to beginning. if t_traj[0] > 1.0e-2: t_traj.insert(0, 0.0) q_traj.insert(0, self.Q(arm=arm)) self.dq_traj = self.QTrajToDQTraj(q_traj, t_traj) #self.traj= self.ToROSTrajectory(self.JointNames(), q_traj, t_traj, dq_traj) #, dq_traj #print traj #self.sub_jpc.publish(self.ToROSTrajectory(self.JointNames(), q_traj, t_traj, dq_traj)) def QTrajToDQTraj(self, q_traj, t_traj): dof = len(q_traj[0]) #Modeling the trajectory with spline. splines = [TCubicHermiteSpline() for d in range(dof)] for d in range(len(splines)): data_d = [[t, q[d]] for q, t in zip(q_traj, t_traj)] splines[d].Initialize(data_d, tan_method=splines[d].CARDINAL, c=0.0, m=0.0) #NOTE: We don't have to make spline models as we just want velocities at key points. # They can be obtained by computing tan_method, which will be more efficient. with_tan=True dq_traj = [] for t in t_traj: dq = [splines[d].Evaluate(t, with_tan=True)[1] for d in range(dof)] dq_traj.append(dq) #print dq_traj return dq_traj def JointNames(self): #0arm= 0 return self.joint_names[0] def ROSGetJTP(self, q, t, dq=None): jp = trajectory_msgs.msg.JointTrajectoryPoint() jp.positions = q jp.time_from_start = rospy.Duration(t) if dq is not None: jp.velocities = dq return jp def ToROSTrajectory(self, joint_names, q_traj, t_traj, dq_traj=None): assert (len(q_traj) == len(t_traj)) if dq_traj is not None: (len(dq_traj) == len(t_traj)) #traj= trajectory_msgs.msg.JointTrajectory() self.traj.joint_names = joint_names if dq_traj is not None: self.traj.points = [ self.ROSGetJTP(q, t, dq) for q, t, dq in zip(q_traj, t_traj, dq_traj) ] else: self.traj.points = [ self.ROSGetJTP(q, t) for q, t in zip(q_traj, t_traj) ] self.traj.header.stamp = rospy.Time.now() #print self.traj return self.traj def SmoothQTraj(self, q_traj): if len(q_traj) == 0: return q_prev = np.array(q_traj[0]) q_offset = np.array([0] * len(q_prev)) for q in q_traj: q_diff = np.array(q) - q_prev for d in range(len(q_prev)): if q_diff[d] < -math.pi: q_offset[d] += 1 elif q_diff[d] > math.pi: q_offset[d] -= 1 q_prev = copy.deepcopy(q) q[:] = q + q_offset * 2.0 * math.pi def add_target(self, f_target_pose, frame, x, y, o1, o2, o3, o4): f_target_pose.header.frame_id = frame f_target_pose.pose.position.x = x f_target_pose.pose.position.y = y f_target_pose.pose.position.z = self.table_ground + self.table_size[ 2] + self.f_target_size[2] / 2.0 f_target_pose.pose.orientation.x = o1 f_target_pose.pose.orientation.y = o2 f_target_pose.pose.orientation.z = o3 f_target_pose.pose.orientation.w = o4 #self.scene.add_box(f_target_id,f_target_pose,f_target_size) def cts(self, start_pose, end_pose, maxtries, exe_signal=False): waypoints = [] fraction = 0.0 attempts = 0 #maxtries_z=300 waypoints.append(start_pose) waypoints.append(end_pose) while fraction != 1 and attempts < maxtries: (plan, fraction) = self.arm.compute_cartesian_path( waypoints, 0.005, 0.0, True) attempts += 1 if (attempts % maxtries == 0 and fraction != 1): rospy.loginfo("path planning failed with " + str(fraction * 100) + "% success.") signal = False elif fraction == 1: rospy.loginfo("path compute successfully with " + str(attempts) + " attempts.") if exe_signal: self.arm.execute(plan) end_joint_state = plan.joint_trajectory.points[-1].positions signal = True return plan, end_joint_state, signal # shaking function: # freq : shaking freqence # times : shaking time per action def shaking(self, initial_state, start_joint_state, end_joint_state, freq, times): q_traj = [initial_state] t_traj = [0.0] for i in range(times): q_traj.append(end_joint_state) t_traj.append(t_traj[-1] + 0.5 / freq) q_traj.append(start_joint_state) t_traj.append(t_traj[-1] + 0.5 / freq) q_traj.append(initial_state) t_traj.append(t_traj[-1] + 0.5 / freq) self.FollowQTraj(q_traj, t_traj) self.sub_jpc.publish( self.ToROSTrajectory(self.JointNames(), q_traj, t_traj, self.dq_traj)) rospy.sleep(6) def setupSence(self): r_tool_size = [0.03, 0.02, 0.18] l_tool_size = [0.03, 0.02, 0.18] #real scene table table_pose = PoseStamped() table_pose.header.frame_id = self.reference_frame table_pose.pose.position.x = -0.184 table_pose.pose.position.y = 0.62 table_pose.pose.position.z = self.table_ground + self.table_size[ 2] / 2.0 table_pose.pose.orientation.w = 1.0 self.scene.add_box(self.table_id, table_pose, self.table_size) #left gripper l_p = PoseStamped() l_p.header.frame_id = self.arm_end_effector_link l_p.pose.position.x = 0.00 l_p.pose.position.y = 0.057 l_p.pose.position.z = 0.09 l_p.pose.orientation.w = 1 self.scene.attach_box(self.arm_end_effector_link, self.l_id, l_p, l_tool_size) #right gripper r_p = PoseStamped() r_p.header.frame_id = self.arm_end_effector_link r_p.pose.position.x = 0.00 r_p.pose.position.y = -0.057 r_p.pose.position.z = 0.09 r_p.pose.orientation.w = 1 self.scene.attach_box(self.arm_end_effector_link, self.r_id, r_p, r_tool_size) def __init__(self): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') self.scene = PlanningSceneInterface() pub_traj = rospy.Publisher('/joint_path_command', trajectory_msgs.msg.JointTrajectory, queue_size=10) self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) self.gripperCtrl = rospy.ServiceProxy( "/two_finger/gripper/gotoPositionUntilTouch", SetPosition) #self.m2j=rospy.Publisher("/two_finger/motoman_control/move_to_joint",JointAnglesDuration,queue_size=1,latch=True) self.colors = dict() rospy.sleep(1) self.arm = MoveGroupCommander('arm') cartesian = rospy.get_param('~cartesian', True) self.arm_end_effector_link = self.arm.get_end_effector_link() self.arm.set_goal_position_tolerance(0.005) self.arm.set_goal_orientation_tolerance(0.025) self.arm.allow_replanning(True) self.reference_frame = 'base_link' self.arm.set_pose_reference_frame(self.reference_frame) self.arm.set_planning_time(5) #shaking self.joint_names = [[]] self.joint_names[0] = rospy.get_param('controller_joint_names') self.traj = trajectory_msgs.msg.JointTrajectory() self.sub_jpc = rospy.Publisher('/joint_path_command', trajectory_msgs.msg.JointTrajectory, queue_size=10) #scene planning self.l_id = 'l_tool' self.r_id = 'r_tool' self.table_id = 'table' self.target1_id = 'target1_object' self.target2_id = 'target2_object' self.target3_id = 'target3_object' self.target4_id = 'target4_object' self.f_target_id = 'receive_container' self.scene.remove_world_object(self.l_id) self.scene.remove_world_object(self.r_id) self.scene.remove_world_object(self.table_id) self.scene.remove_world_object(self.target1_id) self.scene.remove_world_object(self.target2_id) self.scene.remove_world_object(self.target3_id) self.scene.remove_world_object(self.target4_id) #self.scene.remove_attached_object(self.arm_end_effector_link,self.target_id) self.scene.remove_world_object(self.f_target_id) self.table_ground = 0.13 self.table_size = [0.9, 0.6, 0.018] self.setupSence() joint_names = [ 'joint_' + jkey for jkey in ('s', 'l', 'e', 'u', 'r', 'b', 't') ] joint_names = rospy.get_param('controller_joint_names') traj = trajectory_msgs.msg.JointTrajectory() traj.joint_names = joint_names target1_size = [0.058, 0.058, 0.19] target2_size = [0.058, 0.058, 0.19] target3_size = [0.058, 0.058, 0.19] target4_size = [0.058, 0.058, 0.19] self.f_target_size = [0.2, 0.2, 0.04] f_target_pose = PoseStamped() pre_pour_pose = PoseStamped() target1_pose = PoseStamped() target2_pose = PoseStamped() target3_pose = PoseStamped() target4_pose = PoseStamped() #self.target_pose=PoseStamped() #final target #self.add_target(f_target_pose,self.reference_frame,-0.184+0.27,0.62+0.1,0,0,0,1) #self.scene.add_box(self.f_target_id,f_target_pose,f_target_size) #self.add_target(pre_pour_pose,self.reference_frame,x,y,0,0,0,1) #pouring pose pour_pose = f_target_pose pour_pose.pose.position.x -= 0.06 pour_pose.pose.position.y -= 0.12 pour_pose.pose.position.z += 0.15 pour_pose.pose.orientation.x = -0.5 pour_pose.pose.orientation.y = -0.5 pour_pose.pose.orientation.z = -0.5 pour_pose.pose.orientation.w = 0.5 #grasp_pose g_p = PoseStamped() g_p.header.frame_id = self.arm_end_effector_link g_p.pose.position.x = 0.00 g_p.pose.position.y = -0.00 g_p.pose.position.z = 0.025 g_p.pose.orientation.w = 0.707 g_p.pose.orientation.x = 0 g_p.pose.orientation.y = -0.707 g_p.pose.orientation.z = 0 #set color self.setColor(self.target1_id, 0.8, 0, 0, 1.0) self.setColor(self.target2_id, 0.8, 0, 0, 1.0) self.setColor(self.target3_id, 0.8, 0, 0, 1.0) self.setColor(self.target4_id, 0.8, 0, 0, 1.0) self.setColor(self.f_target_id, 0.8, 0.4, 0, 1.0) self.setColor('r_tool', 0.8, 0, 0) self.setColor('l_tool', 0.8, 0, 0) self.setColor(self.table_id, 0, 1, 0) self.sendColors() self.gripperCtrl(255) rospy.sleep(3) self.arm.set_named_target("initial_arm") self.arm.go() rospy.sleep(5) j_ori_state = [ -1.899937629699707, -0.5684762597084045, 0.46537330746650696, 2.3229329586029053, -0.057941947132349014, -1.2867668867111206, 0.2628822326660156 ] signal = True self.arm.set_joint_value_target(j_ori_state) self.arm.go() rospy.sleep(3) #target localization tar_num = 2 maxtries = 300 #msg = rospy.wait_for_message('/aruco_single/pose',PoseStamped) self.add_target(target1_pose, self.reference_frame, -0.05, 0.6, 0, 0, 0, 1) self.scene.add_box(self.target1_id, target1_pose, target1_size) self.add_target(target2_pose, self.reference_frame, -0.15, 0.55, 0, 0, 0, 1) self.scene.add_box(self.target2_id, target2_pose, target2_size) #self.add_target(target3_pose,self.reference_frame,-0.25y,0,0,0,1) #self.scene.add_box(target3_id,target3_pose,target3_size) #self.add_target(target4_pose,self.reference_frame,x,y,0,0,0,1) #self.scene.add_box(target4_id,target4_pose,target4_size) #path planning #input : target pose #output : policy and execute #cts : output : plan, end_joint_state, signal #global target_pose,target_id,target_size for i in range(tar_num): start_pose = self.arm.get_current_pose( self.arm_end_effector_link).pose if i == 0: target_pose = target1_pose target_id = self.target1_id target_size = target1_size elif i == 1: target_pose = target2_pose target_id = self.target2_id target_size = target2_size elif i == 2: self.target_pose = target3_pose self.target_id = target3_id self.target_size = target3_size elif i == 3: self.target_pose = target4_pose self.target_id = target4_id self.target_size = target4_size #pick up if cartesian: plan_1, end_joint_state_1, signal_1 = self.cts( start_pose, target_pose.pose, maxtries) if signal_1: self.arm.set_joint_value_target(end_joint_state_1) self.arm.go() rospy.sleep(5) self.gripperCtrl(0) rospy.sleep(2) self.scene.attach_box(self.arm_end_effector_link, target_id, g_p, target_size) self.arm.set_joint_value_target(start_pose) self.arm.go() rospy.sleep(5) self.arm.set_joint_value_target(end_joint_state_1) self.arm.go() rospy.sleep(5) self.gripperCtrl(255) self.scene.remove_attached_object( self.arm_end_effector_link, target_id) rospy.sleep(3) self.arm.set_joint_value_target(start_pose) self.arm.go() rospy.sleep(5) """ #move to pouring pose if cartesian: plan_2, end_joint_state_2,signal_2=self.cts(start_pose,target_pose,maxtries) if signal_2: self.arm.set_joint_value_target(end_joint_state_2) self.arm.go() rospy.sleep(5) #scene.remove_attached_object(end_effector_link,target_id) #shaking amp= freq= r_angle= start_pick_pose=self.arm.get_current_pose(self.arm_end_effector_link).pose start_joint_state=self.arm.get_current_joint_values() shift_x_pose=deepcopy(start_pick_pose) shift_z_pose=deepcopy(start_pick_pose) shift_x_pose.position.x+=0.04 shift_z_pose.position.z-=0.04 #exe_sig=False if cartesian: plan_z,end_joint_state_z,signal_z=self.cts(start_pick_pose,shift_z_pose,300) plan_x,end_joint_state_x,signal_x=self.cts(start_pick_pose,shift_x_pose,300) #shaking process #signal_x=False shake_times=0 #self.freq=3.0 signal=True while signal: if (shake_times%3!=0 and signal_x) or (shake_times%3==0 and not signal_z): self.shaking(start_joint_state,end_joint_state_x,3,3) elif shake_times%3==0 and signal_z: self.shaking(start_joint_state,end_joint_state_z,3,1) shake_times+=1 rospy.loginfo("shaking times : "+str(shake_times)+ " .") if shake_times==10: signal=False """ #remove and shut down #self.scene.remove_attached_object(self.arm_end_effector_link,'l_tool') #self.scene.remove_attached_object(self.arm_end_effector_link,'r_tool') moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
group_left.set_pose_target(pose, "l_eef") result = group_left.go(None,1) if result == 0: print "ERROR init pos left" sys.exit() ####################### ADD RIGHT SHOE TO THE SCENE ############################### scene.remove_attached_object('r_eef', 'right_shoe') rospy.sleep(1) pose.pose.position.x = 0.475 pose.pose.position.y = -0.1500 pose.pose.position.z = 1.035 pose.pose.orientation.w = 0.99144 pose.pose.orientation.x = 0 pose.pose.orientation.y = 0 pose.pose.orientation.z = 0.13053 pose.header.frame_id = robot.get_planning_frame() pose.header.stamp = rospy.Time.now() path = roslib.packages.get_pkg_dir('hermes_virtual_robot')+'/common/files/stl/right_shoe.stl' scene.add_mesh("right_shoe", pose, path) rospy.sleep(1)
def __init__(self): roscpp_initialize(sys.argv) rospy.init_node('moveit_py_demo', anonymous=True) scene = PlanningSceneInterface() robot = RobotCommander() right_arm = MoveGroupCommander(GROUP_NAME_ARM) #right_arm.set_planner_id("KPIECEkConfigDefault"); right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) eef = right_arm.get_end_effector_link() rospy.sleep(2) scene.remove_attached_object(GRIPPER_FRAME, "part") # clean the scene scene.remove_world_object("table") scene.remove_world_object("part") right_arm.set_named_target("right_start") right_arm.go() right_gripper.set_named_target("right_gripper_open") right_gripper.go() rospy.sleep(1) # publish a demo scene p = PoseStamped() p.header.frame_id = robot.get_planning_frame() # add a table p.pose.position.x = 0.42 p.pose.position.y = -0.2 p.pose.position.z = 0.3 scene.add_box("table", p, (0.5, 1.5, 0.6)) # add an object to be grasped p.pose.position.x = 0.40 p.pose.position.y = -0.0 p.pose.position.z = 0.85 scene.add_box("part", p, (0.07, 0.01, 0.2)) rospy.sleep(1) g = Grasp() g.id = "test" start_pose = PoseStamped() start_pose.header.frame_id = FIXED_FRAME # start the gripper in a neutral pose part way to the target start_pose.pose.position.x = 0.37636 start_pose.pose.position.y = 0.21886 start_pose.pose.position.z = 0.9 start_pose.pose.orientation.x = 0.00080331 start_pose.pose.orientation.y = 0.001589 start_pose.pose.orientation.z = -2.4165e-06 start_pose.pose.orientation.w = 1 right_arm.set_pose_target(start_pose) right_arm.go() rospy.sleep(2) # generate a list of grasps grasps = self.make_grasps(start_pose) result = False n_attempts = 0 # repeat until will succeed while result == False: result = robot.right_arm.pick("part", grasps) n_attempts += 1 print "Attempts: ", n_attempts rospy.sleep(0.3) rospy.spin() roscpp_shutdown()
class PickAndPlaceServer(object): def __init__(self): self.node_name = "PickAndPlaceServer" rospy.loginfo("Initalizing PickAndPlaceServer...") self.sg = SphericalGrasps() # Get the object size self.object_height = 0.1 self.object_width = 0.05 self.object_depth = 0.05 self.pick_pose = rospy.get_param('~pickup_marker_pose') self.place_pose = rospy.get_param('~place_marker_pose') rospy.loginfo("%s: Waiting for pickup action server...", self.node_name) self.pickup_ac = SimpleActionClient('/pickup', PickupAction) connected = self.pickup_ac.wait_for_server(rospy.Duration(3000)) if not connected: rospy.logerr("%s: Could not connect to pickup action server", self.node_name) exit() rospy.loginfo("%s: Connected to pickup action server", self.node_name) rospy.loginfo("%s: Waiting for place action server...", self.node_name) self.place_ac = SimpleActionClient('/place', PlaceAction) if not self.place_ac.wait_for_server(rospy.Duration(3000)): rospy.logerr("%s: Could not connect to place action server", self.node_name) exit() rospy.loginfo("%s: Connected to place action server", self.node_name) self.scene = PlanningSceneInterface() rospy.loginfo("Connecting to /get_planning_scene service") self.scene_srv = rospy.ServiceProxy('/get_planning_scene', GetPlanningScene) self.scene_srv.wait_for_service() rospy.loginfo("Connected.") rospy.loginfo("Connecting to clear octomap service...") self.clear_octomap_srv = rospy.ServiceProxy('/clear_octomap', Empty) self.clear_octomap_srv.wait_for_service() rospy.loginfo("Connected!") # Get the links of the end effector exclude from collisions self.links_to_allow_contact = rospy.get_param( '~links_to_allow_contact', None) if self.links_to_allow_contact is None: rospy.logwarn( "Didn't find any links to allow contacts... at param ~links_to_allow_contact" ) else: rospy.loginfo("Found links to allow contacts: " + str(self.links_to_allow_contact)) self.pick_as = SimpleActionServer(self.pick_pose, PickUpPoseAction, execute_cb=self.pick_cb, auto_start=False) self.pick_as.start() self.place_as = SimpleActionServer(self.place_pose, PickUpPoseAction, execute_cb=self.place_cb, auto_start=False) self.place_as.start() def pick_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.grasp_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1 and error_code != -3: self.pick_as.set_aborted(p_res) else: self.pick_as.set_succeeded(p_res) def place_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.place_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.place_as.set_aborted(p_res) else: self.place_as.set_succeeded(p_res) def wait_for_planning_scene_object(self, object_name='part'): rospy.loginfo("Waiting for object '" + object_name + "'' to appear in planning scene...") gps_req = GetPlanningSceneRequest() gps_req.components.components = gps_req.components.WORLD_OBJECT_NAMES part_in_scene = False while not rospy.is_shutdown() and not part_in_scene: # This call takes a while when rgbd sensor is set gps_resp = self.scene_srv.call(gps_req) # check if 'part' is in the answer for collision_obj in gps_resp.scene.world.collision_objects: if collision_obj.id == object_name: part_in_scene = True break else: rospy.sleep(1.0) rospy.loginfo("'" + object_name + "'' is in scene!") def grasp_object(self, object_pose): rospy.loginfo("Removing any previous 'part' object") self.scene.remove_attached_object("arm_tool_link") self.scene.remove_world_object("part") self.scene.remove_world_object("table") rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) rospy.sleep(2.0) #Add object description in scene rospy.loginfo("Adding new 'part' object") object_pose.pose.position.z = object_pose.pose.position.z + 0.06 object_pose.pose.position.x = object_pose.pose.position.x - 0.03 # rospy.loginfo("Object pose: %s", object_pose.pose) self.scene.add_box( "part", object_pose, (self.object_depth, self.object_width, self.object_height)) #define a virtual table below the object table_pose = copy.deepcopy(object_pose) table_height = 0.8 table_width = 0.8 table_depth = 0.8 table_pose.pose.position.z += -( self.object_height) / 2 - table_height / 2 table_pose.pose.position.x += 0.25 # # We need to wait for the object part to appear self.scene.add_box("table", table_pose, (table_depth, table_width, table_height)) self.wait_for_planning_scene_object() self.wait_for_planning_scene_object("table") # compute grasps possible_grasps = self.sg.create_grasps_from_object_pose(object_pose) goal = createPickupGoal("arm_torso", "part", object_pose, possible_grasps, self.links_to_allow_contact) rospy.loginfo("Sending goal") self.pickup_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.pickup_ac.wait_for_result() result = self.pickup_ac.get_result() rospy.logdebug("Using torso result: " + str(result)) rospy.loginfo("Pick result: " + str(moveit_error_dict[result.error_code.val])) # Remove table from world self.scene.remove_world_object("table") return result.error_code.val def place_object(self, object_pose): rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) possible_placings = self.sg.create_placings_from_object_pose( object_pose) # Try only with arm rospy.loginfo("Trying to place using only arm") goal = createPlaceGoal(object_pose, possible_placings, "arm", "part", self.links_to_allow_contact) rospy.loginfo("Sending goal") self.place_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.place_ac.wait_for_result() result = self.place_ac.get_result() rospy.loginfo(str(moveit_error_dict[result.error_code.val])) if str(moveit_error_dict[result.error_code.val]) != "SUCCESS": rospy.loginfo("Trying to place with arm and torso") # Try with arm and torso goal = createPlaceGoal(object_pose, possible_placings, "arm_torso", "part", self.links_to_allow_contact) rospy.loginfo("Sending goal") self.place_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.place_ac.wait_for_result() result = self.place_ac.get_result() rospy.loginfo(str(moveit_error_dict[result.error_code.val])) rospy.loginfo("Result: " + str(moveit_error_dict[result.error_code.val])) rospy.loginfo("Removing previous 'part' object") self.scene.remove_world_object("part") return result.error_code.val
class PickAndPlaceServer(object): def __init__(self): rospy.loginfo("Initalizing PickAndPlaceServer...") self.sg = SphericalGrasps() rospy.loginfo("Connecting to pickup AS") self.pickup_ac = SimpleActionClient('/pickup', PickupAction) self.pickup_ac.wait_for_server() rospy.loginfo("Succesfully connected.") rospy.loginfo("Connecting to place AS") self.place_ac = SimpleActionClient('/place', PlaceAction) self.place_ac.wait_for_server() rospy.loginfo("Succesfully connected.") self.scene = PlanningSceneInterface() rospy.loginfo("Connecting to /get_planning_scene service") self.scene_srv = rospy.ServiceProxy( '/get_planning_scene', GetPlanningScene) self.scene_srv.wait_for_service() rospy.loginfo("Connected.") rospy.loginfo("Connecting to clear octomap service...") self.clear_octomap_srv = rospy.ServiceProxy( '/clear_octomap', Empty) self.clear_octomap_srv.wait_for_service() rospy.loginfo("Connected!") # Get the object size self.object_height = rospy.get_param('~object_height') self.object_width = rospy.get_param('~object_width') self.object_depth = rospy.get_param('~object_depth') # Get the links of the end effector exclude from collisions self.links_to_allow_contact = rospy.get_param('~links_to_allow_contact', None) if self.links_to_allow_contact is None: rospy.logwarn("Didn't find any links to allow contacts... at param ~links_to_allow_contact") else: rospy.loginfo("Found links to allow contacts: " + str(self.links_to_allow_contact)) self.pick_as = SimpleActionServer( '/pickup_pose', PickUpPoseAction, execute_cb=self.pick_cb, auto_start=False) self.pick_as.start() self.place_as = SimpleActionServer( '/place_pose', PickUpPoseAction, execute_cb=self.place_cb, auto_start=False) self.place_as.start() def pick_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.grasp_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.pick_as.set_aborted(p_res) else: self.pick_as.set_succeeded(p_res) def place_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.place_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.place_as.set_aborted(p_res) else: self.place_as.set_succeeded(p_res) def wait_for_planning_scene_object(self, object_name='part'): rospy.loginfo( "Waiting for object '" + object_name + "'' to appear in planning scene...") gps_req = GetPlanningSceneRequest() gps_req.components.components = gps_req.components.WORLD_OBJECT_NAMES part_in_scene = False while not rospy.is_shutdown() and not part_in_scene: # This call takes a while when rgbd sensor is set gps_resp = self.scene_srv.call(gps_req) # check if 'part' is in the answer for collision_obj in gps_resp.scene.world.collision_objects: if collision_obj.id == object_name: part_in_scene = True break else: rospy.sleep(1.0) rospy.loginfo("'" + object_name + "'' is in scene!") def grasp_object(self, object_pose): rospy.loginfo("Removing any previous 'part' object") self.scene.remove_attached_object("arm_tool_link") self.scene.remove_world_object("part") self.scene.remove_world_object("table") self.scene.remove_world_object("left") self.scene.remove_world_object("right") self.scene.remove_world_object("up") self.scene.remove_world_object("back") rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) rospy.sleep(2.0) # Removing is fast rospy.loginfo("Adding new 'part' object") rospy.loginfo("Object pose: %s", object_pose.pose) #Add object description in scene self.scene.add_box("part", object_pose, (self.object_depth, self.object_width, self.object_height)) rospy.loginfo("Second%s", object_pose.pose) table_pose = copy.deepcopy(object_pose) #define a virtual table below the object table_height = 1.8 #object_pose.pose.position.z - self.object_width/2 #before it was 1.8 table_width = 1.8 table_depth = 0.8 table_pose.pose.position.z += -(2*self.object_height)/2 -table_height/2 +0.11 #before also -0.1 and was object width instead of object height table_height -= 0.1 #remove few milimeters to prevent contact between the object and the table self.scene.add_box("table", table_pose, (table_depth, table_width, table_height)) # # We need to wait for the object part to appear self.wait_for_planning_scene_object() self.wait_for_planning_scene_object("table") right_pose = copy.deepcopy(object_pose) #define a virtual table below the object right_height = 1.8 #object_pose.pose.position.z - self.object_width/2 #before it was 1.8 right_width = 1.8 right_depth = 0.8 right_pose.pose.position.y += 0.5 #before also -0.1 and was object width instead of object height right_width = 0.2 #remove few milimeters to prevent contact between the object and the table self.scene.add_box("right", right_pose, (right_depth, right_width, right_height)) # # We need to wait for the object part to appear self.wait_for_planning_scene_object() self.wait_for_planning_scene_object("right") left_pose = copy.deepcopy(object_pose) #define a virtual table below the object left_height = 0.8 #object_pose.pose.position.z - self.object_width/2 #before it was 1.8 left_width = 0.8 left_depth = 0.2 left_pose.pose.position.x += 0.7 #before also -0.1 and was object width instead of object height self.scene.add_box("back", left_pose, (left_depth, left_width, left_height)) self.wait_for_planning_scene_object() self.wait_for_planning_scene_object("back") up_pose = copy.deepcopy(object_pose) #define a virtual table below the object up_height = 0.2 #object_pose.pose.position.z - self.object_width/2 #before it was 1.8 up_width = 1.8 up_depth = 0.8 up_pose.pose.position.z += 0.5 #before also -0.1 and was object width instead of object height self.scene.add_box("up", up_pose, (up_depth, up_width, up_height)) back_pose = copy.deepcopy(object_pose) #define a virtual table below the object back_height = 1.8 #object_pose.pose.position.z - self.object_width/2 #before it was 1.8 back_width = 1.8 back_depth = 0.8 back_pose.pose.position.y -= 0.5 #before also -0.1 and was object width instead of object height back_width = 0.2 #remove few milimeters to prevent contact between the object and the table self.scene.add_box("left", back_pose, (back_depth, back_width, back_height)) self.wait_for_planning_scene_object() self.wait_for_planning_scene_object("left") # compute grasps possible_grasps = self.sg.create_grasps_from_object_pose(object_pose) self.pickup_ac goal = createPickupGoal( "arm", "part", object_pose, possible_grasps, self.links_to_allow_contact) rospy.loginfo("Sending goal") self.pickup_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.pickup_ac.wait_for_result() result = self.pickup_ac.get_result() rospy.logdebug("Using torso result: " + str(result)) rospy.loginfo( "Pick result: " + str(moveit_error_dict[result.error_code.val])) return result.error_code.val def place_object(self, object_pose): rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) possible_placings = self.sg.create_placings_from_object_pose( object_pose) # Try only with arm rospy.loginfo("Trying to place using only arm") goal = createPlaceGoal( object_pose, possible_placings, "arm", "part", self.links_to_allow_contact) rospy.loginfo("Sending goal") self.place_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.place_ac.wait_for_result() result = self.place_ac.get_result() rospy.loginfo(str(moveit_error_dict[result.error_code.val])) if str(moveit_error_dict[result.error_code.val]) != "SUCCESS": rospy.loginfo( "Trying to place with arm and torso") # Try with arm and torso goal = createPlaceGoal( object_pose, possible_placings, "arm", "part", self.links_to_allow_contact) rospy.loginfo("Sending goal") self.place_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.place_ac.wait_for_result() result = self.place_ac.get_result() rospy.logerr(str(moveit_error_dict[result.error_code.val])) # print result rospy.loginfo( "Result: " + str(moveit_error_dict[result.error_code.val])) rospy.loginfo("Removing previous 'part' object") self.scene.remove_world_object("part") return result.error_code.val
class MoveItDemo: def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') #Initialize robot robot = moveit_commander.RobotCommander() # Use the planning scene object to add or remove objects self.scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=10) # Create a publisher for displaying object frames self.object_frames_pub = rospy.Publisher('object_frames', PoseStamped, queue_size=10) ### Create a publisher for visualizing direction ### self.p_pub = rospy.Publisher('target', PoseStamped, latch=True, queue_size = 10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the MoveIt! commander for the arm self.right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the MoveIt! commander for the gripper self.right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Allow 5 seconds per planning attempt self.right_arm.set_planning_time(5) # Prepare Action Controller for gripper self.ac = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',pr2c.Pr2GripperCommandAction) self.ac.wait_for_server() # Give the scene a chance to catch up rospy.sleep(2) # Prepare Gazebo Subscriber self.pwh = None self.pwh_copy = None self.idx_targ = None self.gazebo_subscriber = rospy.Subscriber("/gazebo/model_states", ModelStates, self.model_state_callback) ### OPEN THE GRIPPER ### self.open_gripper() self.obj_att = None # PREPARE THE SCENE while self.pwh is None: rospy.sleep(0.05) ############## CLEAR THE SCENE ################ # planning_scene.world.collision_objects.remove('target') # Remove leftover objects from a previous run self.scene.remove_world_object('target') self.scene.remove_world_object('table') # self.scene.remove_world_object(obstacle1_id) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, 'target') # Run and keep in the BG the scene generator also add the ability to kill the code with ctrl^c timerThread = threading.Thread(target=self.scene_generator) timerThread.daemon = True timerThread.start() initial_pose = target_pose initial_pose.header.frame_id = 'gazebo_world' print "==================== Generating Transformations ===========================" #################### PRE GRASPING POSE ######################### # M1 = transformations.quaternion_matrix([target_pose.pose.orientation.x, target_pose.pose.orientation.y, target_pose.pose.orientation.z, target_pose.pose.orientation.w]) # M1[0,3] = target_pose.pose.position.x # M1[1,3] = target_pose.pose.position.y # M1[2,3] = target_pose.pose.position.z # M2 = transformations.euler_matrix(0, 1.57, 0) # M2[0,3] = 0.0 # offset about x # M2[1,3] = 0.0 # about y # M2[2,3] = 0.25 # about z # T = np.dot(M1, M2) # pre_grasping = deepcopy(target_pose) # pre_grasping.pose.position.x = T[0,3] # pre_grasping.pose.position.y = T[1,3] # pre_grasping.pose.position.z = T[2,3] # quat = transformations.quaternion_from_matrix(T) # pre_grasping.pose.orientation.x = quat[0] # pre_grasping.pose.orientation.y = quat[1] # pre_grasping.pose.orientation.z = quat[2] # pre_grasping.pose.orientation.w = quat[3] # pre_grasping.header.frame_id = 'gazebo_world' # self.plan_exec(pre_grasping) ################# GENERATE GRASPS ################### # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Track success/failure and number of attempts for pick operation success = False n_attempts = 0 grasps = self.grasp_generator(initial_pose) possible_grasps = [] for grasp in grasps: self.gripper_pose_pub.publish(grasp) possible_grasps.append(grasp.pose) rospy.sleep(0.2) #print possible_grasps self.right_arm.pick(target_id, grasps) # target_name = target_id # group_name = GROUP_NAME_ARM # end_effector = GROUP_NAME_GRIPPER # attached_object_touch_links = ['r_forearm_link'] # #print (target_name, group_name, end_effector) # PickupGoal(target_name, group_name ,end_effector, possible_grasps ) # # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # # Exit the script moveit_commander.os._exit(0) ################################################################# FUNCTIONS ################################################################################# def model_state_callback(self,msg): self.pwh = ModelStates() self.pwh = msg def grasp_generator(self, initial_pose): # Pitch angles to try pitch_vals = [1, 1.57,0, 1,2 ] # Yaw angles to try yaw_vals = [0]#, 1.57, -1.57] # A list to hold the grasps grasps = [] g = PoseStamped() g.header.frame_id = REFERENCE_FRAME g.pose = initial_pose.pose #g.pose.position.z += 0.18 # Generate a grasp for each pitch and yaw angle for y in yaw_vals: for p in pitch_vals: # Create a quaternion from the Euler angles q = transformations.quaternion_from_euler(0, p, y) # Set the grasp pose orientation accordingly g.pose.orientation.x = q[0] g.pose.orientation.y = q[1] g.pose.orientation.z = q[2] g.pose.orientation.w = q[3] # Append the grasp to the list grasps.append(deepcopy(g)) # Return the list return grasps def plan_exec(self, pose): self.right_arm.clear_pose_targets() self.right_arm.set_pose_target(pose, GRIPPER_FRAME) self.right_arm.plan() rospy.sleep(5) self.right_arm.go(wait=True) def close_gripper(self): g_close = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.035, 100)) self.ac.send_goal(g_close) self.ac.wait_for_result() rospy.sleep(15) # Gazebo requires up to 15 seconds to attach object def open_gripper(self): g_open = pr2c.Pr2GripperCommandGoal(pr2c.Pr2GripperCommand(0.088, 100)) self.ac.send_goal(g_open) self.ac.wait_for_result() rospy.sleep(5) # And up to 20 to detach it def scene_generator(self): # print obj_att global target_pose global target_id next_call = time.time() while True: next_call = next_call+1 target_id = 'target' self.taid = self.pwh.name.index('wood_cube_5cm') table_id = 'table' self.tid = self.pwh.name.index('table') # obstacle1_id = 'obstacle1' # self.o1id = self.pwh.name.index('wood_block_10_2_1cm') # Set the target size [l, w, h] target_size = [0.05, 0.05, 0.05] table_size = [1.5, 0.8, 0.03] # obstacle1_size = [0.1, 0.025, 0.01] ## Set the target pose on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose = self.pwh.pose[self.taid] target_pose.pose.position.z += 0.025 if self.obj_att is None: # Add the target object to the scene self.scene.add_box(target_id, target_pose, target_size) table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose = self.pwh.pose[self.tid] table_pose.pose.position.z += 1 self.scene.add_box(table_id, table_pose, table_size) # obstacle1_pose = PoseStamped() # obstacle1_pose.header.frame_id = REFERENCE_FRAME # obstacle1_pose.pose = self.pwh.pose[self.o1id] # # Add the target object to the scene # scene.add_box(obstacle1_id, obstacle1_pose, obstacle1_size) ### Make the target purple ### self.setColor(target_id, 0.6, 0, 1, 1.0) # Send the colors to the planning scene self.sendColors() else: self.scene.remove_world_object('target') time.sleep(next_call - time.time()) #threading.Timer(0.5, self.scene_generator).start() # Set the color of an object def setColor(self, name, r, g, b, a = 0.9): # Initialize a MoveIt color object color = ObjectColor() # Set the id to the name given as an argument color.id = name # Set the rgb and alpha values given as input color.color.r = r color.color.g = g color.color.b = b color.color.a = a # Update the global color dictionary self.colors[name] = color # Actually send the colors to MoveIt! def sendColors(self): # Initialize a planning scene object p = PlanningScene() # Need to publish a planning scene diff p.is_diff = True # Append the colors from the global color dictionary for color in self.colors.values(): p.object_colors.append(color) # Publish the scene diff self.scene_pub.publish(p)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) #rospy.init_node('moveit_demo') # Initialize the ROS node rospy.init_node('moveit_demo', anonymous=True) #cartesian = rospy.get_param('~cartesian', True) print "===== It is OK ====" rospy.sleep(3) # Construct the initial scene object scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=1) # Create a dictionary to hold object colors self.colors = dict() # Pause for the scene to get ready rospy.sleep(1) # Initialize the move group for the left arm left_arm = MoveGroupCommander('left_arm') left_gripper = MoveGroupCommander('left_gripper') # Get the name of the end-effector link left_eef = left_arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) left_arm.set_goal_position_tolerance(0.01) left_arm.set_goal_orientation_tolerance(0.05) # Allow replanning to increase the odds of a solution left_arm.allow_replanning(True) left_reference_frame = left_arm.get_planning_frame() # Set the left arm reference frame left_arm.set_pose_reference_frame('base') # Allow 5 seconds per planning attempt left_arm.set_planning_time(10) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 10 # Set a limit on the number of place attempts max_place_attempts = 10 # Give the scene a chance to catch up rospy.sleep(2) #object1_id = 'object1' table_id = 'table' target_id = 'target' #tool_id = 'tool' #obstacle1_id = 'obstacle1' # Remove leftover objects from a previous run #scene.remove_world_object(object1_id) scene.remove_world_object(table_id) scene.remove_world_object(target_id) #scene.remove_world_object(tool_id) # Remove any attached objects from a previous session scene.remove_attached_object('base', target_id) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "resting" pose stored in the SRDF file left_arm.set_named_target('left_arm_zero') left_arm.go() rospy.sleep(1) left_gripper.set_joint_value_target(GRIPPER_OPEN) left_gripper.go() rospy.sleep(1) # Set the height of the table off the ground table_ground = 0.0 #object1_size = [0.088, 0.04, 0.02] # Set the dimensions of the scene objects [l, w, h] table_size = [0.2, 0.7, 0.01] # Set the target size [l, w, h] target_size = [0.02, 0.01, 0.12] # Add a table top and two boxes to the scene #obstacle1_size = [0.3, 0.05, 0.45] # Add a table top and two boxes to the scene #obstacle1_pose = PoseStamped() #obstacle1_pose.header.frame_id = left_reference_frame #obstacle1_pose.pose.position.x = 0.96 #obstacle1_pose.pose.position.y = 0.24 #obstacle1_pose.pose.position.z = 0.04 #obstacle1_pose.pose.orientation.w = 1.0 #scene.add_box(obstacle1_id, obstacle1_pose, obstacle1_size) #self.setColor(obstacle1_id, 0.8, 0.4, 0, 1.0) #object1_pose = PoseStamped() #object1_pose.header.frame_id = left_reference_frame #object1_pose.pose.position.x = 0.80 #object1_pose.pose.position.y = 0.04 #object1_pose.pose.position.z = table_ground + table_size[2] + object1_size[2] / 2.0 #object1_pose.pose.orientation.w = 1.0 #scene.add_box(object1_id, object1_pose, object1_size) # Add a table top and two boxes to the scene table_pose = PoseStamped() table_pose.header.frame_id = left_reference_frame table_pose.pose.position.x = 1 table_pose.pose.position.y = 0.7 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box(table_id, table_pose, table_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = left_reference_frame target_pose.pose.position.x = 1 target_pose.pose.position.y = 0.7 target_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.w = 1 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) # Make the table red and the boxes orange #self.setColor(object1_id, 0.8, 0, 0, 1.0) self.setColor(table_id, 0.8, 0, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object left_arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = left_reference_frame place_pose.pose.position.x = 0.18 place_pose.pose.position.y = -0.18 place_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 0 # Initialize the grasp pose to the target pose grasp_pose = target_pose # Shift the grasp pose by half the width of the target to center it #grasp_pose.pose.position.y -= target_size[1] / 2.0 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id]) # Publish the grasp poses so they can be viewed in RViz for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) result = left_arm.pick(target_id, grasps) rospy.sleep(0.2) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: result = None n_attempts = 0 # Generate valid place poses places = self.make_places(place_pose) # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) for place in places: result = left_arm.place(target_id, place) if result == MoveItErrorCodes.SUCCESS: break rospy.sleep(0.2) if result != MoveItErrorCodes.SUCCESS: rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") else: rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") # Return the arm to the "resting" pose stored in the SRDF file left_arm.set_named_target('left_arm_zero') left_arm.go() # Open the gripper to the neutral position left_gripper.set_joint_value_target(GRIPPER_OPEN) left_gripper.go() rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
class MoveItDemo: def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # We need a tf2 listener to convert poses into arm reference base try: self._tf2_buff = tf2_ros.Buffer() self._tf2_list = tf2_ros.TransformListener(self._tf2_buff) except rospy.ROSException as err: rospy.logerr("MoveItDemo: could not start tf buffer client: " + str(err)) raise err self.gripper_opened = [ rospy.get_param(GRIPPER_PARAM + "/max_opening") - 0.01 ] self.gripper_closed = [ rospy.get_param(GRIPPER_PARAM + "/min_opening") + 0.01 ] self.gripper_neutral = [ rospy.get_param(GRIPPER_PARAM + "/neutral", (self.gripper_opened[0] + self.gripper_closed[0]) / 2.0) ] self.gripper_tighten = rospy.get_param(GRIPPER_PARAM + "/tighten", 0.0) # Use the planning scene object to add or remove objects self.scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=10) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('target_pose', PoseStamped, queue_size=10) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the right arm arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the move group for the right gripper gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) arm.set_goal_position_tolerance(0.04) arm.set_goal_orientation_tolerance(0.01) # Allow replanning to increase the odds of a solution arm.allow_replanning(True) # Set the right arm reference frame arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt arm.set_planning_time(5) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 3 # Set a limit on the number of place attempts max_place_attempts = 3 rospy.loginfo("Scaling for MoveIt timeout=" + str( rospy.get_param( '/move_group/trajectory_execution/allowed_execution_duration_scaling' ))) # Give each of the scene objects a unique name table_id = 'table' box1_id = 'box1' box2_id = 'box2' target_id = 'target' tool_id = 'tool' # Remove leftover objects from a previous run self.scene.remove_world_object(table_id) self.scene.remove_world_object(box1_id) self.scene.remove_world_object(box2_id) self.scene.remove_world_object(target_id) self.scene.remove_world_object(tool_id) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "arm_up" pose stored in the SRDF file rospy.loginfo("Set Arm: right_up") arm.set_named_target('right_up') if arm.go() != True: rospy.logwarn(" Go failed") # Move the gripper to the open position rospy.loginfo("Set Gripper: Open " + str(self.gripper_opened)) gripper.set_joint_value_target(self.gripper_opened) if gripper.go() != True: rospy.logwarn(" Go failed") # Set the height of the table off the ground table_ground = 0.4 # Set the dimensions of the scene objects [l, w, h] table_size = [0.2, 0.7, 0.01] box1_size = [0.1, 0.05, 0.05] box2_size = [0.05, 0.05, 0.15] # Set the target size [l, w, h] target_size = [0.02, 0.005, 0.12] # Add a table top and two boxes to the scene table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose.position.x = 0.36 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 self.scene.add_box(table_id, table_pose, table_size) box1_pose = PoseStamped() box1_pose.header.frame_id = REFERENCE_FRAME box1_pose.pose.position.x = table_pose.pose.position.x - 0.04 box1_pose.pose.position.y = 0.0 box1_pose.pose.position.z = table_ground + table_size[ 2] + box1_size[2] / 2.0 box1_pose.pose.orientation.w = 1.0 self.scene.add_box(box1_id, box1_pose, box1_size) box2_pose = PoseStamped() box2_pose.header.frame_id = REFERENCE_FRAME box2_pose.pose.position.x = table_pose.pose.position.x - 0.06 box2_pose.pose.position.y = 0.2 box2_pose.pose.position.z = table_ground + table_size[ 2] + box2_size[2] / 2.0 box2_pose.pose.orientation.w = 1.0 self.scene.add_box(box2_id, box2_pose, box2_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = table_pose.pose.position.x - 0.03 target_pose.pose.position.y = 0.1 target_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.w = 1.0 # Add the target object to the scene self.scene.add_box(target_id, target_pose, target_size) # Make the table red and the boxes orange self.setColor(table_id, 0.8, 0, 0, 1.0) self.setColor(box1_id, 0.8, 0.4, 0, 1.0) self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = table_pose.pose.position.x - 0.03 place_pose.pose.position.y = -0.15 place_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 # Initialize the grasp pose to the target pose grasp_pose = target_pose # Shift the grasp pose by half the width of the target to center it grasp_pose.pose.position.y -= target_size[1] / 2.0 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id], [target_size[1] - self.gripper_tighten]) # Track success/failure and number of attempts for pick operation result = MoveItErrorCodes.FAILURE n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: rospy.loginfo("Pick attempt #" + str(n_attempts)) for grasp in grasps: # Publish the grasp poses so they can be viewed in RViz self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) result = arm.pick(target_id, grasps) if result == MoveItErrorCodes.SUCCESS: break n_attempts += 1 rospy.sleep(0.2) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: rospy.loginfo(" Pick: Done!") # Generate valid place poses places = self.make_places(target_id, place_pose) success = False n_attempts = 0 # Repeat until we succeed or run out of attempts while not success and n_attempts < max_place_attempts: rospy.loginfo("Place attempt #" + str(n_attempts)) for place in places: # Publish the place poses so they can be viewed in RViz self.gripper_pose_pub.publish(place) rospy.sleep(0.2) success = arm.place(target_id, place) if success: break n_attempts += 1 rospy.sleep(0.2) if not success: rospy.logerr("Place operation failed after " + str(n_attempts) + " attempts.") else: rospy.loginfo(" Place: Done!") else: rospy.logerr("Pick operation failed after " + str(n_attempts) + " attempts.") # Return the arm to the "resting" pose stored in the SRDF file (passing through right_up) arm.set_named_target('right_up') arm.go() arm.set_named_target('resting') arm.go() # Open the gripper to the neutral position gripper.set_joint_value_target(self.gripper_neutral) gripper.go() rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0) # Get the gripper posture as a JointTrajectory def make_gripper_posture(self, joint_positions): # Initialize the joint trajectory for the gripper joints t = JointTrajectory() # Set the joint names to the gripper joint names t.header.stamp = rospy.get_rostime() t.joint_names = GRIPPER_JOINT_NAMES # Initialize a joint trajectory point to represent the goal tp = JointTrajectoryPoint() # Assign the trajectory joint positions to the input positions tp.positions = joint_positions # Set the gripper effort tp.effort = GRIPPER_EFFORT tp.time_from_start = rospy.Duration(0.0) # Append the goal point to the trajectory points t.points.append(tp) # Return the joint trajectory return t # Generate a gripper translation in the direction given by vector def make_gripper_translation(self, min_dist, desired, vector): # Initialize the gripper translation object g = GripperTranslation() # Set the direction vector components to the input g.direction.vector.x = vector[0] g.direction.vector.y = vector[1] g.direction.vector.z = vector[2] # The vector is relative to the gripper frame g.direction.header.frame_id = GRIPPER_FRAME # Assign the min and desired distances from the input g.min_distance = min_dist g.desired_distance = desired return g # Generate a list of possible grasps def make_grasps(self, initial_pose_stamped, allowed_touch_objects, grasp_opening=[0]): # Initialize the grasp object g = Grasp() # Set the pre-grasp and grasp postures appropriately; # grasp_opening should be a bit smaller than target width g.pre_grasp_posture = self.make_gripper_posture(self.gripper_opened) g.grasp_posture = self.make_gripper_posture(grasp_opening) # Set the approach and retreat parameters as desired g.pre_grasp_approach = self.make_gripper_translation( 0.01, 0.1, [1.0, 0.0, 0.0]) g.post_grasp_retreat = self.make_gripper_translation( 0.1, 0.15, [0.0, -1.0, 1.0]) # Set the first grasp pose to the input pose g.grasp_pose = initial_pose_stamped # Pitch angles to try pitch_vals = [0, 0.1, -0.1, 0.2, -0.2, 0.4, -0.4] # Yaw angles to try; given the limited dofs of turtlebot_arm, we must calculate the heading # from arm base to the object to pick (first we must transform its pose to arm base frame) target_pose_arm_ref = self._tf2_buff.transform(initial_pose_stamped, ARM_BASE_FRAME) x = target_pose_arm_ref.pose.position.x y = target_pose_arm_ref.pose.position.y yaw_vals = [atan2(y, x) + inc for inc in [0, 0.1, -0.1]] # A list to hold the grasps grasps = [] # Generate a grasp for each pitch and yaw angle for yaw in yaw_vals: for pitch in pitch_vals: # Create a quaternion from the Euler angles q = quaternion_from_euler(0, pitch, yaw) # Set the grasp pose orientation accordingly g.grasp_pose.pose.orientation.x = q[0] g.grasp_pose.pose.orientation.y = q[1] g.grasp_pose.pose.orientation.z = q[2] g.grasp_pose.pose.orientation.w = q[3] # Set and id for this grasp (simply needs to be unique) g.id = str(len(grasps)) # Set the allowed touch objects to the input list g.allowed_touch_objects = allowed_touch_objects # Don't restrict contact force g.max_contact_force = 0 # Degrade grasp quality for increasing pitch angles g.grasp_quality = 1.0 - abs(pitch) # Append the grasp to the list grasps.append(deepcopy(g)) # Return the list return grasps # Generate a list of possible place poses def make_places(self, target_id, init_pose): # Initialize the place location as a PoseStamped message place = PoseStamped() # Start with the input place pose place = init_pose # A list of x shifts (meters) to try x_vals = [0, 0.005, -0.005] #, 0.01, -0.01, 0.015, -0.015] # A list of y shifts (meters) to try y_vals = [0, 0.005, -0.005, 0.01, -0.01] #, 0.015, -0.015] # A list of pitch angles to try pitch_vals = [0] #, 0.005, -0.005, 0.01, -0.01, 0.02, -0.02] # A list to hold the places places = [] # Generate a place pose for each angle and translation for pitch in pitch_vals: for dy in y_vals: for dx in x_vals: place.pose.position.x = init_pose.pose.position.x + dx place.pose.position.y = init_pose.pose.position.y + dy # Yaw angle: given the limited dofs of turtlebot_arm, we must calculate the heading from # arm base to the place location (first we must transform its pose to arm base frame) target_pose_arm_ref = self._tf2_buff.transform( place, ARM_BASE_FRAME) x = target_pose_arm_ref.pose.position.x y = target_pose_arm_ref.pose.position.y yaw = atan2(y, x) # Create a quaternion from the Euler angles q = quaternion_from_euler(0, pitch, yaw) # Set the place pose orientation accordingly place.pose.orientation.x = q[0] place.pose.orientation.y = q[1] place.pose.orientation.z = q[2] place.pose.orientation.w = q[3] # MoveGroup::place will transform the provided place pose with the attached body pose, so the object retains # the orientation it had when picked. However, with our 4-dofs arm this is infeasible (nor we care about the # objects orientation!), so we cancel this transformation. It is applied here: # https://github.com/ros-planning/moveit_ros/blob/jade-devel/manipulation/pick_place/src/place.cpp#L64 # More details on this issue: https://github.com/ros-planning/moveit_ros/issues/577 acobjs = self.scene.get_attached_objects([target_id]) aco_pose = self.get_pose(acobjs[target_id]) if aco_pose is None: rospy.logerr( "Attached collision object '%s' not found" % target_id) return None aco_tf = self.pose_to_mat(aco_pose) place_tf = self.pose_to_mat(place.pose) place.pose = self.mat_to_pose(place_tf, aco_tf) rospy.logdebug("Compensate place pose with the attached object pose [%s]. Results: [%s]" \ % (aco_pose, place.pose)) # Append this place pose to the list places.append(deepcopy(place)) # Return the list return places # Set the color of an object def setColor(self, name, r, g, b, a=0.9): # Initialize a MoveIt color object color = ObjectColor() # Set the id to the name given as an argument color.id = name # Set the rgb and alpha values given as input color.color.r = r color.color.g = g color.color.b = b color.color.a = a # Update the global color dictionary self.colors[name] = color # Actually send the colors to MoveIt! def sendColors(self): # Initialize a planning scene object p = PlanningScene() # Need to publish a planning scene diff p.is_diff = True # Append the colors from the global color dictionary for color in self.colors.values(): p.object_colors.append(color) # Publish the scene diff self.scene_pub.publish(p) def get_pose(self, co): # We get object's pose from the mesh/primitive poses; try first with the meshes if isinstance(co, CollisionObject): if co.mesh_poses: return co.mesh_poses[0] elif co.primitive_poses: return co.primitive_poses[0] else: rospy.logerr( "Collision object '%s' has no mesh/primitive poses" % co.id) return None elif isinstance(co, AttachedCollisionObject): if co.object.mesh_poses: return co.object.mesh_poses[0] elif co.object.primitive_poses: return co.object.primitive_poses[0] else: rospy.logerr( "Attached collision object '%s' has no mesh/primitive poses" % co.id) return None else: rospy.logerr("Input parameter is not a collision object") return None def pose_to_mat(self, pose): '''Convert a pose message to a 4x4 numpy matrix. Args: pose (geometry_msgs.msg.Pose): Pose rospy message class. Returns: mat (numpy.matrix): 4x4 numpy matrix ''' quat = [ pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w ] pos = np.matrix([pose.position.x, pose.position.y, pose.position.z]).T mat = np.matrix(quaternion_matrix(quat)) mat[0:3, 3] = pos return mat def mat_to_pose(self, mat, transform=None): '''Convert a homogeneous matrix to a Pose message, optionally premultiply by a transform. Args: mat (numpy.ndarray): 4x4 array (or matrix) representing a homogenous transform. transform (numpy.ndarray): Optional 4x4 array representing additional transform Returns: pose (geometry_msgs.msg.Pose): Pose message representing transform. ''' if transform != None: mat = np.dot(mat, transform) pose = Pose() pose.position.x = mat[0, 3] pose.position.y = mat[1, 3] pose.position.z = mat[2, 3] quat = quaternion_from_matrix(mat) pose.orientation.x = quat[0] pose.orientation.y = quat[1] pose.orientation.z = quat[2] pose.orientation.w = quat[3] return pose
class PickAndPlace: def setColor(self, name, r, g, b, a=0.9): color = ObjectColor() color.id = name color.color.r = r color.color.g = g color.color.b = b color.color.a = a self.colors[name] = color def sendColors(self): p = PlanningScene() p.is_diff = True for color in self.colors.values(): p.object_colors.append(color) self.scene_pub.publish(p) def add_point(self, traj, time, positions, velocities=None): point = trajectory_msgs.msg.JointTrajectoryPoint() point.positions = copy.deepcopy(positions) if velocities is not None: point.velocities = copy.deepcopy(velocities) point.time_from_start = rospy.Duration(time) traj.points.append(point) def FollowQTraj(self, q_traj, t_traj): assert (len(q_traj) == len(t_traj)) #Insert current position to beginning. if t_traj[0] > 1.0e-2: t_traj.insert(0, 0.0) q_traj.insert(0, self.Q(arm=arm)) self.dq_traj = self.QTrajToDQTraj(q_traj, t_traj) def QTrajToDQTraj(self, q_traj, t_traj): dof = len(q_traj[0]) #Modeling the trajectory with spline. splines = [TCubicHermiteSpline() for d in range(dof)] for d in range(len(splines)): data_d = [[t, q[d]] for q, t in zip(q_traj, t_traj)] splines[d].Initialize(data_d, tan_method=splines[d].CARDINAL, c=0.0, m=0.0) #NOTE: We don't have to make spline models as we just want velocities at key points. # They can be obtained by computing tan_method, which will be more efficient. with_tan=True dq_traj = [] for t in t_traj: dq = [splines[d].Evaluate(t, with_tan=True)[1] for d in range(dof)] dq_traj.append(dq) #print dq_traj return dq_traj def JointNames(self): #0arm= 0 return self.joint_names[0] def ROSGetJTP(self, q, t, dq=None): jp = trajectory_msgs.msg.JointTrajectoryPoint() jp.positions = q jp.time_from_start = rospy.Duration(t) if dq is not None: jp.velocities = dq return jp def ToROSTrajectory(self, joint_names, q_traj, t_traj, dq_traj=None): assert (len(q_traj) == len(t_traj)) if dq_traj is not None: (len(dq_traj) == len(t_traj)) #traj= trajectory_msgs.msg.JointTrajectory() self.traj.joint_names = joint_names if dq_traj is not None: self.traj.points = [ self.ROSGetJTP(q, t, dq) for q, t, dq in zip(q_traj, t_traj, dq_traj) ] else: self.traj.points = [ self.ROSGetJTP(q, t) for q, t in zip(q_traj, t_traj) ] self.traj.header.stamp = rospy.Time.now() #print self.traj return self.traj def SmoothQTraj(self, q_traj): if len(q_traj) == 0: return q_prev = np.array(q_traj[0]) q_offset = np.array([0] * len(q_prev)) for q in q_traj: q_diff = np.array(q) - q_prev for d in range(len(q_prev)): if q_diff[d] < -math.pi: q_offset[d] += 1 elif q_diff[d] > math.pi: q_offset[d] -= 1 q_prev = copy.deepcopy(q) q[:] = q + q_offset * 2.0 * math.pi def add_target(self, target_pose, target_size, frame, x, y, o1, o2, o3, o4): target_pose.header.frame_id = frame target_pose.pose.position.x = x target_pose.pose.position.y = y target_pose.pose.position.z = self.table_ground + self.table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.x = o1 target_pose.pose.orientation.y = o2 target_pose.pose.orientation.z = o3 target_pose.pose.orientation.w = o4 #self.scene.add_box(f_target_id,f_target_pose,f_target_size) def cts(self, start_pose, mid_pose, end_pose, maxtries, exe_signal=False): waypoints = [] fraction = 0.0 attempts = 0 waypoints.append(start_pose.pose) if mid_pose != 0: waypoints.append(mid_pose.pose) waypoints.append(end_pose.pose) while fraction != 1 and attempts < maxtries: (plan, fraction) = self.arm.compute_cartesian_path( waypoints, 0.005, 0.0, True) attempts += 1 if (attempts % maxtries == 0 and fraction != 1): rospy.loginfo("path planning failed with " + str(fraction * 100) + "% success.") return 0, 0 continue elif fraction == 1: rospy.loginfo("path compute successfully with " + str(attempts) + " attempts.") if exe_signal: q_traj = [self.arm.get_current_joint_values()] t_traj = [0.0] for i in range(2, len(plan.joint_trajectory.points)): q_traj.append( plan.joint_trajectory.points[i].positions) t_traj.append(t_traj[-1] + 0.07) self.FollowQTraj(q_traj, t_traj) self.sub_jpc.publish( self.ToROSTrajectory(self.JointNames(), q_traj, t_traj, self.dq_traj)) rospy.sleep(5) end_joint_state = plan.joint_trajectory.points[-1].positions signal = 1 return signal, end_joint_state #move and rotate def cts_rotate(self, start_pose, end_pose, angle_r, maxtries, exe_signal=False): angle = angle_r * 3.14 / 180.0 waypoints = [] fraction = 0.0 attempts = 0 waypoints.append(start_pose.pose) waypoints.append(end_pose.pose) while fraction != 1 and attempts < maxtries: (plan, fraction) = self.arm.compute_cartesian_path( waypoints, 0.005, 0.0, True) attempts += 1 if (attempts % maxtries == 0 and fraction != 1): rospy.loginfo("path planning failed with " + str(fraction * 100) + "% success.") return 0, 0.0 continue elif fraction == 1: rospy.loginfo("path compute successfully with " + str(attempts) + " attempts.") if exe_signal: q_traj = [self.arm.get_current_joint_values()] t_traj = [0.0] per_angle = angle / (len(plan.joint_trajectory.points) - 2) for i in range(2, len(plan.joint_trajectory.points)): joint_inc_list = [ j for j in plan.joint_trajectory.points[i].positions ] #plan.joint_trajectory.points[i].positions[6]-=per_angle*(i-1) joint_inc_list[6] -= per_angle * (i - 1) q_traj.append(joint_inc_list) t_traj.append(t_traj[-1] + 0.05) self.FollowQTraj(q_traj, t_traj) self.sub_jpc.publish( self.ToROSTrajectory(self.JointNames(), q_traj, t_traj, self.dq_traj)) rospy.sleep(5) end_joint_state = plan.joint_trajectory.points[-1].positions signal = 1 return signal, end_joint_state # shaking function: # freq : shaking freqence # times : shaking time per action def shaking(self, initial_state, end_joint_state, freq, times): q_traj = [initial_state] t_traj = [0.0] for i in range(times): q_traj.append(end_joint_state) t_traj.append(t_traj[-1] + 0.5 / freq) q_traj.append(initial_state) t_traj.append(t_traj[-1] + 0.5 / freq) self.FollowQTraj(q_traj, t_traj) self.sub_jpc.publish( self.ToROSTrajectory(self.JointNames(), q_traj, t_traj, self.dq_traj)) rospy.sleep(6) #shaking_a: vertical bottle axis def shake_a(self, pre_p_angle, r_angle, amp): start_shake_pose = self.arm.get_current_pose( self.arm_end_effector_link) # for trajectory of shaking start_joint_state = self.arm.get_current_joint_values( ) # for state[6] to rotate shift_pose = deepcopy(start_shake_pose) r_angle = (r_angle / 180.0) * 3.14 pre_p_angle = (pre_p_angle / 180.0) * 3.14 shift_pose.pose.position.x += amp * math.sin(r_angle) * math.cos( pre_p_angle) # in verticle direction shift_pose.pose.position.y -= amp * math.sin(r_angle) * math.sin( pre_p_angle) shift_pose.pose.position.z += amp * math.cos(r_angle) #... signal, end_joint_state = self.cts(start_shake_pose, shift_pose, 300) return signal, end_joint_state def shake_b(self, pre_p_angle, r_angle, amp): start_shake_pose = self.arm.get_current_pose( self.arm_end_effector_link) # for trajectory of shaking start_joint_state = self.arm.get_current_joint_values( ) # for state[6] to rotate shift_pose = deepcopy(start_shake_pose) r_angle = (r_angle / 180.0) * 3.14 pre_p_angle = (pre_p_angle / 180.0) * 3.14 shift_pose.pose.position.x -= amp * math.cos(r_angle) * math.cos( pre_p_angle) # in verticle direction shift_pose.pose.position.y += amp * math.cos(r_angle) * math.sin( pre_p_angle) shift_pose.pose.position.z += amp * math.sin(r_angle) #... signal, end_joint_state = self.cts(start_shake_pose, shift_pose, 300) return signal, end_joint_state def setupSence(self): r_tool_size = [0.03, 0.02, 0.18] l_tool_size = [0.03, 0.02, 0.18] #real scene table table_pose = PoseStamped() table_pose.header.frame_id = self.reference_frame table_pose.pose.position.x = -0.0 table_pose.pose.position.y = 0.65 table_pose.pose.position.z = self.table_ground + self.table_size[ 2] / 2.0 table_pose.pose.orientation.w = 1.0 self.scene.add_box(self.table_id, table_pose, self.table_size) #left gripper l_p = PoseStamped() l_p.header.frame_id = self.arm_end_effector_link l_p.pose.position.x = 0.00 l_p.pose.position.y = 0.057 l_p.pose.position.z = 0.09 l_p.pose.orientation.w = 1 self.scene.attach_box(self.arm_end_effector_link, self.l_id, l_p, l_tool_size) #right gripper r_p = PoseStamped() r_p.header.frame_id = self.arm_end_effector_link r_p.pose.position.x = 0.00 r_p.pose.position.y = -0.057 r_p.pose.position.z = 0.09 r_p.pose.orientation.w = 1 self.scene.attach_box(self.arm_end_effector_link, self.r_id, r_p, r_tool_size) #Params: pose of bottle, grasp_radius, grasp_height, grasp_theta def get_grasp_pose(self, pose, r, theta): g_p = PoseStamped() g_p.header.frame_id = self.arm_end_effector_link g_p.pose.position.x = pose.pose.position.x + r * math.sin(theta) g_p.pose.position.y = pose.pose.position.y - r * math.cos(theta) g_p.pose.position.z = pose.pose.position.z g_p.pose.orientation.w = 0.5 * (math.cos(0.5 * theta) - math.sin(0.5 * theta)) g_p.pose.orientation.x = -0.5 * (math.cos(0.5 * theta) + math.sin(0.5 * theta)) g_p.pose.orientation.y = 0.5 * (math.cos(0.5 * theta) - math.sin(0.5 * theta)) g_p.pose.orientation.z = 0.5 * (math.sin(0.5 * theta) + math.cos(0.5 * theta)) return g_p def get_pour_pose(self, pose, h, r, theta): p_p = PoseStamped() p_p.header.frame_id = self.arm_end_effector_link p_p.pose.position.x = pose.pose.position.x - r * math.cos(theta) p_p.pose.position.y = pose.pose.position.y + r * math.sin(theta) p_p.pose.position.z = pose.pose.position.z + h theta *= -1 p_p.pose.orientation.w = 0.5 * (math.cos(0.5 * theta) - math.sin(0.5 * theta)) p_p.pose.orientation.x = -0.5 * (math.cos(0.5 * theta) + math.sin(0.5 * theta)) p_p.pose.orientation.y = 0.5 * (math.cos(0.5 * theta) - math.sin(0.5 * theta)) p_p.pose.orientation.z = 0.5 * (math.sin(0.5 * theta) + math.cos(0.5 * theta)) return p_p def pour_rotate(self, angle_pre, angle_r, r, maxtries): angle_pre = (angle_pre / 180.0) * 3.14 angle_r_1 = (angle_r / 180.0) * 3.14 initial_state = self.arm.get_current_joint_values() initial_pose = self.arm.get_current_pose(self.arm_end_effector_link) final_pose = deepcopy(initial_pose) final_pose.pose.position.x += r * ( 1 - math.cos(angle_r_1)) * math.cos(angle_pre) final_pose.pose.position.y += r * ( 1 - math.cos(angle_r_1)) * math.sin(angle_pre) final_pose.pose.position.z += r * math.sin(angle_r_1) signal, e_j_s = self.cts_rotate(initial_pose, final_pose, angle_r, maxtries, True) return signal def pg_g_pp(self, pose, r, pre_r): start_pose = self.arm.get_current_pose(self.arm_end_effector_link) p_i_radian = np.arctan(abs(pose.pose.position.x / pose.pose.position.y)) p_i_angle = p_i_radian * 180.0 / 3.14 pick_list = [ 0.0, p_i_angle, 5.0, 25.0, 45.0, 65.0, 15.0, 35.0, 55.0, 75.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0 ] for i in range(len(pick_list)): theta = (pick_list[i] / 180.0) * 3.14 if pose.pose.position.x > 0: theta *= -1.0 pre_grasp_pose = self.get_grasp_pose(pose, r + pre_r, theta) #pick up grasp_pose = pre_grasp_pose grasp_pose.pose.position.x -= pre_r * math.sin(theta) grasp_pose.pose.position.y += pre_r * math.cos(theta) signal, e_j_s = self.cts(start_pose, pre_grasp_pose, grasp_pose, 300, True) if signal == 0: continue break rospy.sleep(1) self.gripperCtrl(0) rospy.sleep(2) #move to ori_pose current_pose = self.arm.get_current_pose(self.arm_end_effector_link) signal, e_j_s = self.cts(current_pose, pre_grasp_pose, start_pose, 300, True) rospy.sleep(2) rospy.loginfo("Grasping done.") return start_pose, pre_grasp_pose, grasp_pose def pp_ps(self, target_pose, pour_angle, r_pour, h_pour): for i in range(len(pour_angle)): maxtries = 300 start_pose = self.arm.get_current_pose(self.arm_end_effector_link) theta = (pour_angle[i] / 180.0) * 3.14 pour_pose = self.get_pour_pose(target_pose, h_pour, r_pour, theta) #move to pose signal_1, e_j_s = self.cts_rotate(start_pose, pour_pose, 90.0, maxtries, True) if signal_1 == 0: continue pre_pour_angle = pour_angle[i] rospy.loginfo("Ready for pouring.") return pre_pour_angle def go_back(self, ori_pose, pre_grasp_pose, grasp_pose): cur_pose = self.arm.get_current_pose(self.arm_end_effector_link) signal, e1 = self.cts(cur_pose, 0, ori_pose, 300, True) rospy.loginfo("back to pre_grasp pose, ready for placing bottle..") signal_1, e2 = self.cts(ori_pose, pre_grasp_pose, grasp_pose, 300, True) rospy.loginfo("back to grasp pose, open gripper..") self.gripperCtrl(255) rospy.sleep(1) signal_2, e3 = self.cts(grasp_pose, pre_grasp_pose, ori_pose, 300, True) rospy.loginfo("back to pre_grasp pose, ready for next kind of source.") def rotate_back(self, angle): angle = angle * 3.14 / 180.0 current_j_state = self.arm.get_current_joint_values() current_j_state[6] += angle + 1.57 self.arm.go() def last_step_go_back(self, ori_pose): cur_pose = self.arm.get_current_pose(self.arm_end_effector_link) signal, e1 = self.cts(cur_pose, 0, ori_pose, 300, True) rospy.loginfo("back to last step...") rospy.sleep(1) def __init__(self): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') self.scene = PlanningSceneInterface() pub_traj = rospy.Publisher('/joint_path_command', trajectory_msgs.msg.JointTrajectory, queue_size=10) #pub_ratio_sig= rospy.Publisher('/enable_source_change',Int64,queue_size=1) self.scene_pub = rospy.Publisher('planning_scene', PlanningScene) self.gripperCtrl = rospy.ServiceProxy( "/two_finger/gripper/gotoPositionUntilTouch", SetPosition) self.colors = dict() rospy.sleep(1) self.robot = moveit_commander.robot.RobotCommander() self.arm = MoveGroupCommander('arm') self.arm.allow_replanning(True) cartesian = rospy.get_param('~cartesian', True) self.arm_end_effector_link = self.arm.get_end_effector_link() self.arm.set_goal_position_tolerance(0.005) self.arm.set_goal_orientation_tolerance(0.025) self.arm.allow_replanning(True) self.reference_frame = 'base_link' self.arm.set_pose_reference_frame(self.reference_frame) self.arm.set_planning_time(5) #shaking self.joint_names = [[]] self.joint_names[0] = rospy.get_param('controller_joint_names') self.traj = trajectory_msgs.msg.JointTrajectory() self.sub_jpc = rospy.Publisher('/joint_path_command', trajectory_msgs.msg.JointTrajectory, queue_size=10) #scene planning self.l_id = 'l_tool' self.r_id = 'r_tool' self.table_id = 'table' self.target1_id = 'target1_object' self.target2_id = 'target2_object' self.target3_id = 'target3_object' self.target4_id = 'target4_object' self.f_target_id = 'receive_container' self.scene.remove_world_object(self.l_id) self.scene.remove_world_object(self.r_id) self.scene.remove_world_object(self.table_id) self.scene.remove_world_object(self.target1_id) self.scene.remove_world_object(self.target2_id) self.scene.remove_world_object(self.target3_id) self.scene.remove_world_object(self.target4_id) self.scene.remove_world_object(self.f_target_id) #self.scene.remove_attached_object(self.arm_end_effector_link,self.target_id) self.table_ground = 0.13 self.table_size = [0.9, 0.6, 0.018] self.setupSence() target1_size = [0.035, 0.035, 0.19] target2_size = target1_size target3_size = target1_size target4_size = target1_size self.f_target_size = [0.2, 0.2, 0.04] f_target_pose = PoseStamped() pre_pour_pose = PoseStamped() target1_pose = PoseStamped() target2_pose = PoseStamped() target3_pose = PoseStamped() target4_pose = PoseStamped() joint_names = [ 'joint_' + jkey for jkey in ('s', 'l', 'e', 'u', 'r', 'b', 't') ] joint_names = rospy.get_param('controller_joint_names') traj = trajectory_msgs.msg.JointTrajectory() traj.joint_names = joint_names #final target #self.add_target(f_target_pose,self.f_target_size,self.reference_frame,-0.184+0.27,0.62+0.1,0,0,0,1) self.add_target(f_target_pose, self.f_target_size, self.reference_frame, 0.2, 0.6, 0, 0, 0, 1) self.scene.add_box(self.f_target_id, f_target_pose, self.f_target_size) #self.add_target(pre_pour_pose,self.reference_frame,x,y,0,0,0,1) #target localization #msg = rospy.wait_for_message('/aruco_single/pose',PoseStamped) self.add_target(target1_pose, target1_size, self.reference_frame, -0.25, 0.8, 0, 0, 0, 1) self.scene.add_box(self.target1_id, target1_pose, target1_size) self.add_target(target2_pose, target2_size, self.reference_frame, -0.12, 0.87, 0, 0, 0, 1) self.scene.add_box(self.target2_id, target2_pose, target2_size) self.add_target(target3_pose, target3_size, self.reference_frame, 0.02, 0.88, 0, 0, 0, 1) self.scene.add_box(self.target3_id, target3_pose, target3_size) self.add_target(target4_pose, target4_size, self.reference_frame, 0.15, 0.80, 0, 0, 0, 1) self.scene.add_box(self.target4_id, target4_pose, target4_size) #attach_pose g_p = PoseStamped() g_p.header.frame_id = self.arm_end_effector_link g_p.pose.position.x = 0.00 g_p.pose.position.y = -0.00 g_p.pose.position.z = 0.025 g_p.pose.orientation.w = 0.707 g_p.pose.orientation.x = 0 g_p.pose.orientation.y = -0.707 g_p.pose.orientation.z = 0 #set color self.setColor(self.target1_id, 0.8, 0, 0, 1.0) self.setColor(self.target2_id, 0.8, 0, 0, 1.0) self.setColor(self.target3_id, 0.8, 0, 0, 1.0) self.setColor(self.target4_id, 0.8, 0, 0, 1.0) self.setColor(self.f_target_id, 0.8, 0.3, 0, 1.0) self.setColor('r_tool', 0.8, 0, 0) self.setColor('l_tool', 0.8, 0, 0) self.sendColors() self.gripperCtrl(255) rospy.sleep(3) self.arm.set_named_target("initial_arm") self.arm.go() rospy.sleep(3) #j_ori_state=[-1.899937629699707, -0.5684762597084045, 0.46537330746650696, 2.3229329586029053, -0.057941947132349014, -1.2867668867111206, 0.2628822326660156] #j_ori_state=[-2.161055326461792, -0.6802523136138916, -1.7733728885650635, -2.3315746784210205, -0.5292841196060181, 1.4411976337432861, -2.2327845096588135] j_ori_state = [ -1.2628753185272217, -0.442996621131897, -0.1326361745595932, 2.333048105239868, -0.15598002076148987, -1.2167049646377563, 3.1414425373077393 ] #signal= True self.arm.set_joint_value_target(j_ori_state) self.arm.go() rospy.sleep(3) #parameter setup tar_num = 4 maxtries = 300 r_grasp = 0.15 r_pre_g = 0.1 r_bottle = 0.1 for i in range(0, tar_num): #grasp target rospy.loginfo("Choosing source...") if i == 0: target_pose = target1_pose target_id = self.target1_id target_size = target1_size amp = 0.1 freq = 2.75 r_angle = 45.0 elif i == 1: target_pose = target2_pose target_id = self.target2_id target_size = target2_size amp = 0.15 freq = 2.0 r_angle = 30.0 elif i == 2: target_pose = target3_pose target_id = self.target3_id target_size = target3_size amp = 0.1 freq = 2.75 r_angle = 45.0 elif i == 3: target_pose = target4_pose target_id = self.target4_id target_size = target4_size amp = 0.1 freq = 2.75 r_angle = 45.0 r_pour = 0.1 h_pour = 0.1 #pour_angle=[15.0,30.0,45.0,60.0,75.0] pour_angle = [ 0.0, -15.0, -10.0, -5.0, 0.0, 10.0, 15.0, 30.0, 45.0, 60.0, 75.0 ] rospy.loginfo("Params loaded.") rospy.loginfo("Current Source: " + str(i + 1) + " ") #grasp and back ori_pose, mid_pose, g_pose = self.pg_g_pp(target_pose, r_grasp, r_pre_g) #move to target position for pouring pre_p_angle = self.pp_ps(f_target_pose, pour_angle, r_pour, h_pour) rospy.loginfo("pre_pour_angle : " + str(pre_p_angle)) #rotation and shaking ps_signal = self.pour_rotate(pre_p_angle, r_angle, r_bottle, maxtries) if ps_signal != 1: rospy.loginfo( "Pre_shaking_rotation failed, back to ori_pose...") self.last_step_go_back(ori_pose) rospy.sleep(3) continue else: rospy.loginfo("Shaking planning...") shake_per_times = 3 shake_times = 0 shake_times_tgt = 1 signal = True rospy.loginfo("Parameter loaded") rospy.sleep(1) signal, end_joint_state = self.shake_a(pre_p_angle, r_angle, amp) while signal == 1: #area_ratio= rospy.wait_for_message('/color_area_ratio',Float64) #if (area_ratio>ratio_table[i]) or (shake_times>shake_times_tgt): if (shake_times < shake_times_tgt): self.shaking(start_joint_state, end_joint_state, freq, shake_per_times) shake_times += 1 rospy.loginfo("shaking times : " + str(shake_times) + " .") else: signal = 0 self.rotate_back(r_angle) self.go_back(ori_pose, mid_pose, g_pose) rospy.sleep(2) continue #remove and shut down self.scene.remove_attached_object(self.arm_end_effector_link, 'l_tool') self.scene.remove_attached_object(self.arm_end_effector_link, 'r_tool') moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
class Pick_and_Place: def __init__(self): self.scene = PlanningSceneInterface() self.robot = RobotCommander() self.arm = MoveGroupCommander("arm") rospy.sleep(1) #remove existing objects self.scene.remove_world_object() self.scene.remove_attached_object("endeff", "part") rospy.sleep(5) ''' # publish a demo scene self.pos = PoseStamped() self.pos.header.frame_id = "world" # add wall in between self.pos.pose.position.x = -0.14 self.pos.pose.position.y = 0.02 self.pos.pose.position.z = 0.09 self.scene.add_box("wall", pos, (0.06, 0.01, 0.18)) # add an object to be grasped self.pos.pose.position.x = -0.14 self.pos.pose.position.y = -0.0434 self.pos.pose.position.z = 0.054 ''' self.g=Grasp() self.g.pre_grasp_approach.direction.vector.z= 1 self.g.pre_grasp_approach.direction.header.frame_id = 'endeff' self.g.pre_grasp_approach.min_distance = 0.04 self.g.pre_grasp_approach.desired_distance = 0.10 self.g.grasp_posture = self.make_gripper_posture(0) self.g.post_grasp_retreat.direction.vector.z= -1 self.g.post_grasp_retreat.direction.header.frame_id = 'endeff' self.g.post_grasp_retreat.min_distance = 0.04 self.g.post_grasp_retreat.desired_distance = 0.10 self.g.allowed_touch_objects = ["part"] self.p=PlaceLocation() self.p.place_pose.header.frame_id= 'world' self.p.place_pose.pose.position.x= -0.13341 self.p.place_pose.pose.position.y= 0.12294 self.p.place_pose.pose.position.z= 0.099833 self.p.place_pose.pose.orientation.x= 0 self.p.place_pose.pose.orientation.y= 0 self.p.place_pose.pose.orientation.z= 0 self.p.place_pose.pose.orientation.w= 1 self.p.pre_place_approach.direction.vector.z= 1 self.p.pre_place_approach.direction.header.frame_id = 'endeff' self.p.pre_place_approach.min_distance = 0.06 self.p.pre_place_approach.desired_distance = 0.12 self.p.post_place_posture= self.make_gripper_posture(-1.1158) self.p.post_place_retreat.direction.vector.z= -1 self.p.post_place_retreat.direction.header.frame_id = 'endeff' self.p.post_place_retreat.min_distance = 0.05 self.p.post_place_retreat.desired_distance = 0.06 self.p.allowed_touch_objects=["part"] self._as = actionlib.SimpleActionServer("server_test", TwoIntsAction, execute_cb=self.execute_pick_place, auto_start = False) self._as.start() # Get the gripper posture as a JointTrajectory def make_gripper_posture(self,pose): t = JointTrajectory() t.joint_names = ['joint6'] tp = JointTrajectoryPoint() tp.positions = [pose for j in t.joint_names] #tp.effort = GRIPPER_EFFORT t.points.append(tp) return t def execute_pick_place(self,g): res= TwoIntsResult() obj_pos = PoseStamped() obj_pos.header.frame_id = "world" obj_pos.pose.position.x = -g.a*0.01 obj_pos.pose.position.y = -g.b*0.01 obj_pos.pose.position.z = 0.054 #msg.z-0.02 self.scene.add_box("part", obj_pos, (0.02, 0.02, 0.02)) rospy.sleep(2) tar_pose = PoseStamped() tar_pose.header.frame_id = 'world' tar_pose.pose.position.x = -g.a*0.01 #-0.14 tar_pose.pose.position.y = -g.b*0.01 #-0.0434 tar_pose.pose.position.z = 0.074 #msg.z tar_pose.pose.orientation.x = -0.076043 tar_pose.pose.orientation.y = 0.99627 tar_pose.pose.orientation.z = -0.00033696 tar_pose.pose.orientation.w = -0.028802 self.g.grasp_pose=tar_pose grasps = [] grasps.append(copy.deepcopy(self.g)) result=-1 attempt=0 while result < 0 and attempt <= 150: result=self.arm.pick("part", grasps) print "Attempt:", attempt print "pick result: ", result attempt+=1 if result < 0: print "Pick Failed" else: print "Pick Success" result=False attempt=0 while result == False and attempt <= 150: result=self.arm.place("part", self.p) print "Attempt:", attempt attempt+=1 if result == False: print "Place Failed" #else: # print "Place Success" self.arm.set_named_target("Home") self.arm.go() res.sum=1 rospy.sleep(1) self._as.set_succeeded(res)
def __init__(self): # 初始化move_group的API moveit_commander.roscpp_initialize(sys.argv) # 初始化ROS节点 rospy.init_node('moveit_attached_object_demo') # 初始化场景对象 scene = PlanningSceneInterface() rospy.sleep(1) # 初始化需要使用move group控制的机械臂中的arm group arm = MoveGroupCommander('manipulator') # 获取终端link的名称 end_effector_link = arm.get_end_effector_link() # 设置位置(单位:米)和姿态(单位:弧度)的允许误差 arm.set_goal_position_tolerance(0.01) arm.set_goal_orientation_tolerance(0.05) # 当运动规划失败后,允许重新规划 arm.allow_replanning(True) # 控制机械臂回到初始化位置 arm.set_named_target('home') arm.go() # 设置每次运动规划的时间限制:10s arm.set_planning_time(10) # 移除场景中之前运行残留的物体 scene.remove_attached_object(end_effector_link, 'tool') scene.remove_world_object('table') # 设置桌面的高度 table_ground = 0.7 # 设置table和tool的三维尺寸 table_size = [0.1, 0.3, 0.02] tool_size = [0.2, 0.02, 0.02] # 设置tool的位姿 p = PoseStamped() p.header.frame_id = end_effector_link p.pose.position.x = tool_size[0] / 2.0 p.pose.position.z = -0.015 p.pose.orientation.w = 1 # 将tool附着到机器人的终端 scene.attach_box(end_effector_link, 'tool', p, tool_size) # 将table加入场景当中 table_pose = PoseStamped() table_pose.header.frame_id = 'base_link' table_pose.pose.position.x = 0.4 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] table_pose.pose.orientation.w = 1.0 scene.add_box('table', table_pose, table_size) rospy.sleep(2) # 更新当前的位姿 arm.set_start_state_to_current_state() # 设置机械臂的目标位置,使用六轴的位置数据进行描述(单位:弧度) joint_positions = [ -0.5110620856285095, 0.32814791798591614, 0.5454912781715393, 1.0146701335906982, 0.8498637080192566, -0.45695754885673523 ] arm.set_joint_value_target(joint_positions) # 控制机械臂完成运动 arm.go() rospy.sleep(1) # 控制机械臂回到初始化位置 arm.set_named_target('home') arm.go() moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
def __init__(self): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') scene=PlanningSceneInterface() self.scene_pub=rospy.Publisher('planning_scene',PlanningScene) self.colors=dict() rospy.sleep(1) self.arm=MoveGroupCommander('arm') cartesian=rospy.get_param('~cartesian',True) self.end_effector_link=self.arm.get_end_effector_link() self.arm.set_goal_position_tolerance(0.005) self.arm.set_goal_orientation_tolerance(0.025) self.arm.allow_replanning(True) self.reference_frame='base_link' self.arm.set_pose_reference_frame(self.reference_frame) self.arm.set_planning_time(5) #scene planning table_id='table' #cylinder_id='cylinder' #box1_id='box1' box2_id='box2' target_id='target_object' #scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(table_id) scene.remove_world_object(target_id) rospy.sleep(2) table_ground=0.20 table_size=[1,0.5,0.01] #box1_size=[0.1,0.05,0.03] #box2_size=[0.05,0.05,0.1] r_tool_size=[0.03,0.01,0.06] l_tool_size=[0.03,0.01,0.06] target_size=[0.03,0.03,0.1] table_pose=PoseStamped() table_pose.header.frame_id=self.reference_frame table_pose.pose.position.x=0 table_pose.pose.position.y=0.75 table_pose.pose.position.z=table_ground+table_size[2]/2.0 table_pose.pose.orientation.w=1.0 scene.add_box(table_id,table_pose,table_size) ''' box1_pose=PoseStamped() box1_pose.header.frame_id=reference_frame box1_pose.pose.position.x=0.7 box1_pose.pose.position.y=-0.2 box1_pose.pose.position.z=table_ground+table_size[2]+box1_size[2]/2.0 box1_pose.pose.orientation.w=1.0 scene.add_box(box1_id,box1_pose,box1_size) box2_pose=PoseStamped() box2_pose.header.frame_id=self.reference_frame box2_pose.pose.position.x=0.6 box2_pose.pose.position.y=-0.05 box2_pose.pose.position.z=table_ground+table_size[2]+box2_size[2]/2.0 box2_pose.pose.orientation.w=1.0 scene.add_box(box2_id,box2_pose,box2_size) ''' #left gripper l_p=PoseStamped() l_p.header.frame_id=self.end_effector_link l_p.pose.position.x=0.00 l_p.pose.position.y=0.04 l_p.pose.position.z=0.04 l_p.pose.orientation.w=1 scene.attach_box(self.end_effector_link,'l_tool',l_p,l_tool_size) #right gripper r_p=PoseStamped() r_p.header.frame_id=self.end_effector_link r_p.pose.position.x=0.00 r_p.pose.position.y=-0.04 r_p.pose.position.z=0.04 r_p.pose.orientation.w=1 scene.attach_box(self.end_effector_link,'r_tool',r_p,r_tool_size) #target target_pose=PoseStamped() target_pose.header.frame_id=self.reference_frame target_pose.pose.position.x=-0.4 target_pose.pose.position.y=0.65 target_pose.pose.position.z=table_ground+table_size[2]+target_size[2]/2.0 target_pose.pose.orientation.x=0 target_pose.pose.orientation.y=0 target_pose.pose.orientation.z=0 target_pose.pose.orientation.w=1 scene.add_box(target_id,target_pose,target_size) #grasp #grasp_pose(self,x,y,z,r,theta) #set color self.setColor(table_id,0.8,0,0,1.0) #self.setColor(box1_id,0.8,0.4,0,1.0) self.setColor(box2_id,0.8,0.4,0,1.0) self.setColor('r_tool',0.8,0,0) self.setColor('l_tool',0.8,0,0) self.setColor('target_object',0,1,0) self.sendColors() #motion planning j_ori_state=[-1.899937629699707, -0.5684762597084045, 0.46537330746650696, 2.3229329586029053, -0.057941947132349014, -1.2867668867111206, 0.2628822326660156] self.arm.set_joint_value_target(j_ori_state) self.arm.go() rospy.sleep(3) r=0.06 maxtries=300 for theta in range(0,157,16): theta/=100.0 start_pose=self.arm.get_current_pose(self.end_effector_link) rospy.sleep(2) grasp_pose=self.grasp_pose(target_pose.pose.position.x,target_pose.pose.position.y,target_pose.pose.position.z,r,theta) if cartesian: (plan,e_j_state,s)=self.cts(start_pose.pose,grasp_pose.pose,maxtries) if s==0: continue #print(plan.joint_trajectory.points) #self.arm.set_joint_value_target(e_j_state) #self.arm.go() self.arm.execute(plan) rospy.sleep(5) #self.arm.set_named_target("initial_arm") #self.arm.go() #rospy.sleep(2) #remove and shut down scene.remove_attached_object(self.end_effector_link,'l_tool') scene.remove_attached_object(self.end_effector_link,'r_tool') moveit_commander.roscpp_shutdown() moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=5) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=5) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the right arm right_arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the move group for the right gripper right_gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = right_arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) right_arm.set_goal_position_tolerance(0.05) right_arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution right_arm.allow_replanning(True) # Set the right arm reference frame right_arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt right_arm.set_planning_time(60) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name table_id = 'table' box1_id = 'box1' box2_id = 'box2' target_id = 'target' tool_id = 'tool' # Remove leftover objects from a previous run scene.remove_world_object(table_id) scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(target_id) scene.remove_world_object(tool_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "grasp" pose stored in the SRDF file right_arm.set_named_target('right_arm_up') right_arm.go() # Open the gripper to the neutral position right_gripper.set_joint_value_target(GRIPPER_OPEN) right_gripper.go() rospy.sleep(5) # Set the height of the table off the ground table_ground = 0.04 # Set the dimensions of the scene objects [l, w, h] table_size = [0.2, 0.7, 0.01] box1_size = [0.1, 0.05, 0.05] box2_size = [0.05, 0.05, 0.15] # Set the target size [l, w, h] target_size = [0.02, 0.01, 0.12] target_x = 0.135 #target_y = -0.32 target_y = -0.285290879999 # Add a table top and two boxes to the scene table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose.position.x = 0.25 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box(table_id, table_pose, table_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = target_x target_pose.pose.position.y = target_y target_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) # Make the table blue and the boxes orange self.setColor(table_id, 0, 0, 0.8, 1.0) self.setColor(box1_id, 0.8, 0.4, 0, 1.0) self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object right_arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.18 place_pose.pose.position.y = 0 place_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 p = PoseStamped() p.header.frame_id = "up1_footprint" p.pose.position.x = 0.12792118579 p.pose.position.y = -0.285290879999 p.pose.position.z = 0.120301181892 p.pose.orientation.x = 0.0 p.pose.orientation.y = 0.0 p.pose.orientation.z = -0.706825181105 p.pose.orientation.w = 0.707388269167 right_gripper.set_pose_target(p.pose) # pick an object right_arm.allow_replanning(True) right_arm.allow_looking(True) right_arm.set_goal_tolerance(0.05) right_arm.set_planning_time(60) print "arm grasp" success = 0 attempt = 0 while not success: p_plan = right_arm.plan() attempt = attempt + 1 print "Planning attempt: " + str(attempt) if p_plan.joint_trajectory.points != []: success = 1 print "arm grasp" right_arm.execute(p_plan) rospy.sleep(5) right_gripper.set_joint_value_target(GRIPPER_GRASP) right_gripper.go() print "gripper closed" rospy.sleep(5) scene.attach_box(GRIPPER_FRAME, target_id) print "object attached" right_arm.set_named_target('right_arm_up') right_arm.go() print "arm up" rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) # Initialize the ROS node rospy.init_node('moveit_demo', anonymous=True) # Construct the initial scene object scene = PlanningSceneInterface() rospy.sleep(1) # Connect to the right_arm move group right_arm = moveit_commander.MoveGroupCommander('arm') # Get the name of the end-effector link end_effector_link = right_arm.get_end_effector_link() # Display the name of the end_effector link rospy.loginfo("The end effector link is: " + str(end_effector_link)) # Set a small tolerance on joint angles right_arm.set_goal_joint_tolerance(0.001) right_arm.set_goal_position_tolerance(0.0001) scene.remove_world_object('block') # Start the arm target in "contract" pose stored in the SRDF file # right_arm.set_named_target('contract') # right_arm.go() # rospy.sleep(2) # Start the arm target in "right" pose stored in the SRDF file right_arm.set_named_target('right') # Plan a trajectory to the goal configuration traj = right_arm.plan() # Execute the planned trajectory right_arm.execute(traj) # Pause for a moment rospy.sleep(1) start_pose = right_arm.get_current_pose().pose waypoints = [] wpose = deepcopy(start_pose) waypoints.append(deepcopy(wpose)) wpose.position.x -= 0.2 waypoints.append(deepcopy(wpose)) wpose.position.y += 0.3 waypoints.append(deepcopy(wpose)) wpose.position.z -= 0.5 waypoints.append(deepcopy(wpose)) fraction = 0.0 maxtries = 100 attempts = 0 # Set the internal state to the current state right_arm.set_start_state_to_current_state() # Plan the Cartesian path connecting the waypoints while fraction < 1.0 and attempts < maxtries: (plan, fraction) = right_arm.compute_cartesian_path( waypoints, # waypoint poses 0.01, # eef_step 0.0, # jump_threshold True) # avoid_collisions # Increment the number of attempts attempts += 1 # Print out a progress message if attempts % 10 == 0: rospy.loginfo("Still trying after " + str(attempts) + " attempts...") # If we have a complete plan, execute the trajectory if fraction == 1.0: rospy.loginfo("Path computed successfully. Moving the arm.") right_arm.execute(plan) rospy.loginfo("Path execution complete.") else: rospy.loginfo("Path planning failed with only " + str(fraction) + " success after " + str(maxtries) + " attempts.") # Set the size of block block_size = [0.01, 0.05, 0.05] # Create a pose for the block relative to the end-effector p = PoseStamped() p.header.frame_id = end_effector_link # Place the end of the object within the grasp of the gripper p.pose.position.x = -0.015 p.pose.position.y = 0.0 p.pose.position.z = 0.0 # Align the object with the gripper (straight out) p.pose.orientation.x = 0 p.pose.orientation.y = 0 p.pose.orientation.z = 0 p.pose.orientation.w = 1 # Attach the tool to the end-effector scene.attach_box(end_effector_link, 'block', p, block_size) waypoints = [] start_pose = right_arm.get_current_pose().pose wpose = deepcopy(start_pose) waypoints.append(deepcopy(wpose)) wpose.position.z += 0.25 waypoints.append(deepcopy(wpose)) #wpose.position.y -= 0.30 #waypoints.append(deepcopy(wpose)) fraction = 0.0 maxtries = 100 attempts = 0 # Set the internal state to the current state right_arm.set_start_state_to_current_state() # Plan the Cartesian path connecting the waypoints while fraction < 1.0 and attempts < maxtries: (plan, fraction) = right_arm.compute_cartesian_path( waypoints, # waypoint poses 0.01, # eef_step 0.0, # jump_threshold True) # avoid_collisions # Increment the number of attempts attempts += 1 # Print out a progress message if attempts % 10 == 0: rospy.loginfo("Still trying after " + str(attempts) + " attempts...") # If we have a complete plan, execute the trajectory if fraction == 1.0: rospy.loginfo("Path computed successfully. Moving the arm.") right_arm.execute(plan) rospy.loginfo("Path execution complete.") else: rospy.loginfo("Path planning failed with only " + str(fraction) + " success after " + str(maxtries) + " attempts.") joint_positions = right_arm.get_current_joint_values() joint_positions[0] = -1.5707 right_arm.set_joint_value_target(joint_positions) right_arm.go() rospy.sleep(1) waypoints = [] start_pose = right_arm.get_current_pose().pose wpose = deepcopy(start_pose) waypoints.append(deepcopy(wpose)) wpose.position.z -= 0.25 waypoints.append(deepcopy(wpose)) fraction = 0.0 maxtries = 100 attempts = 0 # Set the internal state to the current state right_arm.set_start_state_to_current_state() # Plan the Cartesian path connecting the waypoints while fraction < 1.0 and attempts < maxtries: (plan, fraction) = right_arm.compute_cartesian_path( waypoints, # waypoint poses 0.01, # eef_step 0.0, # jump_threshold True) # avoid_collisions # Increment the number of attempts attempts += 1 # Print out a progress message if attempts % 10 == 0: rospy.loginfo("Still trying after " + str(attempts) + " attempts...") # If we have a complete plan, execute the trajectory if fraction == 1.0: rospy.loginfo("Path computed successfully. Moving the arm.") right_arm.execute(plan) rospy.loginfo("Path execution complete.") else: rospy.loginfo("Path planning failed with only " + str(fraction) + " success after " + str(maxtries) + " attempts.") scene.remove_attached_object(end_effector_link, 'block') rospy.sleep(1) waypoints = [] start_pose = right_arm.get_current_pose().pose wpose = deepcopy(start_pose) waypoints.append(deepcopy(wpose)) wpose.position.z += 0.15 waypoints.append(deepcopy(wpose)) #wpose.position.y -= 0.30 #waypoints.append(deepcopy(wpose)) fraction = 0.0 maxtries = 100 attempts = 0 # Set the internal state to the current state right_arm.set_start_state_to_current_state() # Plan the Cartesian path connecting the waypoints while fraction < 1.0 and attempts < maxtries: (plan, fraction) = right_arm.compute_cartesian_path( waypoints, # waypoint poses 0.01, # eef_step 0.0, # jump_threshold True) # avoid_collisions # Increment the number of attempts attempts += 1 # Print out a progress message if attempts % 10 == 0: rospy.loginfo("Still trying after " + str(attempts) + " attempts...") # If we have a complete plan, execute the trajectory if fraction == 1.0: rospy.loginfo("Path computed successfully. Moving the arm.") right_arm.execute(plan) rospy.loginfo("Path execution complete.") else: rospy.loginfo("Path planning failed with only " + str(fraction) + " success after " + str(maxtries) + " attempts.") rospy.sleep(1) joint_positions = right_arm.get_current_joint_values() joint_positions[0] = 0 joint_positions[4] = 0 joint_positions[5] = 0 right_arm.set_joint_value_target(joint_positions) right_arm.go() rospy.sleep(1) # Return the arm to the named "resting" pose stored in the SRDF file right_arm.set_named_target('right') right_arm.go() rospy.sleep(1) # Cleanly shut down MoveIt moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
def __init__(self): # Initialize the move_group API moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('moveit_demo') # Use the planning scene object to add or remove objects scene = PlanningSceneInterface() # Create a scene publisher to push changes to the scene self.scene_pub = rospy.Publisher('planning_scene', PlanningScene, queue_size=5) # Create a publisher for displaying gripper poses self.gripper_pose_pub = rospy.Publisher('gripper_pose', PoseStamped, queue_size=5) # Create a dictionary to hold object colors self.colors = dict() # Initialize the move group for the arm arm = MoveGroupCommander(GROUP_NAME_ARM) # Initialize the move group for the gripper gripper = MoveGroupCommander(GROUP_NAME_GRIPPER) # Get the name of the end-effector link end_effector_link = arm.get_end_effector_link() # Allow some leeway in position (meters) and orientation (radians) arm.set_goal_position_tolerance(0.05) arm.set_goal_orientation_tolerance(0.1) # Allow replanning to increase the odds of a solution arm.allow_replanning(True) # Set the right arm reference frame arm.set_pose_reference_frame(REFERENCE_FRAME) # Allow 5 seconds per planning attempt arm.set_planning_time(5) # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Set a limit on the number of place attempts max_place_attempts = 5 # Give the scene a chance to catch up rospy.sleep(2) # Give each of the scene objects a unique name table_id = 'table' box1_id = 'box1' box2_id = 'box2' target_id = 'target' tool_id = 'tool' # Remove leftover objects from a previous run scene.remove_world_object(table_id) scene.remove_world_object(box1_id) scene.remove_world_object(box2_id) scene.remove_world_object(target_id) scene.remove_world_object(tool_id) # Remove any attached objects from a previous session scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Start the arm in the "grasp" pose stored in the SRDF file arm.set_named_target('left_arm_up') arm.go() # Open the gripper to the neutral position gripper.set_joint_value_target(GRIPPER_OPEN) gripper.go() rospy.sleep(1) # Set the height of the table off the ground table_ground = 0.04 # Set the dimensions of the scene objects [l, w, h] table_size = [0.2, 0.7, 0.01] box1_size = [0.1, 0.05, 0.05] box2_size = [0.05, 0.05, 0.15] # Set the target size [l, w, h] target_size = [0.02, 0.01, 0.12] # Add a table top and two boxes to the scene table_pose = PoseStamped() table_pose.header.frame_id = REFERENCE_FRAME table_pose.pose.position.x = 0.25 table_pose.pose.position.y = 0.0 table_pose.pose.position.z = table_ground + table_size[2] / 2.0 table_pose.pose.orientation.w = 1.0 scene.add_box(table_id, table_pose, table_size) box1_pose = PoseStamped() box1_pose.header.frame_id = REFERENCE_FRAME box1_pose.pose.position.x = 0.21 box1_pose.pose.position.y = -0.1 box1_pose.pose.position.z = table_ground + table_size[ 2] + box1_size[2] / 2.0 box1_pose.pose.orientation.w = 1.0 #scene.add_box(box1_id, box1_pose, box1_size) box2_pose = PoseStamped() box2_pose.header.frame_id = REFERENCE_FRAME box2_pose.pose.position.x = 0.19 box2_pose.pose.position.y = 0.13 box2_pose.pose.position.z = table_ground + table_size[ 2] + box2_size[2] / 2.0 box2_pose.pose.orientation.w = 1.0 #scene.add_box(box2_id, box2_pose, box2_size) # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = 0.24 target_pose.pose.position.y = 0.275 target_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 target_pose.pose.orientation.w = 1.0 # Add the target object to the scene scene.add_box(target_id, target_pose, target_size) # Make the table blue and the boxes orange self.setColor(table_id, 0, 0, 0.8, 1.0) self.setColor(box1_id, 0.8, 0.4, 0, 1.0) self.setColor(box2_id, 0.8, 0.4, 0, 1.0) # Make the target yellow self.setColor(target_id, 0.9, 0.9, 0, 1.0) # Send the colors to the planning scene self.sendColors() # Set the support surface name to the table object arm.set_support_surface_name(table_id) # Specify a pose to place the target after being picked up place_pose = PoseStamped() place_pose.header.frame_id = REFERENCE_FRAME place_pose.pose.position.x = 0.18 place_pose.pose.position.y = 0 place_pose.pose.position.z = table_ground + table_size[ 2] + target_size[2] / 2.0 place_pose.pose.orientation.w = 1.0 # Initialize the grasp pose to the target pose grasp_pose = target_pose # Shift the grasp pose by half the width of the target to center it #grasp_pose.pose.position.y -= target_size[1] / 2.0 grasp_pose.pose.position.x = 0.12792118579 + .1 grasp_pose.pose.position.y = 0.285290879999 + 0.05 grasp_pose.pose.position.z = 0.120301181892 #grasp_pose.pose.orientation = # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id, table_id]) # Publish the grasp poses so they can be viewed in RViz for grasp in grasps: self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) break # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) result = arm.pick(target_id, grasps) rospy.sleep(0.2) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: result = None n_attempts = 0 # Generate valid place poses places = self.make_places(place_pose) # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) for place in places: result = arm.place(target_id, place) if result == MoveItErrorCodes.SUCCESS: break rospy.sleep(0.2) if result != MoveItErrorCodes.SUCCESS: rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") else: # Return the arm to the "resting" pose stored in the SRDF file arm.set_named_target('left_arm_rest') arm.go() # Open the gripper to the open position gripper.set_joint_value_target(GRIPPER_OPEN) gripper.go() else: rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") rospy.sleep(1) # Shut down MoveIt cleanly moveit_commander.roscpp_shutdown() # Exit the script moveit_commander.os._exit(0)
class Jaco_rapper(): def __init__(self): moveit_commander.roscpp_initialize(sys.argv) self.scene = PlanningSceneInterface() self.robot = RobotCommander() self.jaco_arm = MoveGroupCommander("Arm") self.hand = MoveGroupCommander("Hand") #self.pose_pub = rospy.Publisher("hand_pose", PoseStamped,queue_size = 100) self.pick_command = rospy.Publisher("pick_command", Bool, queue_size=100) rospy.Subscriber("pick_pose", PoseStamped, self.pick) self.jaco_arm.allow_replanning(True) # Set the right arm reference frame self.jaco_arm.set_pose_reference_frame(REFERENCE_FRAME) self.jaco_arm.set_planning_time(5) self.jaco_arm.set_goal_tolerance(0.02) self.jaco_arm.set_goal_orientation_tolerance(0.1) #self.pick_command.publish(True) def test(self): #self.hand.set_joint_value_target([0, 0, 0, 0]) grasp_pose = PoseStamped() grasp_pose.header.frame_id = 'arm_stand' grasp_pose.pose.position.x = 0 grasp_pose.pose.position.y = 0.24 grasp_pose.pose.position.z = -0.4 grasp_pose.pose.orientation = Quaternion(0.606301648371, 0.599731279995, 0.381153346104, 0.356991358063) # self.hand.set_joint_value_target([0, 0.012 ,0.012 ,0.012]) while (True): self.jaco_arm.set_pose_target( grasp_pose) # move to the top of the target self.jaco_arm.go() rospy.sleep(0.2) #result = self.jaco_arm.go() def pick(self, p): target_id = 'target' # Set a limit on the number of pick attempts before bailing max_pick_attempts = 5 # Set a limit on the number of place attempts max_place_attempts = 5 # Remove leftover objects from a previous run self.scene.remove_world_object(target_id) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, target_id) # Give the scene a chance to catch up rospy.sleep(1) # Open the gripper to the neutral position self.hand.set_joint_value_target([0.2, 0.2, 0.2, 0.2]) self.hand.go() rospy.sleep(1) target_size = [0.01, 0.01, 0.01] # Set the target pose in between the boxes and on the table target_pose = PoseStamped() target_pose.header.frame_id = REFERENCE_FRAME target_pose.pose.position.x = p.pose.position.x - 0.015 #p.pose.position.x - 0.015 target_pose.pose.position.y = 0.05 target_pose.pose.position.z = p.pose.position.z target_pose.pose.orientation.w = 0 print "Arm is catching {} object at ({}, {}, {})".format( p.header.frame_id, p.pose.position.x, p.pose.position.y, p.pose.position.z) # Add the target object to the scene self.scene.add_box(target_id, target_pose, target_size) # Initialize the grasp pose to the target pose grasp_pose = PoseStamped() grasp_pose.header.frame_id = REFERENCE_FRAME grasp_pose.pose = target_pose.pose grasp_pose.pose.position.y = 0.24 # Generate a list of grasps grasps = self.make_grasps(grasp_pose, [target_id]) # Publish the grasp poses so they can be viewed in RViz for grasp in grasps: #self.gripper_pose_pub.publish(grasp.grasp_pose) rospy.sleep(0.2) # Track success/failure and number of attempts for pick operation result = None n_attempts = 0 # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_pick_attempts: result = self.jaco_arm.pick(target_id, grasps) n_attempts += 1 rospy.loginfo("Pick attempt: " + str(n_attempts)) rospy.sleep(1.0) # If the pick was successful, attempt the place operation if result == MoveItErrorCodes.SUCCESS: result = None n_attempts = 0 # Generate valid place poses places = self.make_places(p.header.frame_id) # Repeat until we succeed or run out of attempts while result != MoveItErrorCodes.SUCCESS and n_attempts < max_place_attempts: for place in places: result = self.jaco_arm.place(target_id, place) if result == MoveItErrorCodes.SUCCESS: break n_attempts += 1 rospy.loginfo("Place attempt: " + str(n_attempts)) rospy.sleep(0.2) if result != MoveItErrorCodes.SUCCESS: rospy.loginfo("Place operation failed after " + str(n_attempts) + " attempts.") else: rospy.loginfo("Pick operation failed after " + str(n_attempts) + " attempts.") rospy.sleep(0.2) self.scene.remove_world_object(target_id) # Remove any attached objects from a previous session self.scene.remove_attached_object(GRIPPER_FRAME, target_id) self.pick_command.publish(Bool(True)) return # Get the gripper posture as a JointTrajectory def make_gripper_posture(self, joint_positions): # Initialize the joint trajectory for the gripper joints t = JointTrajectory() # Set the joint names to the gripper joint names t.joint_names = GRIPPER_JOINT_NAMES # Initialize a joint trajectory point to represent the goal tp = JointTrajectoryPoint() # Assign the trajectory joint positions to the input positions tp.positions = joint_positions # Set the gripper effort tp.effort = GRIPPER_EFFORT tp.time_from_start = rospy.Duration(1.0) # Append the goal point to the trajectory points t.points.append(tp) # Return the joint trajectory return t # Generate a gripper translation in the direction given by vector def make_gripper_translation(self, min_dist, desired, vector): # Initialize the gripper translation object g = GripperTranslation() # Set the direction vector components to the input g.direction.vector.x = vector[0] g.direction.vector.y = vector[1] g.direction.vector.z = vector[2] # The vector is relative to the gripper frame g.direction.header.frame_id = 'arm_stand' # Assign the min and desired distances from the input g.min_distance = min_dist g.desired_distance = desired return g # Generate a list of possible grasps def make_grasps(self, initial_pose_stamped, allowed_touch_objects): # Initialize the grasp object g = Grasp() # Set the pre-grasp and grasp postures appropriately g.pre_grasp_posture = self.make_gripper_posture(GRIPPER_OPEN) g.grasp_posture = self.make_gripper_posture(GRIPPER_CLOSED) # Set the approach and retreat parameters as desired g.pre_grasp_approach = self.make_gripper_translation( 0.05, 0.15, [0.0, -1.0, 0.0]) g.post_grasp_retreat = self.make_gripper_translation( 0.05, 0.1, [0.0, 1.0, 0.0]) # Set the first grasp pose to the input pose g.grasp_pose = initial_pose_stamped # Pitch angles to try pitch_vals = [0, 0.1, -0.1, 0.2, -0.2, 0.3, -0.3] # Yaw angles to try yaw_vals = [0] # A list to hold the grasps g.grasp_pose.pose.orientation = Quaternion(0.606301648371, 0.599731279995, 0.381153346104, 0.356991358063) # Set and id for this grasp (simply needs to be unique) g.id = str(len(yaw_vals)) # Set the allowed touch objects to the input list g.allowed_touch_objects = allowed_touch_objects # Don't restrict contact force g.max_contact_force = 0 grasps = [g] # Return the list return grasps # Generate a list of possible place poses def make_places(self, color): # Initialize the place location as a PoseStamped message x = 0 z = 0 if (color == 'red'): x = 0.4 z = -0.4 elif (color == 'blue'): x = 0.4 z = -0.25 else: x = -0.3 z = -0.4 place_pose = PoseStamped() place_pose.pose.position.x = x place_pose.pose.position.y = 0.2 place_pose.pose.position.z = z # Start with the input place pose place_pose.header.frame_id = REFERENCE_FRAME # A list to hold the places places = [] # Create a quaternion from the Euler angles place_pose.pose.orientation = Quaternion(0, 0, 0, 0) # Append this place pose to the list places.append(deepcopy(place_pose)) # Return the list return places
class Pick_Place: def __init__(self): # Retrieve params: self._table_object_name = rospy.get_param('~table_object_name', 'Grasp_Table') self._grasp_object_name = rospy.get_param('~grasp_object_name', 'Grasp_Object') self._grasp_object_width = rospy.get_param('~grasp_object_width', 0.01) self._arm_group = rospy.get_param('~manipulator', 'manipulator') self._gripper_group = rospy.get_param('~gripper', 'gripper') self._approach_retreat_desired_dist = rospy.get_param('~approach_retreat_desired_dist', 0.2) self._approach_retreat_min_dist = rospy.get_param('~approach_retreat_min_dist', 0.1) # Create (debugging) publishers: self._grasps_pub = rospy.Publisher('grasps', PoseArray, queue_size=1, latch=True) self._places_pub = rospy.Publisher('places', PoseArray, queue_size=1, latch=True) # Create planning scene and robot commander: self._scene = PlanningSceneInterface() self._robot = RobotCommander() rospy.sleep(1.0) # Retrieve groups (arm and gripper): self._arm = self._robot.get_group(self._arm_group) self._gripper = self._robot.get_group(self._gripper_group) # # self._pose_table = self._scene.get_object_poses(self._table_object_name) # self._pose_coke_can = self._scene.get_object_poses(self._grasp_object_name) # self.setup() # Clean the scene: self._scene.remove_world_object(self._table_object_name) rospy.sleep(1.0) self._scene.remove_world_object(self._grasp_object_name) rospy.sleep(1.0) # # Add table and Coke can objects to the planning scene: self._pose_table = self._add_table(self._table_object_name) rospy.sleep(2.0) self._pose_coke_can = self._add_grasp_block_(self._grasp_object_name) rospy.sleep(2.0) # rospy.sleep(1.0) # Define target place pose: self._pose_place = Pose() self._pose_place.position.x = self._pose_coke_can.position.x self._pose_place.position.y = self._pose_coke_can.position.y - 0.06 self._pose_place.position.z = self._pose_coke_can.position.z self._pose_place.orientation = Quaternion(*quaternion_from_euler(0.0, 0.0, 0.0)) # Create grasp generator 'generate' action client: self._grasps_ac = SimpleActionClient('/moveit_simple_grasps_server/generate', GenerateGraspsAction) if not self._grasps_ac.wait_for_server(rospy.Duration(5.0)): rospy.logerr('Grasp generator action client not available!') rospy.signal_shutdown('Grasp generator action client not available!') return # Create move group 'pickup' action client: self._pickup_ac = SimpleActionClient('/pickup', PickupAction) if not self._pickup_ac.wait_for_server(rospy.Duration(5.0)): rospy.logerr('Pick up action client not available!') rospy.signal_shutdown('Pick up action client not available!') return # Create move group 'place' action client: self._place_ac = SimpleActionClient('/place', PlaceAction) if not self._place_ac.wait_for_server(rospy.Duration(5.0)): rospy.logerr('Place action client not available!') rospy.signal_shutdown('Place action client not available!') return # Pick Coke can object: while not self._pickup(self._arm_group, self._grasp_object_name, self._grasp_object_width): rospy.logwarn('Pick up failed! Retrying ...') rospy.sleep(1.0) rospy.loginfo('Pick up successfully') # Place Coke can object on another place on the support surface (table): # while not self._place(self._arm_group, self._grasp_object_name, self._pose_place): # rospy.logwarn('Place failed! Retrying ...') # rospy.sleep(1.0) # # rospy.loginfo('Place successfully') def setup(): # Clean the scene: self._scene.remove_world_object(self._table_object_name) self._scene.remove_world_object(self._grasp_object_name) # Add table and Coke can objects to the planning scene: self._pose_table = self._add_table(self._table_object_name) self._pose_coke_can = self._add_grasp_block_(self._grasp_object_name) def __del__(self): # Clean the scene: self._scene.remove_world_object(self._grasp_object_name) self._scene.remove_world_object(self._table_object_name) self._scene.remove_attached_object() def _add_table(self, name): rospy.loginfo("entered table") p = PoseStamped() p.header.frame_id = self._robot.get_planning_frame() p.header.stamp = rospy.Time.now() p.pose.position.x = 0.0 p.pose.position.y = 0.0 p.pose.position.z = -0.2 q = quaternion_from_euler(0.0, 0.0, numpy.deg2rad(90.0)) p.pose.orientation = Quaternion(*q) # Table size from ~/.gazebo/models/table/model.sdf, using the values # for the surface link. self._scene.add_box(name, p, (9 , 9, 0.02)) return p.pose def _add_grasp_block_(self, name): rospy.loginfo("entered box grabber") p = PoseStamped() p.header.frame_id = self._robot.get_planning_frame() p.header.stamp = rospy.Time.now() p.pose.position.x = 0.5 p.pose.position.y = 0.05 p.pose.position.z = 0.32 q = quaternion_from_euler(0.0, 0.0, 0.0) p.pose.orientation = Quaternion(*q) # Coke can size from ~/.gazebo/models/coke_can/meshes/coke_can.dae, # using the measure tape tool from meshlab. # The box is the bounding box of the coke cylinder. # The values are taken from the cylinder base diameter and height. self._scene.add_box(name, p, (0.1, 0.1, 0.1)) return p.pose def _generate_grasps(self, pose, width): """ Generate grasps by using the grasp generator generate action; based on server_test.py example on moveit_simple_grasps pkg. """ # Create goal: goal = GenerateGraspsGoal() goal.pose = pose goal.width = width options = GraspGeneratorOptions() # simple_graps.cpp doesn't implement GRASP_AXIS_Z! #options.grasp_axis = GraspGeneratorOptions.GRASP_AXIS_Z options.grasp_direction = GraspGeneratorOptions.GRASP_DIRECTION_UP options.grasp_rotation = GraspGeneratorOptions.GRASP_ROTATION_FULL # @todo disabled because it works better with the default options #goal.options.append(options) # Send goal and wait for result: state = self._grasps_ac.send_goal_and_wait(goal) if state != GoalStatus.SUCCEEDED: rospy.logerr('Grasp goal failed!: %s' % self._grasps_ac.get_goal_status_text()) return None grasps = self._grasps_ac.get_result().grasps # Publish grasps (for debugging/visualization purposes): self._publish_grasps(grasps) return grasps def _generate_places(self, target): """ Generate places (place locations), based on https://github.com/davetcoleman/baxter_cpp/blob/hydro-devel/ baxter_pick_place/src/block_pick_place.cpp """ # Generate places: places = [] now = rospy.Time.now() for angle in numpy.arange(0.0, numpy.deg2rad(360.0), numpy.deg2rad(1.0)): # Create place location: place = PlaceLocation() place.place_pose.header.stamp = now place.place_pose.header.frame_id = self._robot.get_planning_frame() # Set target position: place.place_pose.pose = copy.deepcopy(target) # Generate orientation (wrt Z axis): q = quaternion_from_euler(0.0, 0.0, angle ) place.place_pose.pose.orientation = Quaternion(*q) # Generate pre place approach: place.pre_place_approach.desired_distance = self._approach_retreat_desired_dist place.pre_place_approach.min_distance = self._approach_retreat_min_dist place.pre_place_approach.direction.header.stamp = now place.pre_place_approach.direction.header.frame_id = self._robot.get_planning_frame() place.pre_place_approach.direction.vector.x = 0 place.pre_place_approach.direction.vector.y = 0 place.pre_place_approach.direction.vector.z = 0.2 # Generate post place approach: place.post_place_retreat.direction.header.stamp = now place.post_place_retreat.direction.header.frame_id = self._robot.get_planning_frame() place.post_place_retreat.desired_distance = self._approach_retreat_desired_dist place.post_place_retreat.min_distance = self._approach_retreat_min_dist place.post_place_retreat.direction.vector.x = 0 place.post_place_retreat.direction.vector.y = 0 place.post_place_retreat.direction.vector.z = 0.2 # Add place: places.append(place) # Publish places (for debugging/visualization purposes): self._publish_places(places) return places def _create_pickup_goal(self, group, target, grasps): """ Create a MoveIt! PickupGoal """ # Create goal: goal = PickupGoal() goal.group_name = group goal.target_name = target goal.possible_grasps.extend(grasps) goal.allowed_touch_objects.append(target) goal.support_surface_name = self._table_object_name # Configure goal planning options: goal.allowed_planning_time = 7.0 goal.planning_options.planning_scene_diff.is_diff = True goal.planning_options.planning_scene_diff.robot_state.is_diff = True goal.planning_options.plan_only = False goal.planning_options.replan = True goal.planning_options.replan_attempts = 20 return goal def _create_place_goal(self, group, target, places): """ Create a MoveIt! PlaceGoal """ # Create goal: goal = PlaceGoal() goal.group_name = group goal.attached_object_name = target goal.place_locations.extend(places) # Configure goal planning options: goal.allowed_planning_time = 7.0 goal.planning_options.planning_scene_diff.is_diff = True goal.planning_options.planning_scene_diff.robot_state.is_diff = True goal.planning_options.plan_only = False goal.planning_options.replan = True goal.planning_options.replan_attempts = 20 return goal def _pickup(self, group, target, width): """ Pick up a target using the planning group """ # Obtain possible grasps from the grasp generator server: grasps = self._generate_grasps(self._pose_coke_can, width) # Create and send Pickup goal: goal = self._create_pickup_goal(group, target, grasps) state = self._pickup_ac.send_goal_and_wait(goal) if state != GoalStatus.SUCCEEDED: rospy.logerr('Pick up goal failed!: %s' % self._pickup_ac.get_goal_status_text()) return None result = self._pickup_ac.get_result() # Check for error: err = result.error_code.val if err != MoveItErrorCodes.SUCCESS: rospy.logwarn('Group %s cannot pick up target %s!: %s' % (group, target, str(moveit_error_dict[err]))) return False return True def _place(self, group, target, place): """ Place a target using the planning group """ # Obtain possible places: places = self._generate_places(place) # Create and send Place goal: goal = self._create_place_goal(group, target, places) state = self._place_ac.send_goal_and_wait(goal) if state != GoalStatus.SUCCEEDED: rospy.logerr('Place goal failed!: %s' % self._place_ac.get_goal_status_text()) return None result = self._place_ac.get_result() # Check for error: err = result.error_code.val if err != MoveItErrorCodes.SUCCESS: rospy.logwarn('Group %s cannot place target %s!: %s' % (group, target, str(moveit_error_dict[err]))) return False return True def _publish_grasps(self, grasps): """ Publish grasps as poses, using a PoseArray message """ if self._grasps_pub.get_num_connections() > 0: msg = PoseArray() msg.header.frame_id = self._robot.get_planning_frame() msg.header.stamp = rospy.Time.now() for grasp in grasps: p = grasp.grasp_pose.pose msg.poses.append(Pose(p.position, p.orientation)) self._grasps_pub.publish(msg) def _publish_places(self, places): """ Publish places as poses, using a PoseArray message """ if self._places_pub.get_num_connections() > 0: msg = PoseArray() msg.header.frame_id = self._robot.get_planning_frame() msg.header.stamp = rospy.Time.now() for place in places: msg.poses.append(place.place_pose.pose) self._places_pub.publish(msg) def _add_objects(self): """ Here add all the objects that you want to add to the _scene """ self._pose_table = self._add_table(self._table_object_name) self._pose_coke_can = self._add_grasp_block_(self._grasp_object_name)
class PickAndPlaceServer(object): def __init__(self): self.node_name = "PickAndPlaceServer" rospy.loginfo("Initalizing PickAndPlaceServer...") self.sg = SphericalGrasps() # Get the object size self.object_height = 0.1 self.object_width = 0.05 self.object_depth = 0.05 self.pick_pose = rospy.get_param('~pickup_marker_pose') self.place_pose = rospy.get_param('~place_marker_pose') rospy.loginfo("%s: Waiting for pickup action server...", self.node_name) self.pickup_ac = SimpleActionClient('/pickup', PickupAction) connected = self.pickup_ac.wait_for_server(rospy.Duration(3000)) if not connected: rospy.logerr("%s: Could not connect to pickup action server", self.node_name) exit() rospy.loginfo("%s: Connected to pickup action server", self.node_name) rospy.loginfo("%s: Waiting for place action server...", self.node_name) self.place_ac = SimpleActionClient('/place', PlaceAction) if not self.place_ac.wait_for_server(rospy.Duration(3000)): rospy.logerr("%s: Could not connect to place action server", self.node_name) exit() rospy.loginfo("%s: Connected to place action server", self.node_name) self.scene = PlanningSceneInterface() rospy.loginfo("Connecting to /get_planning_scene service") self.scene_srv = rospy.ServiceProxy('/get_planning_scene', GetPlanningScene) self.scene_srv.wait_for_service() rospy.loginfo("Connected.") rospy.loginfo("Connecting to clear octomap service...") self.clear_octomap_srv = rospy.ServiceProxy('/clear_octomap', Empty) self.clear_octomap_srv.wait_for_service() rospy.loginfo("Connected!") # Get the links of the end effector exclude from collisions self.links_to_allow_contact = rospy.get_param('~links_to_allow_contact', None) if self.links_to_allow_contact is None: rospy.logwarn("Didn't find any links to allow contacts... at param ~links_to_allow_contact") else: rospy.loginfo("Found links to allow contacts: " + str(self.links_to_allow_contact)) self.pick_as = SimpleActionServer(self.pick_pose, PickUpPoseAction, execute_cb=self.pick_cb, auto_start=False) self.pick_as.start() self.place_as = SimpleActionServer(self.place_pose, PickUpPoseAction, execute_cb=self.place_cb, auto_start=False) self.place_as.start() def pick_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.grasp_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.pick_as.set_aborted(p_res) else: self.pick_as.set_succeeded(p_res) def place_cb(self, goal): """ :type goal: PickUpPoseGoal """ error_code = self.place_object(goal.object_pose) p_res = PickUpPoseResult() p_res.error_code = error_code if error_code != 1: self.place_as.set_aborted(p_res) else: self.place_as.set_succeeded(p_res) def wait_for_planning_scene_object(self, object_name='part'): rospy.loginfo( "Waiting for object '" + object_name + "'' to appear in planning scene...") gps_req = GetPlanningSceneRequest() gps_req.components.components = gps_req.components.WORLD_OBJECT_NAMES part_in_scene = False while not rospy.is_shutdown() and not part_in_scene: # This call takes a while when rgbd sensor is set gps_resp = self.scene_srv.call(gps_req) # check if 'part' is in the answer for collision_obj in gps_resp.scene.world.collision_objects: if collision_obj.id == object_name: part_in_scene = True break else: rospy.sleep(1.0) rospy.loginfo("'" + object_name + "'' is in scene!") def grasp_object(self, object_pose): rospy.loginfo("Removing any previous 'part' object") self.scene.remove_attached_object("arm_tool_link") self.scene.remove_world_object("part") self.scene.remove_world_object("table") rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) rospy.sleep(2.0) # Removing is fast rospy.loginfo("Adding new 'part' object") rospy.loginfo("Object pose: %s", object_pose.pose) #Add object description in scene self.scene.add_box("part", object_pose, (self.object_depth, self.object_width, self.object_height)) rospy.loginfo("Second%s", object_pose.pose) table_pose = copy.deepcopy(object_pose) #define a virtual table below the object table_height = object_pose.pose.position.z - self.object_width/2 table_width = 1.8 table_depth = 0.5 table_pose.pose.position.z += -(2*self.object_width)/2 -table_height/2 table_height -= 0.008 #remove few milimeters to prevent contact between the object and the table self.scene.add_box("table", table_pose, (table_depth, table_width, table_height)) # # We need to wait for the object part to appear self.wait_for_planning_scene_object() self.wait_for_planning_scene_object("table") # compute grasps possible_grasps = self.sg.create_grasps_from_object_pose(object_pose) goal = createPickupGoal("arm_torso", "part", object_pose, possible_grasps, self.links_to_allow_contact) rospy.loginfo("Sending goal") self.pickup_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.pickup_ac.wait_for_result() result = self.pickup_ac.get_result() rospy.logdebug("Using torso result: " + str(result)) rospy.loginfo( "Pick result: " + str(moveit_error_dict[result.error_code.val])) # Remove table from world self.scene.remove_world_object("table") return result.error_code.val def place_object(self, object_pose): rospy.loginfo("Clearing octomap") self.clear_octomap_srv.call(EmptyRequest()) possible_placings = self.sg.create_placings_from_object_pose( object_pose) # Try only with arm rospy.loginfo("Trying to place using only arm") goal = createPlaceGoal( object_pose, possible_placings, "arm", "part", self.links_to_allow_contact) rospy.loginfo("Sending goal") self.place_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.place_ac.wait_for_result() result = self.place_ac.get_result() rospy.loginfo(str(moveit_error_dict[result.error_code.val])) if str(moveit_error_dict[result.error_code.val]) != "SUCCESS": rospy.loginfo( "Trying to place with arm and torso") # Try with arm and torso goal = createPlaceGoal( object_pose, possible_placings, "arm_torso", "part", self.links_to_allow_contact) rospy.loginfo("Sending goal") self.place_ac.send_goal(goal) rospy.loginfo("Waiting for result") self.place_ac.wait_for_result() result = self.place_ac.get_result() rospy.logerr(str(moveit_error_dict[result.error_code.val])) # print result rospy.loginfo( "Result: " + str(moveit_error_dict[result.error_code.val])) rospy.loginfo("Removing previous 'part' object") self.scene.remove_world_object("part") return result.error_code.val