move_arm.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 import roslib
00004 roslib.load_manifest( 'rospy' )
00005 roslib.load_manifest( 'rosparam' )
00006 roslib.load_manifest( 'actionlib' )
00007 roslib.load_manifest( 'kinematics_msgs' )
00008 roslib.load_manifest( 'trajectory_msgs' )
00009 roslib.load_manifest( 'geometry_msgs' )
00010 roslib.load_manifest( 'pr2_controllers_msgs' )
00011 roslib.load_manifest( 'tf' )
00012 roslib.load_manifest( 'sensor_msgs' )
00013 roslib.load_manifest( 'planning_environment_msgs' )
00014 roslib.load_manifest( 'motion_planning_msgs' )
00015 roslib.load_manifest( 'std_msgs' )
00016 
00017 import rospy
00018 import rosparam
00019 
00020 from actionlib import \
00021      SimpleActionClient, GoalStatus
00022 from kinematics_msgs.srv import \
00023     GetPositionIK, GetPositionIKRequest
00024 from trajectory_msgs.msg import \
00025     JointTrajectory, JointTrajectoryPoint
00026 from geometry_msgs.msg import \
00027     Pose, Point, Quaternion
00028 from pr2_controllers_msgs.msg import \
00029     JointTrajectoryAction, JointTrajectoryGoal
00030 from sensor_msgs.msg import JointState
00031 from planning_environment_msgs.srv import \
00032     GetJointTrajectoryValidity, GetJointTrajectoryValidityRequest, GetRobotState
00033 
00034 from motion_planning_msgs.srv import \
00035     FilterJointTrajectoryWithConstraints, FilterJointTrajectoryWithConstraintsRequest
00036 
00037 from std_msgs.msg import Int8
00038 
00039 import matplotlib.pyplot as plt
00040 import numpy as np
00041 from math import cos, sin
00042 import random
00043 
00044 import sys
00045 
00046 def getJointNames( controller_name ):
00047     return rosparam.get_param( ''.join( (controller_name, '/joints') ) ) 
00048 
00049 def rpyToQuaternion( r, p, y ):
00050     q = [0] * 4
00051     q[0] = cos(r/2)*cos(p/2)*cos(y/2)+sin(r/2)*sin(p/2)*sin(y/2)
00052     q[1] = sin(r/2)*cos(p/2)*cos(y/2)-cos(r/2)*sin(p/2)*sin(y/2)
00053     q[2] = cos(r/2)*sin(p/2)*cos(y/2)+sin(r/2)*cos(p/2)*sin(y/2)
00054     q[3] = cos(r/2)*cos(p/2)*sin(y/2)-sin(r/2)*sin(p/2)*cos(y/2)
00055     return q
00056 
00057 class TrajectoryFilter:
00058     
00059     def __init__( self, service_name ):
00060         rospy.loginfo( 'waiting for service: %s'%service_name )
00061         rospy.wait_for_service( service_name )
00062         self.proxy = rospy.ServiceProxy( service_name, FilterJointTrajectoryWithConstraints )
00063 
00064     def filter( self, trajectory ):
00065         # rospy.loginfo( 'filtering trajectory:\n %s'%trajectory )
00066         request = FilterJointTrajectoryWithConstraintsRequest()
00067         request.allowed_time = rospy.Duration.from_sec(1.0);
00068         request.trajectory = trajectory
00069         try:
00070             response = self.proxy( request )
00071             
00072             if response.error_code.val == response.error_code.SUCCESS:
00073                 return response.trajectory
00074             else:
00075                 rospy.logerr( 'Trajectory was not filtered! (error: %s)'%response.error_code.val )
00076                 return None
00077 
00078         except rospy.ServiceException, e:
00079             rospy.logerr( 'service call failed: %s'%e)
00080             return None
00081         
00082     
00083 class ArmIK:
00084     
00085     def __init__( self, controller_name, service_name ):
00086         rospy.loginfo( 'waiting for service: %s'%service_name )
00087         rospy.wait_for_service( service_name )
00088         self.proxy = rospy.ServiceProxy( service_name, GetPositionIK )
00089 
00090         # handle joint states for seek 
00091         self.joint_names = getJointNames( controller_name )
00092         self.joint_idx = None
00093         self.positions = None
00094         rospy.Subscriber( '/joint_states', JointState, self.js_callback )
00095 
00096         # set static fields of request
00097         self.request = GetPositionIKRequest()
00098         self.request.timeout = rospy.Duration.from_sec( 5.0 )
00099         self.request.ik_request.ik_link_name = 'r_wrist_roll_link'
00100         self.request.ik_request.pose_stamped.header.frame_id = "torso_lift_link"
00101         self.request.ik_request.ik_seed_state.joint_state.name = self.joint_names
00102         self.request.ik_request.ik_seed_state.joint_state.position = [0] * len( self.joint_names )
00103 
00104     def js_callback( self, msg ):
00105         if self.joint_idx is None:
00106             self.joint_idx = map( msg.name.index, self.joint_names )
00107         
00108         self.positions = map( lambda x : msg.position[x], self.joint_idx )
00109 
00110     def getJointNames( self ):
00111         return self.joint_names
00112 
00113     def getJointPositions( self ):
00114         return self.positions
00115     
00116     def getSolution( self, pose ):
00117         rospy.logdebug( 'requesting IK solution for pose:\n %s'%pose )
00118         self.request.ik_request.pose_stamped.pose = pose
00119 
00120         # set seed to current joint positions
00121         if not self.positions is None:
00122             self.request.ik_request.ik_seed_state.joint_state.position = self.positions
00123 
00124         rospy.logdebug( 'seed IK with: %s'%self.request.ik_request.ik_seed_state.joint_state.position )
00125 
00126         try:
00127             response = self.proxy( self.request )
00128             
00129             if response.error_code.val == response.error_code.SUCCESS:
00130                 return np.asarray( response.solution.joint_state.position )
00131             else:
00132                 rospy.logerr( 'IK failed! (error: %s)'%response.error_code.val )
00133                 return None
00134 
00135         except rospy.ServiceException, e:
00136             rospy.logerr( 'service call failed: %s'%e)
00137             return None
00138     
00139     def get2PointTrajectory( self, positions, time_from_start ):
00140         if self.positions is None or positions is None:
00141             return None
00142         jt = JointTrajectory()
00143         jt.joint_names = self.joint_names
00144         jt.points = []
00145         jp = JointTrajectoryPoint()
00146         jp.time_from_start = rospy.Time.from_seconds( 0.0 )
00147         jp.positions = self.positions
00148         jt.points.append( jp )
00149         jp = JointTrajectoryPoint()
00150         jp.time_from_start = rospy.Time.from_seconds( time_from_start )
00151         jp.positions = positions
00152         jt.points.append( jp )
00153         jt.header.stamp = rospy.Time.now()
00154         return jt
00155 
00156 class TrajectoryArmController:
00157     
00158     def __init__( self, controller_name ):
00159         topic = ''.join( ( controller_name, '/joint_trajectory_action' ) )
00160         self.client = SimpleActionClient( topic, JointTrajectoryAction )
00161         rospy.loginfo( 'waiting for action client: %s'%topic )
00162         self.client.wait_for_server()
00163         
00164     def move( self, trajectory ):
00165         # push trajectory goal to ActionServer
00166         goal = JointTrajectoryGoal()
00167         goal.trajectory = trajectory
00168         goal.trajectory.header.stamp = rospy.Time.now()
00169 
00170         self.client.send_goal( goal )
00171         self.client.wait_for_result()
00172     
00173         if self.client.get_state == GoalStatus.SUCCEEDED:
00174             rospy.logerr( 'failed to move arm to goal:\n %s'%goal )
00175             return False
00176         else:
00177             return True
00178 
00179 class PlanningEnvironment:
00180     
00181     def __init__( self, controller_name, node_name ):
00182         service = ''.join( (node_name, '/get_trajectory_validity') )
00183         rospy.loginfo( 'waiting for service: %s'%service )
00184         rospy.wait_for_service( service )
00185         self.validity_proxy = rospy.ServiceProxy( service, GetJointTrajectoryValidity )
00186 
00187         service = ''.join( (node_name, '/get_robot_state') )
00188         rospy.loginfo( 'waiting for service: %s'%service )
00189         rospy.wait_for_service( service )
00190         self.state_proxy = rospy.ServiceProxy( service, GetRobotState )
00191 
00192         self.joint_names = getJointNames( controller_name )        
00193                 
00194         # set static fields of request
00195         self.request = GetJointTrajectoryValidityRequest()
00196         self.request.robot_state.joint_state.name = self.joint_names
00197         self.request.check_collisions = True
00198         #self.request.check_joint_limits = True
00199         
00200     def check( self, trajectory ):
00201         # rospy.loginfo( 'check joint positions %s for collision'%positions )
00202         
00203         self.request.robot_state = self.getRobotState()
00204 
00205         self.request.trajectory = trajectory
00206 
00207         try:
00208             response = self.validity_proxy( self.request )
00209             
00210             if response.error_code.val == response.error_code.SUCCESS:
00211                 return True
00212             else:
00213                 rospy.logerr( 'Joint-trajectory in collision! (error: %s)'%response.error_code.val )
00214                 return False
00215 
00216         except rospy.ServiceException, e:
00217             rospy.logerr( 'service call failed: %s'%e)
00218             return False
00219 
00220     def getRobotState( self ):
00221         try:
00222             response = self.state_proxy()
00223             return response.robot_state
00224 
00225             # if response.error_code.val == response.error_code.SUCCESS:
00226             #     return response.robot_state
00227             # else:
00228             #     rospy.logerr( 'Can\'t get robot state! (error: %s)'%response.error_code.val )
00229             #     return False
00230 
00231         except rospy.ServiceException, e:
00232             rospy.logerr( 'service call failed: %s'%e)
00233             return None
00234         
00235 
00236 def plotTrajectory( trajectory ):
00237     P = []
00238     for tp in trajectory.points:
00239         P.append( tp.positions )
00240     P = np.asarray( P )
00241     print P.transpose()
00242     plt.plot( P )
00243     plt.show
00244 
00245 
00246 if __name__ == '__main__':
00247     node_name = 'move_arm'
00248     controller_name = 'r_arm_controller'
00249     rospy.init_node( node_name, log_level = rospy.DEBUG )
00250     
00251     controller = TrajectoryArmController( controller_name )
00252     ik = ArmIK( 'r_arm_controller', 'pr2_right_arm_kinematics/get_ik' )
00253     planning = PlanningEnvironment( controller_name, 
00254                                     'environment_server_right_arm' )
00255     traj_filter = TrajectoryFilter( 'trajectory_filter/filter_trajectory_with_constraints' )
00256 
00257     update_pub = rospy.Publisher( '/joint_state_viz/update', Int8 )
00258 
00259     random.random()
00260 
00261     counter = 0
00262 
00263     joint_names = getJointNames( controller_name )
00264 
00265     positions = None
00266     while positions == None:
00267         positions = ik.getJointPositions()
00268     
00269     joint_names = ik.getJointNames()
00270 
00271     last_point = JointTrajectoryPoint()
00272     last_point.positions = positions
00273 
00274 
00275 
00276     soft_lower_limit = -2.1353981634
00277     soft_upper_limit = 0.564601836603
00278 
00279     soft_lower_limit = -np.pi
00280     soft_upper_limit = np.pi
00281     joint_id = joint_names.index( 'r_forearm_roll_joint' )
00282     i = 0
00283 
00284     while not rospy.is_shutdown():
00285         i = i + 1
00286 
00287         print( '----- %d -----'%i )
00288     
00289         pos = np.random.rand() * ( soft_upper_limit - soft_lower_limit ) + soft_lower_limit
00290         rospy.loginfo( 'move to pos %6.4f'%pos )
00291     
00292         jt = JointTrajectory()
00293         jt.joint_names = joint_names
00294         jt.points = []
00295         last_point.time_from_start = rospy.Time.from_seconds( 0.0 )
00296         jt.points.append( last_point )
00297             
00298         jp = JointTrajectoryPoint()
00299         jp.time_from_start = rospy.Time.from_seconds( 5.0 )
00300         jp.positions = last_point.positions
00301         jp.positions[joint_id] = pos
00302         jt.points.append( jp )
00303         jt.header.stamp = rospy.Time.now()
00304 
00305         update_pub.publish( 0 )
00306         rospy.sleep( 1 )
00307         controller.move( jt )
00308         rospy.sleep( 2 )
00309         update_pub.publish( 1 )
00310 
00311         last_point = jp
00312 
00313     # while not rospy.is_shutdown():
00314 
00315     #     trajectory = JointTrajectory()
00316     #     trajectory.points = []
00317     #     trajectory.joint_names = joint_names
00318 
00319     #     last_point.time_from_start = rospy.Time().from_sec( 0.0 )
00320     #     trajectory.points.append( last_point )
00321 
00322     #     while len( trajectory.points ) < 3:
00323 
00324     #         x = random.random()
00325     #         y = random.random() * 2.0 - 1.0
00326     #         z = random.random() - 0.5
00327 
00328     #         roll = random.random() * 2 * np.pi - np.pi
00329     #         pitch = random.random() * 2 * np.pi - np.pi
00330     #         yaw = random.random() * 2 * np.pi - np.pi
00331 
00332     #         q = rpyToQuaternion( roll, pitch, yaw )
00333                 
00334     #         pose = Pose( position = Point( x, y, z),
00335     #                      orientation = Quaternion( q[0], q[1], q[2], q[3] ) )
00336 
00337     #         positions = ik.getSolution( pose )
00338 
00339     #         if not positions is None:
00340     #             tp = JointTrajectoryPoint()
00341     #             tp.positions = positions
00342     #             tp.time_from_start = rospy.Time.from_sec( len( trajectory.points ) * 1.0 )
00343     #             trajectory.points.append( tp )
00344 
00345     #     last_point = trajectory.points[-1]
00346     #     trajectory.header.stamp = rospy.Time.now()
00347 
00348 
00349     #     trajectory = traj_filter.filter( trajectory )
00350     #     if not trajectory is None:
00351     #         if planning.check( trajectory ):
00352     #             trajectory.header.stamp = rospy.Time.now()
00353     #             print trajectory.points[-1].time_from_start.to_sec()
00354     #             controller.move( trajectory )
00355 
00356 
00357 
00358 
00359     # while not rospy.is_shutdown():
00360     #     x = random.random()
00361     #     y = random.random() * 2.0 - 1.0
00362     #     z = random.random() - 0.5
00363 
00364     #     roll = random.random() * 2 * np.pi - np.pi
00365     #     pitch = random.random() * 2 * np.pi - np.pi
00366     #     yaw = random.random() * 2 * np.pi - np.pi
00367 
00368     #     q = rpyToQuaternion( roll, pitch, yaw )
00369                 
00370     #     pose = Pose( position = Point( x, y, z),
00371     #                  orientation = Quaternion( q[0], q[1], q[2], q[3] ) )
00372 
00373     #     positions = ik.getSolution( pose )
00374 
00375     #     if not positions is None:
00376             
00377     #         print 'get two point trajectory ...'
00378     #         trajectory = ik.get2PointTrajectory( positions, 1.0 )
00379     #         print 'done!'
00380 
00381     #         if not trajectory is None:
00382 
00383     #             # # filter trajectory
00384     #             # print 'filter trajectory ...'
00385     #             # trajectory = traj_filter.filter( trajectory )
00386     #             # print 'done!'
00387 
00388     #             if not trajectory is None:
00389     #                 if planning.check( trajectory ):
00390 
00391     #                     update_pub.publish( 0 )
00392 
00393     #                     rospy.sleep( 2 )
00394                         
00395     #                     controller.move( trajectory )
00396 
00397     #                     rospy.sleep( 2 )
00398 
00399     #                     update_pub.publish( 1 )
00400 
00401     #                     counter = counter + 1
00402     #                     print( '----- %d ----- '%counter )
00403 
00404     #                     if counter == 100:
00405     #                         sys.exit()
00406 


kelsey_sandbox
Author(s): kelsey
autogenerated on Wed Nov 27 2013 11:52:04