pomdp_execution_basket_3_piles.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 import roslib; roslib.load_manifest('estirabot_apps')
00004 import rospy
00005 import smach
00006 import smach_ros
00007 import tf
00008 
00009 #from pomdp_create_model import *
00010 
00011 from smach import StateMachine, CBState, Iterator
00012 from smach_ros import ServiceState
00013 from actionlib import *
00014 from actionlib.msg import *
00015 from std_msgs.msg import String
00016 from iri_common_smach.utils_msg import build_pose
00017 from object_manipulation_msgs.msg import PickupAction,PickupGoal,PlaceAction,PlaceGoal
00018 from sensor_msgs.msg import PointCloud2, JointState
00019 from iri_deformable_analysis.srv import DoDeformableAnalysis, DoDeformableAnalysisRequest
00020 from estirabot_msgs.msg import PomdpGraspConfig
00021 from estirabot_msgs.srv import obs2action, obs2actionRequest
00022 from geometry_msgs.msg import Transform, PoseStamped, Pose
00023 from pprint import pprint
00024 from std_msgs.msg import Int8, Int32
00025 
00026 from iri_common_smach.st_get_pcl import GetPCL
00027 from iri_common_smach.transform_manager import TransformManager
00028 from iri_common_smach.homogeneous_product import *
00029 from iri_common_smach.utils_msg           import build_pose_stamped_msg, build_transform_msg
00030 from iri_common_smach.get_keystroke       import GetKeyStroke
00031 
00032 from iri_wam_smach.sm_wam_move_from_pose       import SM_WAM_MoveFromPose 
00033 
00034 from estirabot_apps_base.utils_pomdp            import PomdpConfigFactory 
00035 from estirabot_apps_base.sm_move                import SM_ESTIRABOT_GoHome
00036 from estirabot_apps_base.sm_deformable_analysis import SM_ESTIRABOT_DeformableAnalysis
00037 from estirabot_apps_base.sm_deformable_analysis import PerformAnalysis
00038 from estirabot_apps_base.sm_generate_grasp      import *
00039 from TranslatePomdp3piles import TranslatePomdp 
00040 
00041 
00042 class InputResult(smach.State):
00043     def __init__(self):
00044         smach.State.__init__(self, outcomes=['success'])
00045 
00046     def execute(self, userdata):
00047         keyserver = GetKeyStroke()
00048         c = -1
00049         print "Press [0-5] for clothes grabbed, 9 for error:"
00050         while (c < 0):
00051             c = keyserver()
00052             try:
00053                 c = int(c)
00054             except ValueError:
00055                 print "Error. Press [0-5] for clothes grabbed:"
00056                 continue
00057 
00058         print "Your value was: " + str(c)
00059         return 'success'
00060 
00061 class PlaceHandler():
00062     def __init__(self):
00063         self.next_left_zone  = 1
00064         self.next_right_zone = 1
00065 
00066     def calculate_place_pose(self, pomdp_config):
00067         # If place_point is None it implies special basket
00068         if (pomdp_config.place_point == None):
00069             return self.get_basket_pose()
00070 
00071         if (pomdp_config.grabbing_zone == pomdp_config.RIGHT_ZONE):
00072             return self.get_right_place_pose()
00073         elif (pomdp_config.grabbing_zone == pomdp_config.LEFT_ZONE):
00074             return self.get_left_place_pose()
00075         else:
00076             rospy.logerr("Value for grasping zone is not LEFT or RIGHT")
00077             return build_home_pose()
00078 
00079     def get_basket_pose(self):
00080         return build_pose(-0.165, 0.514, -0.188, 1, 0, 0, 0)
00081 
00082     def get_right_place_pose(self):
00083         if (self.next_right_zone == 1):
00084             pose = build_pose(0.422, -0.390, -0.234, 1, 0, 0, 0)
00085         elif (self.next_right_zone == 2):
00086             pose = build_pose(0.584, -0.390, -0.234, 1, 0, 0, 0)
00087         elif (self.next_right_zone == 3):
00088             pose = build_pose(0.633, -0.260, -0.234, 1, 0, 0, 0)
00089         elif (self.next_right_zone == 4):
00090             pose = build_pose(0.476, -0.260, -0.234, 1, 0, 0, 0)
00091         else:
00092             rospy.logerr("Righ pose next zone is out of range: " + str(self.next_right_zone))
00093 
00094         self.next_right_zone = self.next_right_zone + 1
00095 
00096         # reset to 1 again
00097         if (self.next_right_zone > 4):
00098             self.next_right_zone = 1
00099 
00100         return pose
00101 
00102     def get_left_place_pose(self):
00103         if (self.next_left_zone == 1):
00104             pose = build_pose(0.422, 0.390, -0.234, 1, 0, 0, 0)
00105         elif (self.next_left_zone == 2):
00106             pose = build_pose(0.584, 0.390, -0.234, 1, 0, 0, 0)
00107         elif (self.next_left_zone == 3):
00108             pose = build_pose(0.633, 0.260, -0.234, 1, 0, 0, 0)
00109         elif (self.next_left_zone == 4):
00110             pose = build_pose(0.476, 0.260, -0.234, 1, 0, 0, 0)
00111         else:
00112             rospy.logerr("Left pose next zone is out of range: " + str(self.next_left_zone))
00113 
00114         self.next_left_zone = self.next_left_zone + 1
00115 
00116         # reset to 1 again
00117         if (self.next_left_zone > 4):
00118             self.next_left_zone = 1
00119 
00120         return pose
00121 
00122 class BuildPickupGoalFromTransform(smach.State):
00123     fingers_grasp_configs = []
00124     def __init__(self):
00125         smach.State.__init__(self, outcomes=['success','fail','no_ik_solution'],
00126                                    input_keys=['grasp_pose','transform'],
00127                                    output_keys=['sm_grasp_goal'])
00128         self.fingers_grasp_configs.append("GSTO")
00129         self.fingers_grasp_configs.append("SM 600")
00130         self.fingers_grasp_configs.append("GTC")
00131         self.grasp_pose_st_wam                 = PoseStamped()
00132         self.grasp_pose_st_wam.header.frame_id = '/wam_link0'
00133         self.grasp_pose_st_wam.header.stamp    = rospy.Time.now()
00134         self.grasp_pose_st_wam.pose = build_pose(-0.08, -0.54, -0.35, 1, 0, 0, 0)
00135 
00136     def execute(self, userdata):
00137         # shortcuts
00138         rospy.set_param('/estirabot/skills/grasp/fingers_configuration', self.fingers_grasp_configs)
00139 
00140         pprint("Grasp original")
00141         pub = rospy.Publisher('/debug/grasp/original', PoseStamped, None, False, True)
00142         pub.publish(self.grasp_pose_st_wam)
00143 
00144         # pre-grasp posture is relative to real_grasp pose
00145         pre_grasp_pose_st        = PoseStamped()
00146         pre_grasp_pose_st.header = self.grasp_pose_st_wam.header
00147 
00148         modified_grasp_pose_st.pose = homogeneous_product_pose_transform(self.grasp_pose_st_wam.pose,
00149                                                                          userdata.transform)
00150 
00151         pprint("PRE-Grasp modifier applied")
00152         pub = rospy.Publisher('/debug/grasp/pre_grasp', PoseStamped, None, False, True)
00153         pub.publish(pre_grasp_pose_st)
00154 
00155         # For both grasp and pre-grasp we need the inverse kinematics and get joinst positions
00156         try:
00157             joints_grasp     = get_inverse_kinematics_from_pose(modified_grasp_pose_st)
00158 
00159         #except NoKinematicSolutionException, e:
00160         except rospy.ServiceException, e:
00161             return 'no_ik_solution'
00162 
00163         userdata.sm_grasp_goal =  build_simple_pickup_goal(joints_grasp,
00164                                                         joints_pre_grasp,
00165                                                         self.fingers_grasp_configs)
00166         return 'success'
00167 
00168 class TakeFromBasket(smach.State):
00169     fingers_grasp_configs = []
00170     def __init__(self):
00171         smach.State.__init__(self, outcomes=['success','fail','no_ik_solution'],
00172                                    output_keys=['sm_grasp_goal'])
00173         self.fingers_grasp_configs.append("GSTO")
00174         self.fingers_grasp_configs.append("SM 600")
00175         self.fingers_grasp_configs.append("GTC")
00176         self.grasp_pose_st_wam                 = PoseStamped()
00177         self.grasp_pose_st_wam.header.frame_id = '/wam_link0'
00178         self.grasp_pose_st_wam.header.stamp    = rospy.Time.now()
00179         self.grasp_pose_st_wam.pose = build_pose(-0.08, -0.54, -0.35, 1, 0, 0, 0)
00180 
00181     def execute(self, userdata):
00182         # shortcuts
00183         rospy.set_param('/estirabot/skills/grasp/fingers_configuration', self.fingers_grasp_configs)
00184 
00185         pprint("Grasp original")
00186         pub = rospy.Publisher('/debug/grasp/original', PoseStamped, None, False, True)
00187         pub.publish(self.grasp_pose_st_wam)
00188 
00189         # pre-grasp posture is relative to real_grasp pose
00190         pre_grasp_pose_st        = PoseStamped()
00191         pre_grasp_pose_st.header = self.grasp_pose_st_wam.header
00192 
00193         pre_grasp_pose_st.pose = homogeneous_product_pose_transform(self.grasp_pose_st_wam.pose,
00194                                                           build_transform_msg(0, 0, -0.08, 0, 0, 0, 1))
00195         pprint("PRE-Grasp modifier applied")
00196         pub = rospy.Publisher('/debug/grasp/pre_grasp', PoseStamped, None, False, True)
00197         pub.publish(pre_grasp_pose_st)
00198 
00199         # For both grasp and pre-grasp we need the inverse kinematics and get joinst positions
00200         try:
00201             joints_grasp     = get_inverse_kinematics_from_pose(self.grasp_pose_st_wam)
00202             joints_pre_grasp = get_inverse_kinematics_from_pose(pre_grasp_pose_st)
00203 
00204         #except NoKinematicSolutionException, e:
00205         except rospy.ServiceException, e:
00206             return 'no_ik_solution'
00207 
00208         userdata.sm_grasp_goal =  build_simple_pickup_goal(joints_grasp,
00209                                                         joints_pre_grasp,
00210                                                         self.fingers_grasp_configs)
00211         return 'success'
00212 
00213 class FirstAction(smach.State):
00214     def __init__(self):
00215         smach.State.__init__(self, outcomes    = ['ok','fail'],
00216                                    output_keys = ['pomdp_action','place_handler'])
00217 
00218     def execute(self, userdata):
00219         # Config and launch the deformable analysis
00220         request = obs2actionRequest()
00221         request.first       = True
00222         handler = rospy.ServiceProxy('/estirabot/skills/planner/obs2action', obs2action)
00223         response = handler(request)
00224 
00225         pprint(response)
00226         userdata.pomdp_action = response.action
00227         pub = rospy.Publisher('/log/pomdp/action', Int8, None, False, True)
00228         pub.publish(response.action)
00229 
00230         if (not response):
00231             return 'fail'
00232 
00233         return 'ok'
00234 
00235 class LogPCL(smach.State):
00236     def __init__(self):
00237         smach.State.__init__(self, outcomes=['success','fail'],
00238                                    input_keys=['sm_pcl_to_log'],
00239                                    output_keys=[''])
00240 
00241     def execute(self, userdata):
00242         # Log the PCL
00243         pub = rospy.Publisher('/log/pcl_table', PointCloud2,  None, False, True)
00244         pub.publish(userdata.sm_pcl_to_log)
00245         return 'success'
00246 
00247 
00248 class CalculateGrasp(smach.State):
00249     def __init__(self):
00250         smach.State.__init__(self, outcomes=['success','fail','no_ik_solution','all_ik_fail'],
00251                                    input_keys=['best_grasp_pose','sm_pomdp_config'],
00252                                    output_keys=['sm_pomdp_config','grasp_goal'])
00253         self.tf_manager = TransformManager()
00254 
00255     def execute(self, userdata):
00256         # shorcuts
00257         pomdp_config  = userdata.sm_pomdp_config
00258         grasp_pose_st = userdata.best_grasp_pose
00259 
00260         rospy.set_param('/estirabot/skills/grasp/fingers_configuration', pomdp_config.fingers_grasp_configs)
00261 
00262         # grasp_pose_st comes referecence to camera frame_id
00263         # we need to transform the message to wam base frame /wam_link0 
00264         grasp_pose_st_wam = self.tf_manager.transform_pose('/wam_link0', grasp_pose_st)
00265 
00266         # Orientation is fixed so ignoring previous
00267         grasp_pose_st_wam.pose.orientation.x = 0
00268         grasp_pose_st_wam.pose.orientation.y = 0
00269         grasp_pose_st_wam.pose.orientation.z = 0
00270         grasp_pose_st_wam.pose.orientation.w = 1.0
00271 
00272         pprint("Grasp original")
00273         pub = rospy.Publisher('/debug/grasp/original', PoseStamped, None, False, True)
00274         pub.publish(grasp_pose_st_wam)
00275 
00276         # real grasp is build applying grasp modifier to grasp_pose
00277         current_modifier     = pomdp_config.approach_config.grasp_modifier_used
00278         pprint("Using grasp modifier number: " + str(current_modifier))
00279         real_grasp_st        = PoseStamped()
00280         real_grasp_st.header = grasp_pose_st_wam.header
00281         real_grasp_st.pose   = homogeneous_product_pose_transform(grasp_pose_st_wam.pose,
00282                                                           pomdp_config.approach_config.grasp_modifiers[current_modifier])
00283         if (real_grasp_st.pose.position.z < -0.282):
00284             real_grasp_st.pose.position.z = -0.282
00285 
00286         pprint("Grasp modifier applied")
00287         pub = rospy.Publisher('/debug/grasp/real', PoseStamped, None, False, True)
00288         pub.publish(real_grasp_st)
00289 
00290         # pre-grasp posture is relative to real_grasp pose
00291         pre_grasp_pose_st        = PoseStamped()
00292         pre_grasp_pose_st.header = grasp_pose_st_wam.header
00293 
00294         pre_grasp_pose_st.pose = homogeneous_product_pose_transform(real_grasp_st.pose,
00295                                                           pomdp_config.approach_config.pre_grasp_modifier)
00296         pprint("PRE-Grasp modifier applied")
00297         pub = rospy.Publisher('/debug/grasp/pre_grasp', PoseStamped, None, False, True)
00298         pub.publish(pre_grasp_pose_st)
00299 
00300         # GRASP is Kinematic compliant so save and log the final configuration
00301         pub_config = rospy.Publisher('/log/pomdp_config', PomdpGraspConfig, None, False, True)
00302         pub_config.publish(pomdp_config)
00303 
00304         # For both grasp and pre-grasp we need the inverse kinematics and get joinst positions
00305         try:
00306             joints_grasp     = get_inverse_kinematics_from_pose(real_grasp_st)
00307             joints_pre_grasp = get_inverse_kinematics_from_pose(pre_grasp_pose_st)
00308 
00309         #except NoKinematicSolutionException, e:
00310         except rospy.ServiceException, e:
00311             # Let's go to next grasp_modifier (if any)
00312             if (current_modifier < len(pomdp_config.approach_config.grasp_modifiers)-1):
00313                 # Mark next configuration to use 
00314                 pomdp_config.approach_config.grasp_modifier_used = pomdp_config.approach_config.grasp_modifier_used + 1
00315                 pomdp_config.approach_config.pre_grasp_modifier
00316                 return 'no_ik_solution'
00317             else:
00318                 # all modifiers were tested and are not valid. Return error
00319                 pub = rospy.Publisher('/log/number_of_clothes', Int8, None, False, True)
00320                 pub.publish(0)
00321                 rospy.logerr("Inverse Kinematics has no solution")
00322                 return 'all_ik_fail'
00323 
00324         #     rospy.logerr("WamIK service failed")
00325         #           return 'fail'
00326 
00327         userdata.grasp_goal =  build_simple_pickup_goal(joints_grasp,
00328                                                         joints_pre_grasp,
00329                                                         pomdp_config.fingers_grasp_configs)
00330         return 'success'
00331 
00332 class CountObjects(smach.State):
00333     def __init__(self):
00334         smach.State.__init__(self, outcomes    = ['fail','success'],
00335                                    input_keys  = ['sm_pcl_table_left','sm_pcl_table_right'],
00336                                    output_keys = ['left_objects','right_objects','grasp_objects'])
00337         self.number = -1
00338         # Subscribe to count numbers
00339         sub = rospy.Subscriber("/estirabot/skills/iri_textile_count/num_objects_found",
00340                                Int32, self.recieve_number)
00341 
00342     def execute(self, userdata):
00343         # Left objects
00344         self.calculate_objects(userdata.sm_pcl_table_left)
00345         userdata.left_objects = self.number
00346         pprint ("Left objects: " + str(self.number))
00347         pub = rospy.Publisher('/debug/observation/left_objects', Int8, None, False, True)
00348         pub.publish(self.number)
00349 
00350         # sleep required for visualizing the histograms since they're published to the same topic
00351         # rospy.sleep(2)
00352 
00353         # Right objects
00354         self.calculate_objects(userdata.sm_pcl_table_right)
00355         userdata.right_objects = self.number
00356         pprint ("Right objects: " + str(self.number))
00357         pub = rospy.Publisher('/debug/observation/right_objects', Int8, None, False, True)
00358         pub.publish(self.number)
00359 
00360         userdata.grasp_objects = 0 #blind at grasp (but true since drop works 100%)
00361 
00362         return 'success'
00363 
00364     def recieve_number(self, data):
00365         self.number = data.data
00366 
00367     def calculate_objects(self, pcl):
00368         self.number = -1
00369         # Publish the pcl in /estirabot/skills/table/pcl
00370         pub = rospy.Publisher('/estirabot/skills/table/pcl', PointCloud2, None, False, True)
00371         pub.publish(pcl)
00372         # Wait to recieve the callback
00373         while (self.number == -1 and (not rospy.is_shutdown())):
00374             pprint("waiting")
00375             time.sleep(.1)
00376 
00377 class WeightObjects(smach.State):
00378     def __init__(self):
00379         smach.State.__init__(self, outcomes    = ['fail','success'],
00380                                    output_keys = ['left_objects','right_objects','grasp_objects'])
00381         self.number = -1
00382         # Subscribe to count numbers
00383         #sub = rospy.Subscriber("/estirabot/skills/iri_textile_count/num_objects_found",
00384         #                       Int32, self.recieve_number)
00385 
00386     def execute(self, userdata):
00387         keyserver = GetKeyStroke()
00388         self.number = -1
00389         print "Press [0-5] for clothes grabbed, 9 for error:"
00390         while (self.number < 0):
00391             self.number = keyserver()
00392             try:
00393                 self.number = int(self.number)
00394             except ValueError:
00395                 print "Error. Press [0-5] for clothes grabbed:"
00396                 continue
00397 
00398         print "Your value was: " + str(self.number)
00399         pub = rospy.Publisher('/debug/observation/grasp_objects', Int8, None, False, True)
00400         userdata.grasp_objects = self.number
00401         pub.publish(self.number)
00402 
00403         pub = rospy.Publisher('/debug/observation/left_objects', Int8, None, False, True)
00404         userdata.left_objects = self.number
00405         pub.publish(0) #unreliable data at table
00406 
00407         pub = rospy.Publisher('/debug/observation/right_objects', Int8, None, False, True)
00408         userdata.right_objects = self.number
00409         pub.publish(0) #unreliable data at table
00410 
00411         return 'success'
00412 
00413     def recieve_number(self, data):
00414         self.number = data.data
00415 
00416     def calculate_objects(self, pcl):
00417         self.number = -1
00418         # Publish the pcl in /estirabot/skills/table/pcl
00419         pub = rospy.Publisher('/estirabot/skills/table/pcl', PointCloud2, None, False, True)
00420         pub.publish(pcl)
00421         # Wait to recieve the callback
00422         while (self.number == -1 and (not rospy.is_shutdown())):
00423             pprint("waiting")
00424             time.sleep(.1)
00425 
00426 class PrePlace(smach.State):
00427     def __init__(self):
00428         smach.State.__init__(self, outcomes     = ['fail','success'],
00429                                    input_keys   = ['sm_pomdp_config'],
00430                                    output_keys   = ['pose_st'])
00431 
00432     def execute(self, userdata):
00433         tf = Transform()
00434         tf.translation.z = -0.4
00435 
00436         pose_stamped                 = PoseStamped()
00437         pose_stamped.header.frame_id = '/wam_link0'
00438         pose_stamped.header.stamp    = rospy.Time.now()
00439         pose_stamped.pose = homogeneous_product_pose_transform(userdata.sm_pomdp_config.place_point, tf)
00440 
00441         userdata.pose_st = pose_stamped
00442         return 'success'
00443 
00444 
00445 class UpdateBelieve(smach.State):
00446     def __init__(self):
00447         smach.State.__init__(self, outcomes     = ['fail','finish','continue'],
00448                                    input_keys   = ['left_objects','right_objects','grasp_objects'],
00449                                    output_keys  = ['pomdp_action'])
00450 
00451     def execute(self, userdata):
00452         request = obs2actionRequest()
00453         # Build observation
00454         right_objs = userdata.right_objects
00455         left_objs  = userdata.left_objects
00456         grasp_objs  = userdata.grasp_objects
00457 
00458         if (right_objs > 4):
00459             right_objs = 4
00460 
00461         if (left_objs > 4):
00462             left_objs = 4
00463         
00464         if (grasp_objs > 4):
00465             grasp_objs = 4
00466         
00467         request.first       = False
00468         request.observation = grasp_objs * 5 * 5 + right_objs + left_objs * 5
00469         pub = rospy.Publisher('/log/pomdp/observation', Int8, None, False, True)
00470         pub.publish(request.observation)
00471 
00472         pprint(request)
00473         handler = rospy.ServiceProxy('/estirabot/skills/planner/obs2action', obs2action)
00474         response = handler(request)
00475 
00476         if (not response):
00477             return 'fail'
00478 
00479         pprint(response)
00480         if (response.goal_reached == True):
00481             return 'finish'
00482     
00483         userdata.pomdp_action = response.action
00484         pub2 = rospy.Publisher('/log/pomdp/action', Int8, None, False, True)
00485         pub2.publish(response.action)
00486 
00487         return 'continue'
00488 
00489 def get_sm_place_right_goal_callback(userdata, default_goal):
00490     pose_stamped                 = PoseStamped()
00491     pose_stamped.header.frame_id = '/wam_link0'
00492     pose_stamped.header.stamp    = rospy.Time.now()
00493     pose_stamped.pose            = build_pose(0.4, -0.4, 0.3, 1, 0, 0, 0)
00494 
00495     goal = PlaceGoal()
00496     goal.place_locations.append(pose_stamped)
00497 
00498     return goal
00499 def get_sm_place_left_goal_callback(userdata, default_goal):
00500     pose_stamped                 = PoseStamped()
00501     pose_stamped.header.frame_id = '/wam_link0'
00502     pose_stamped.header.stamp    = rospy.Time.now()
00503     pose_stamped.pose            = build_pose(0.4, 0.4, 0.3, 1, 0, 0, 0)
00504 
00505     goal = PlaceGoal()
00506     goal.place_locations.append(pose_stamped)
00507 
00508     return goal
00509 
00510 
00511 def get_sm_place_init_goal_callback(userdata, default_goal):
00512     pose_stamped                 = PoseStamped()
00513     pose_stamped.header.frame_id = '/wam_link0'
00514     pose_stamped.header.stamp    = rospy.Time.now()
00515     pose_stamped.pose            = build_pose(0.4, -0.4, -0.23, 1, 0, 0, 0)
00516 
00517     goal = PlaceGoal()
00518     goal.place_locations.append(pose_stamped)
00519 
00520     return goal
00521 
00522 def get_sm_grasp_goal_callback(userdata, default_goal):
00523     return userdata.sm_grasp_goal
00524 
00525 def get_sm_place_goal_callback(userdata, default_goal):
00526     pose_stamped                 = PoseStamped()
00527     pose_stamped.header.frame_id = '/wam_link0'
00528     pose_stamped.header.stamp    = rospy.Time.now()
00529     pose_stamped.pose            = userdata.sm_pomdp_config.place_point
00530 
00531     goal = PlaceGoal()
00532     goal.place_locations.append(pose_stamped)
00533 
00534     return goal
00535 
00536 def construct_main_sm():
00537 
00538     factory_home = SM_ESTIRABOT_GoHome()
00539     sm_home = factory_home.build_sm()
00540     factory_move_cartesian = SM_WAM_MoveFromPose('/estirabot/wam_wrapper/joints_move','/estirabot/wam_ik/wamik')
00541     sm_move_cartesian = factory_move_cartesian.build_sm()
00542 
00543 
00544     sm = StateMachine(outcomes = ['succeeded','aborted'])
00545 
00546     with sm:
00547         # Create the place handler
00548         sm.userdata.place_handler = PlaceHandler()
00549 
00550         #TODO machine-in-machine instead of duplicates 
00551         #it's better to build up a standalone statie similar to DO_GRASP
00552         smach.StateMachine.add('TAKE_FROM_BASKET', TakeFromBasket(),
00553                 transitions = { 'success':'DO_GRASP_INIT',
00554                                 'no_ik_solution':'aborted',
00555                                 'fail':'aborted'})
00556         # 0.1 GRASP
00557         smach.StateMachine.add('DO_GRASP_INIT',
00558                                smach_ros.SimpleActionState('/estirabot/skills/grasp/pickup',
00559                                                           PickupAction,
00560                                                           goal_cb = get_sm_grasp_goal_callback,
00561                                                           input_keys=['sm_grasp_goal']),
00562                                {'succeeded': 'DO_LIFT_INIT',
00563                                 'preempted': 'aborted',
00564                                 'aborted'  : 'aborted'})
00565         # 0.2 LIFT
00566         smach.StateMachine.add('DO_LIFT_INIT', sm_home,
00567                         transitions={'success' : 'DO_PLACE_INIT',
00568                                      'aborted'    : 'aborted'})
00569         # 0.4 DO PLACE
00570         smach.StateMachine.add('DO_PLACE_INIT',
00571                        smach_ros.SimpleActionState('/estirabot/skills/iri_place/place',
00572                                                   PlaceAction,
00573                                                   goal_cb = get_sm_place_init_goal_callback),
00574                        {'succeeded': 'BACK_TO_HOME_INIT',
00575                         'preempted': 'aborted',
00576                         'aborted'  : 'aborted'})
00577 
00578         smach.StateMachine.add('BACK_TO_HOME_INIT', sm_home,
00579                           transitions={'success': 'GIVE_FIRST_ACTION',
00580                                        'aborted'   : 'aborted'})
00581 
00582         smach.StateMachine.add('GIVE_FIRST_ACTION', FirstAction(),
00583                 transitions = { 'ok':'START_ROUND',
00584                                 'fail':'aborted'},
00585                 remapping   = { 'pomdp_action' : 'pomdp_action'})
00586 
00587         smach.StateMachine.add('START_ROUND', sm_home,
00588                           transitions={'success': 'LOG_PCL',
00589                                        'aborted'   : 'aborted'})
00590         smach.StateMachine.add('LOG_PCL', 
00591                                 GetPCL("/estirabot/ceiling_kinect/camera/rgb/points"),
00592                 transitions = {'success' : 'LOG_IMAGE',
00593                                'fail'    : 'aborted'},
00594                 remapping   = {'pcl_RGB'  : 'sm_pcl_to_log'})
00595         smach.StateMachine.add('LOG_IMAGE', LogPCL(),
00596                           transitions={'success': 'TRANSLATE_POMDP_ACTION',
00597                                        'fail'   : 'aborted'})
00598 
00599         # 2. RUN POMDP ACTION
00600         smach.StateMachine.add('TRANSLATE_POMDP_ACTION', TranslatePomdp(),
00601             transitions = { 'image_from_left'  : 'DROP_LEFT',
00602                             'image_from_right' : 'DROP_RIGHT',
00603                             'drop':'DO_PLACE',
00604                             'fail':'aborted'},
00605             remapping   = { 'sm_pomdp_config' : 'sm_pomdp_config'})
00606 
00607 
00608         smach.StateMachine.add('DROP_LEFT',
00609                        smach_ros.SimpleActionState('/estirabot/skills/iri_place/place',
00610                                                   PlaceAction,
00611                                                   goal_cb = get_sm_place_left_goal_callback,
00612                                                   input_keys=['sm_pomdp_config']),
00613                        {'succeeded': 'GET_KINECT_IMAGE_FROM_LEFT',
00614                         'preempted': 'aborted',
00615                         'aborted'  : 'aborted'})
00616 
00617         smach.StateMachine.add('DROP_RIGHT',
00618                        smach_ros.SimpleActionState('/estirabot/skills/iri_place/place',
00619                                                   PlaceAction,
00620                                                   goal_cb = get_sm_place_right_goal_callback,
00621                                                   input_keys=['sm_pomdp_config']),
00622                        {'succeeded': 'GET_KINECT_IMAGE_FROM_RIGHT',
00623                         'preempted': 'aborted',
00624                         'aborted'  : 'aborted'})
00625         # 2. CALCULATE GRASP POINT
00626         # 2.1.a GET KINECT IMAGE FROM LEFT
00627         smach.StateMachine.add('GET_KINECT_IMAGE_FROM_LEFT', 
00628                                 GetPCL("/estirabot/skills/table/left/pcl"),
00629                 transitions = {'success' : 'PERFORM_ANALISYS',
00630                                'fail'    : 'aborted'},
00631                 remapping   = {'pcl_RGB'  : 'sm_pcl_output'})
00632 
00633         # 2.1.b GET KINECT IMAGE FROM RIGHT
00634         smach.StateMachine.add('GET_KINECT_IMAGE_FROM_RIGHT', 
00635                               GetPCL("/estirabot/skills/table/right/pcl"),
00636                 transitions = {'success' : 'PERFORM_ANALISYS',
00637                                'fail'    : 'aborted'},
00638                 remapping   = {'pcl_RGB'  : 'sm_pcl_output'})
00639 
00640         # 2.2 ANALYSIS
00641         smach.StateMachine.add('PERFORM_ANALISYS', PerformAnalysis(),
00642                 transitions = {'success'        : 'CALCULATE_GRASP',
00643                                'timeout'        : 'PERFORM_ANALISYS', # hack relaunch since descriptors died
00644                                'fail'           : 'aborted'},
00645                 remapping   = {'pcl_RGB'         : 'sm_pcl_output',
00646                                'best_grasp_pose' : 'sm_best_grasp_pose',
00647                                'deformable_config' : 'sm_pomdp_config'}) # compatibles
00648         # 2.3 CALCULATE GRASP
00649         smach.StateMachine.add('CALCULATE_GRASP', CalculateGrasp(),
00650                 transitions = {'success'        : 'DO_GRASP',
00651                                'no_ik_solution' : 'CALCULATE_GRASP',
00652                                'fail'           : 'aborted',
00653                                'all_ik_fail'    : 'GET_TABLE_IMAGE_FROM_LEFT'},
00654                 remapping   = {'pcl_RGB'         : 'sm_pcl_output',
00655                                'best_grasp_pose' : 'sm_best_grasp_pose',
00656                                'grasp_goal'      : 'sm_grasp_goal'})
00657         # 3.1 GRASP
00658         smach.StateMachine.add('DO_GRASP',
00659                                smach_ros.SimpleActionState('/estirabot/skills/grasp/pickup',
00660                                                           PickupAction,
00661                                                           goal_cb = get_sm_grasp_goal_callback,
00662                                                           input_keys=['sm_grasp_goal']),
00663                                {'succeeded': 'DO_LIFT',
00664                                 'preempted': 'aborted',
00665                                 'aborted'  : 'aborted'})
00666         # 3.2 LIFT
00667         smach.StateMachine.add('DO_LIFT', sm_home,
00668                         transitions={'success' : 'WEIGHT_OBJECTS',
00669                                      'aborted'    : 'aborted'})
00670         # 4.3 GET NUMBER OF OBJECTS
00671         smach.StateMachine.add('WEIGHT_OBJECTS', WeightObjects(),
00672                         transitions={'success' : 'UPDATE_BELIEVE_STATE',
00673                                      'fail'    : 'aborted'})
00674         # 3.3.1 DO PRE PLACE
00675         smach.StateMachine.add('DO_PRE_PLACE', PrePlace(),
00676                         transitions={'success' : 'DO_MOVE',
00677                                      'fail'    : 'aborted'},
00678                         remapping = {'pose_st' : 'sm_pose_st'})
00679 
00680         smach.StateMachine.add('DO_MOVE', sm_move_cartesian,
00681                         transitions={'success' : 'DO_PLACE',
00682                                      'aborted'    : 'aborted',
00683                                      'no_kinematic_solution'    : 'DO_PLACE'}, #TODO recompute pre place point 
00684                         remapping = {'pose_st' : 'sm_pose_st'})
00685         #
00686         # 3.3.2 DO PLACE
00687         smach.StateMachine.add('DO_PLACE',
00688                        smach_ros.SimpleActionState('/estirabot/skills/iri_place/place',
00689                                                   PlaceAction,
00690                                                   goal_cb = get_sm_place_goal_callback,
00691                                                   input_keys=['sm_pomdp_config']),
00692                        {'succeeded': 'BACK_TO_HOME',
00693                         'preempted': 'aborted',
00694                         'aborted'  : 'aborted'})
00695 
00696         smach.StateMachine.add('BACK_TO_HOME', sm_home,
00697                           transitions={'success': 'GET_TABLE_IMAGE_FROM_LEFT',
00698                                        'aborted'   : 'aborted'})
00699 
00700         # 4. OBSERVATION
00701         # 4.1 GET PCL FROM LEFT
00702         smach.StateMachine.add('GET_TABLE_IMAGE_FROM_LEFT', 
00703                       GetPCL("/estirabot/skills/table/left/pcl"),
00704                 transitions = {'success' : 'GET_TABLE_IMAGE_FROM_RIGHT',
00705                                'fail'    : 'aborted'},
00706                 remapping   = {'pcl_RGB'  : 'sm_pcl_table_left'})
00707         # 4.2 GET PCL FROM RIGHT
00708         smach.StateMachine.add('GET_TABLE_IMAGE_FROM_RIGHT', 
00709                       GetPCL("/estirabot/skills/table/right/pcl"),
00710                 transitions = {'success' : 'COUNT_OBJECTS',
00711                                'fail'    : 'aborted'},
00712                 remapping   = {'pcl_RGB'  : 'sm_pcl_table_right'})
00713         # 4.3 GET NUMBER OF OBJECTS
00714         smach.StateMachine.add('COUNT_OBJECTS', CountObjects(),
00715                         transitions={'success' : 'UPDATE_BELIEVE_STATE',
00716                                      'fail'    : 'aborted'})
00717         # 5 UPDATE BELIEVE STATE
00718         smach.StateMachine.add('UPDATE_BELIEVE_STATE', UpdateBelieve(),
00719                         transitions={'continue' : 'START_ROUND',
00720                                      'finish'   : 'succeeded',
00721                                      'fail'     : 'aborted'})
00722 
00723     return sm
00724 
00725 def main():
00726     rospy.init_node("pomdp_sm")
00727     sm_main = construct_main_sm()
00728 
00729     # Run state machine introspection server for smach viewer
00730     sis = smach_ros.IntrospectionServer('estirabot_smach_replicable', sm_main,
00731                                         '/estirabot_smach_replicable')
00732 
00733     sis.start()
00734 
00735     outcome = sm_main.execute()
00736 
00737     rospy.spin()
00738     sis.stop()
00739 
00740 if __name__ == "__main__":
00741     main()


estirabot_apps
Author(s): Jose Luis Rivero
autogenerated on Fri Dec 6 2013 23:20:59