srs_grasp_states.py
Go to the documentation of this file.
00001 #!/usr/bin/python
00002 
00003 import roslib
00004 roslib.load_manifest('srs_grasping')
00005 import rospy
00006 import grasping_functions
00007 from shared_state_information import *
00008 import copy
00009 from srs_knowledge.srv import *
00010 from srs_symbolic_grounding.srv import *
00011 from srs_symbolic_grounding.msg import *
00012 from simple_script_server import *
00013 sss = simple_script_server()
00014 
00015 from srs_grasping.srv import *
00016 from srs_knowledge.srv import *
00017 from pr2_controllers_msgs.msg import JointTrajectoryControllerState
00018 from srs_msgs.msg import SRSSpatialInfo 
00019 from srs_assisted_grasping_msgs.msg import *
00020 from arm_navigation_msgs.msg import *
00021 
00022 class select_srs_grasp(smach.State):
00023 
00024     def __init__(self):
00025         smach.State.__init__(
00026             self,
00027             outcomes=['succeeded', 'not_possible', 'failed', 'preempted'],
00028             input_keys=['object', 'target_object_id'],
00029             output_keys=['grasp_configuration', 'poses'])
00030   
00031 
00032     def execute(self, userdata):
00033         
00034         global listener
00035         print "Object pose before transformation:", userdata.object.pose
00036         try:
00037             # transform object_pose into base_link
00038             object_pose_in = userdata.object.pose
00039             object_pose_in.header.stamp = listener.getLatestCommonTime("/base_link",object_pose_in.header.frame_id)
00040             object_pose_bl = listener.transformPose("/base_link", object_pose_in)
00041 
00042         except rospy.ROSException, e:
00043             print ("Transformation not possible: %s", e)
00044             return 'failed'
00045         
00046         get_grasps_from_position = rospy.ServiceProxy('get_feasible_grasps', GetFeasibleGrasps)
00047         req = GetFeasibleGraspsRequest(userdata.target_object_id, object_pose_bl.pose, [0.0, 0.0]) #[X,Z]
00048         grasp_configuration = copy.deepcopy((get_grasps_from_position(req)).grasp_configuration)
00049 
00050         if len(grasp_configuration) < 1: # no valid configurations found
00051             print "grasp not possible"
00052             return 'not_possible'
00053         else:       
00054             poses=list()
00055             for index in range(len(grasp_configuration)):
00056                 pose = PoseStamped()
00057                 pose.header.frame_id = "/base_link"
00058                 pose.pose = grasp_configuration[index].pre_grasp.pose
00059                 poses.append(pose)
00060             userdata.poses = poses
00061             userdata.grasp_configuration = grasp_configuration
00062         return 'succeeded'
00063      
00064 
00065 class srs_grasp(smach.State):
00066     def __init__(self):
00067         smach.State.__init__(self, outcomes=['succeeded','not_completed','failed', 'preempted','retry'], 
00068                              input_keys=['grasp_configuration','grasp_configuration_id'], 
00069                              output_keys=['grasp_categorisation','surface_distance'])
00070 
00071         self.current_arm_state = [];
00072         self.arm_state = rospy.Subscriber("/arm_controller/state", JointTrajectoryControllerState, self.get_joint_state)
00073 
00074     def get_joint_state(self, msg):
00075         self.current_arm_state = list(msg.desired.positions)
00076 
00077     def get_fake_id(self, grasp_configuration):
00078         #TOP grasps priority.
00079         for i in range(0, len(grasp_configuration)):
00080                 if grasp_configuration[i].category == "TOP":
00081                         return i;
00082         return (len(grasp_configuration)-1);
00083 
00084     def execute(self, userdata):
00085 
00086         client = actionlib.SimpleActionClient('/but_arm_manip/reactive_grasping_action',ReactiveGraspingAction)
00087         grasp_configuration_id = userdata.grasp_configuration_id
00088         #grasp_configuration_id = self.get_fake_id(userdata.grasp_configuration);
00089         
00090         category = userdata.grasp_configuration[grasp_configuration_id].category
00091         userdata.surface_distance = userdata.grasp_configuration[grasp_configuration_id].surface_distance
00092         
00093         
00094         if category == "TOP":
00095             userdata.grasp_categorisation = 'top'
00096             sdh_handle=sss.move("sdh", "spheropen")
00097         elif category == "SIDE" or category == "-SIDE":
00098             userdata.grasp_categorisation = 'side'
00099             sdh_handle=sss.move("sdh", "cylopen")
00100         else:
00101             userdata.grasp_categorisation = 'front'
00102             sdh_handle=sss.move("sdh", "cylopen")
00103         sdh_handle.wait()
00104         
00105 
00106         #Get the current arm joint states.
00107         rospy.sleep(3)
00108         while self.arm_state.get_num_connections() == 0:
00109                 time.sleep(0.3)
00110                 continue
00111         #pregrasps
00112         pre_grasp_stamped = copy.deepcopy(userdata.grasp_configuration[grasp_configuration_id].pre_grasp);
00113         
00114         #grasp
00115         grasp_stamped = copy.deepcopy(userdata.grasp_configuration[grasp_configuration_id].grasp);
00116         
00117         #postgrasp
00118         post_grasp_stamped = copy.deepcopy(grasp_stamped);
00119         post_grasp_stamped.pose.position.x += 0.05;
00120         post_grasp_stamped.pose.position.z += 0.25;
00121         
00122         grasp_trajectory = [];
00123         postgrasp_trajectory = [];
00124         
00125         
00126         class BadGrasp(Exception): pass
00127         try:
00128             try:
00129                 ipa_arm_navigation = rospy.get_param("srs/ipa_arm_navigation")
00130             except Exception, e:
00131                 rospy.INFO('can not read parameter of srs/ipa_arm_navigation, use the default value planned arm navigation disabled')
00132             
00133             #pre-grasp
00134             if ipa_arm_navigation.lower() != 'true':
00135                 grasp_trajectory.append(self.current_arm_state)
00136             else:
00137                 (pgc1, error_code) = grasping_functions.graspingutils.callIKSolver(self.current_arm_state, pre_grasp_stamped)
00138                 if(error_code.val != error_code.SUCCESS):
00139                     sss.say(["I can not move the arm to the pregrasp position!"])
00140                     raise BadGrasp();
00141                 else:
00142                     grasp_trajectory.append(pgc1)
00143                 
00144             #grasp
00145             (gc, error_code) = grasping_functions.graspingutils.callIKSolver(grasp_trajectory[len(grasp_trajectory)-1], grasp_stamped)
00146             if(error_code.val != error_code.SUCCESS):
00147                 sss.say(["I can not move the arm to the grasp position!"])
00148                 raise BadGrasp();
00149             else:
00150                 grasp_trajectory.append(gc);
00151             
00152             #Move arm to pregrasp position.
00153             arm_handle = sss.move("arm", [grasp_trajectory[0]], True, mode='Planned')
00154             # wait while movement
00155             r = rospy.Rate(10)
00156             preempted = False
00157             arm_state = -1
00158             while True:
00159                 preempted = self.preempt_requested()
00160                 arm_state = arm_handle.get_state()
00161                 if preempted or ( arm_state == 3) or (arm_state == 4):
00162                     break # stop waiting
00163                 r.sleep()
00164 
00165             rospy.sleep(5)
00166             arm_handle.wait(5)
00167 
00168             #Move arm to grasp position.
00169             arm_handle = sss.move("arm", [grasp_trajectory[1]], True, mode='Planned')
00170             # wait while movement
00171             r = rospy.Rate(10)
00172             preempted = False
00173             arm_state = -1
00174             while True:
00175                 preempted = self.preempt_requested()
00176                 arm_state = arm_handle.get_state()
00177                 if preempted or ( arm_state == 3) or (arm_state == 4):
00178                     break # stop waiting
00179                 r.sleep()
00180 
00181             rospy.sleep(3)
00182             arm_handle.wait(3)
00183 
00184             # To deprecate #####################################################
00185             #sdh_handle = sss.move("sdh", [list(userdata.grasp_configuration[grasp_configuration_id].sdh_joint_values)]) 
00186             #sdh_handle.wait() 
00187             #rospy.sleep(10) 
00188             ####################################################################
00189             
00190             #Close SDH based on the grasp configuration to grasp.
00191             rospy.loginfo("Waiting for reactive grasping server...")
00192             client.wait_for_server()
00193             
00194             rospy.loginfo('Opening gripper using cob_script_server')
00195             goal = ReactiveGraspingGoal()
00196             
00197             goal.target_configuration.data = list(userdata.grasp_configuration[grasp_configuration_id].sdh_joint_values)
00198             f = 3000.0
00199             goal.max_force.data = [f, f, f, f, f, f] # 6 tactile pads
00200             goal.time = rospy.Duration(3.0)
00201             
00202             client.send_goal(goal)
00203             
00204             rospy.loginfo('Closing gripper using reactive grasping')
00205             client.wait_for_result()
00206             result = client.get_result()
00207             rospy.sleep(6)
00208 
00209             #Confirm the grasp based on force feedback
00210             if not grasping_functions.graspingutils.sdh_tactil_sensor_result():
00211                 #Regrasp (close MORE the fingers)
00212                 regrasp = list(userdata.grasp_configuration[grasp_configuration_id].sdh_joint_values)
00213                 print "Current config, trying regrasp:\n", regrasp
00214                 regrasp[1] += 0.07
00215                 regrasp[3] += 0.07
00216                 regrasp[5] += 0.07
00217                 print "to:\n", regrasp
00218 
00219                 # To deprecate #################################################
00220                 #sdh_handle = sss.move("sdh", [list(userdata.grasp_configuration[grasp_configuration_id].sdh_joint_values)]) 
00221                 #sdh_handle.wait() 
00222                 #rospy.sleep(10) 
00223                 ################################################################
00224 
00225                 
00226                 goal.target_configuration.data = regrasp
00227                 client.send_goal(goal)
00228 
00229                 rospy.loginfo('Regrasp: Closing gripper using reactive grasping')
00230                 client.wait_for_result()
00231                 result = client.get_result()
00232                 rospy.sleep(6)
00233 
00234                 if not grasping_functions.graspingutils.sdh_tactil_sensor_result():
00235                     sss.say(["I can not fix the object correctly!"])
00236                     raise BadGrasp();
00237 
00238             #post-grasp
00239             aux_x = post_grasp_stamped.pose.position.x;
00240             aux = 0.0;
00241             
00242             for i in range(0,5):
00243                 post_grasp_stamped.pose.position.x = aux_x + aux;
00244                 (post_grasp_conf, error_code) = grasping_functions.graspingutils.callIKSolver(grasp_trajectory[1], post_grasp_stamped)
00245                 aux += 0.01;
00246                 if(error_code.val == error_code.SUCCESS):
00247                     postgrasp_trajectory.append(post_grasp_conf);
00248                     break;
00249             
00250             if len(postgrasp_trajectory) == 0:
00251                 sss.say(["I can not move the object to the postgrasp position!"])
00252                 raise BadGrasp();
00253 
00254             arm_handle = sss.move("arm",postgrasp_trajectory, True)
00255             sss.say(["I have grasped the object with success!"])
00256             rospy.sleep(3)
00257             arm_handle.wait(3)
00258 
00259 
00260             #second postgrasp
00261             aux_x = post_grasp_stamped.pose.position.x;
00262             aux = 0.05;
00263             postgrasp_trajectory = [];
00264 
00265             for i in range(0,5):
00266                 post_grasp_stamped.pose.position.x = aux_x + aux;
00267                 (post_grasp_conf2, error_code) = grasping_functions.graspingutils.callIKSolver(post_grasp_conf, post_grasp_stamped)
00268                 aux += 0.01;
00269                 if(error_code.val == error_code.SUCCESS):
00270                     postgrasp_trajectory.append(post_grasp_conf2);
00271                     break;
00272                 else:
00273                     print "Second postgrasp failed: ",i
00274 
00275             if len(postgrasp_trajectory) == 0:
00276                     arm_handle = sss.move("arm",[postgrasp_trajectory[len(postgrasp_trajectory)-1]], True)
00277                     rospy.sleep(3)
00278                     arm_handle.wait(3)
00279 
00280 
00281             return 'succeeded'
00282 
00283         except BadGrasp:
00284             sss.say(["I can not catch the object!"], False)
00285             return 'not_completed';
00286 
00287 # estimate the best grasp position
00288 class grasp_base_pose_estimation(smach.State):
00289     
00290     def __init__(self):
00291         smach.State.__init__(
00292             self,
00293             outcomes=['retry', 'not_retry', 'failed', 'preempted'],
00294             input_keys=['object','target_workspace_name'],
00295             output_keys=['base_pose'])
00296         
00297         self.counter = 0 
00298 
00299 
00300     def execute(self, userdata):
00301         
00302         self.counter = self.counter + 1
00303         if self.counter > 2:
00304             self.counter = 0
00305             #only need to retry once
00306             return 'not_retry'
00307         
00308         global listener
00309 
00310         try:
00311             #transform object_pose into base_link
00312             object_pose_in = userdata.object.pose
00313             object_pose_in.header.stamp = listener.getLatestCommonTime("/map",object_pose_in.header.frame_id)
00314             object_pose_map = listener.transformPose("/map", object_pose_in)
00315         except rospy.ROSException, e:
00316             print "Transformation not possible: %s"%e
00317             return 'failed'
00318 
00319         all_workspaces_on_map = ''
00320         index_of_the_target_workspace = ''
00321 
00322         try:
00323             rospy.wait_for_service('get_workspace_on_map')
00324             getWorkspace = rospy.ServiceProxy('get_workspace_on_map', GetWorkspaceOnMap)
00325             all_workspaces_on_map = getWorkspace(os.environ['ROBOT_ENV'], True)
00326             
00327             #get the index of the target workspace e.g. table0    
00328             index_of_the_target_workspace = all_workspaces_on_map.objects.index(userdata.target_workspace_name)
00329             #get the pose of the workspace from knowledge service
00330             target_object_pose = all_workspaces_on_map.objectsInfo[index_of_the_target_workspace].pose
00331             #get the houseHoldID of the workspace 
00332             object_id = all_workspaces_on_map.houseHoldId[index_of_the_target_workspace]
00333             
00334             #rospy.loginfo ("target name: %s", userdata.target_workspace_name)      
00335             #rospy.loginfo ("target pose: %s", target_object_pose)
00336             #rospy.loginfo ("target id: %s", object_id)
00337 
00338         except rospy.ServiceException, e:
00339             print "Service call failed: %s"%e
00340             return 'failed'
00341 
00342         parent_obj_geometry = SRSSpatialInfo()
00343         parent_obj_geometry.pose = target_object_pose
00344         parent_obj_geometry.l = all_workspaces_on_map.objectsInfo[index_of_the_target_workspace].l
00345         parent_obj_geometry.w = all_workspaces_on_map.objectsInfo[index_of_the_target_workspace].w
00346         parent_obj_geometry.h = all_workspaces_on_map.objectsInfo[index_of_the_target_workspace].h
00347         
00348         rospy.wait_for_service('symbol_grounding_grasp_base_pose_experimental')
00349         symbol_grounding_grasp_base_pose_experimental = rospy.ServiceProxy('symbol_grounding_grasp_base_pose_experimental', SymbolGroundingGraspBasePoseExperimental)
00350         try:
00351             result = symbol_grounding_grasp_base_pose_experimental(object_pose_map.pose, parent_obj_geometry, all_workspaces_on_map.objectsInfo)
00352             userdata.base_pose = [result.grasp_base_pose.x, result.grasp_base_pose.y, result.grasp_base_pose.theta]
00353             return 'retry'
00354         except rospy.ServiceException, e:
00355             print "Service call failed: %s" %e
00356             return 'failed'
00357 


srs_states
Author(s): Georg Arbeiter
autogenerated on Mon Oct 6 2014 08:34:06