urdf_arm_darpa_m3.py
Go to the documentation of this file.
00001 #   Copyright 2013 Georgia Tech Research Corporation
00002 #
00003 #   Licensed under the Apache License, Version 2.0 (the "License");
00004 #   you may not use this file except in compliance with the License.
00005 #   You may obtain a copy of the License at
00006 #
00007 #     http://www.apache.org/licenses/LICENSE-2.0
00008 #
00009 #   Unless required by applicable law or agreed to in writing, software
00010 #   distributed under the License is distributed on an "AS IS" BASIS,
00011 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 #   See the License for the specific language governing permissions and
00013 #   limitations under the License.
00014 #
00015 #  http://healthcare-robotics.com/
00016 
00017 # Author: Marc Killpack, Advait Jain, Philip Grice
00018 
00019 import numpy as np, math
00020 from threading import RLock, Timer
00021 import sys, copy
00022 
00023 import roslib; roslib.load_manifest('hrl_haptic_mpc')
00024 import rospy
00025 import tf
00026 
00027 from sensor_msgs.msg import JointState
00028 
00029 from visualization_msgs.msg import Marker
00030 
00031 from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
00032 from std_msgs.msg import Empty
00033 
00034 from equilibrium_point_control.hrl_arm import HRLArm
00035 from pykdl_utils.kdl_kinematics import create_kdl_kin
00036 from hrl_msgs.msg import FloatArrayBare
00037 import hrl_lib.viz as hv
00038 
00039 class URDFArm(HRLArm):
00040 
00041     def __init__(self, arm, tf_listener=None, base_link=None, end_link=None):
00042         if not arm in ['l', 'r']:
00043             raise Exception, 'Arm should be "l" or "r"'
00044         
00045         if base_link is None:
00046             self.base_link = '/torso_lift_link'
00047         else: 
00048             self.base_link = base_link
00049             
00050         if end_link is None:
00051             self.end_link = arm + '_gripper_tool_frame'
00052         else:        
00053             self.end_link = end_link
00054             
00055         kinematics = create_kdl_kin(self.base_link, self.end_link)
00056         HRLArm.__init__(self, kinematics)
00057         self.joint_names_list = kinematics.get_joint_names()
00058         self.torso_position = None
00059         self.arm_efforts = None
00060         self.delta_jep = None
00061             
00062         try:
00063             if len(self.joint_names_list) == 9:
00064                 self.kp = [rospy.get_param('crona_torso_traj_controller/gains/'+nm+'/p') for nm in self.joint_names_list[:3]]
00065                 self.kp += [rospy.get_param(arm+'_arm_controller/gains/'+nm+'/p') for nm in self.joint_names_list[3:]] # crona testing
00066             else:
00067                 self.kp = [rospy.get_param(arm+'_arm_controller/gains/'+nm+'/p') for nm in self.joint_names_list]
00068         except:
00069             print "kp is not on param server ... exiting"
00070             assert(False)
00071     #        max_kp =  np.max(self.kp)
00072 
00073         if len(self.joint_names_list) == 9: # quick hack to change "weighting" on joints by changing the interpreted stiffness values
00074             self.kp = [100. for i in range(3)]
00075             self.kp += [50. for i in [3,4,5,6,7,8]] 
00076         else:
00077             self.kp = [50. for i in range(len(self.joint_names_list))]
00078 
00079         try:
00080             if len(self.joint_names_list) == 9:
00081                 self.kd = [rospy.get_param('crona_torso_traj_controller/gains/'+nm+'/d') for nm in self.joint_names_list[:3]]
00082                 self.kd += [rospy.get_param(arm+'_arm_controller/gains/'+nm+'/d') for nm in self.joint_names_list[3:]] # crona testing
00083             else:
00084                 self.kd = [rospy.get_param(arm+'_arm_controller/gains/'+nm+'/d') for nm in self.joint_names_list]
00085         except:
00086             print "kd is not on param server ... exiting"
00087             assert(False)
00088             
00089         rospy.Subscriber('/joint_states', JointState, self.joint_states_cb)
00090 
00091         # Set desired joint angle - either through a delta from the current position, or as an absolute value.
00092         rospy.Subscriber ("/haptic_mpc/q_des", FloatArrayBare, self.set_ep_callback)
00093         rospy.Subscriber ("/haptic_mpc/delta_q_des", FloatArrayBare, self.set_delta_ep_callback)
00094         #rospy.Subscriber("/delta_jep_mpc_cvxgen", FloatArrayBare, self.set_ep_callback)
00095 
00096         self.marker_pub = rospy.Publisher(arm+'_arm/viz/markers', Marker)
00097         self.cep_marker_id = 1
00098 
00099         try:
00100           if tf_listener == None:
00101             self.tf_lstnr = tf.TransformListener()
00102           else:
00103             self.tf_lstnr = tf_listener
00104         except rospy.ServiceException, e:
00105           rospy.loginfo("ServiceException caught while instantiating a TF listener. This seems to be normal.")
00106           pass
00107 
00108         self.joint_angles_pub = rospy.Publisher(arm+'_arm_controller/command',
00109                                                 JointTrajectory)
00110         if len(self.joint_names_list) == 9:
00111             self.torso_ja_pub = rospy.Publisher('/crona_torso_traj_controller/command',JointTrajectory) # crona testing
00112     ##
00113     # Callback for /joint_states topic. Updates current joint
00114     # angles and efforts for the arms constantly
00115     # @param data JointState message recieved from the /joint_states topic
00116     def joint_states_cb(self, data):
00117         arm_angles = []
00118         arm_efforts = []
00119         arm_vel = []
00120         jt_idx_list = [0]*len(self.joint_names_list)
00121         for i, jt_nm in enumerate(self.joint_names_list):
00122             jt_idx_list[i] = data.name.index(jt_nm)
00123 
00124         for i, idx in enumerate(jt_idx_list):
00125             if data.name[idx] != self.joint_names_list[i]:
00126                 raise RuntimeError('joint angle name does not match.')
00127             arm_angles.append(data.position[idx])
00128             arm_efforts.append(data.effort[idx])
00129             arm_vel.append(data.velocity[idx])
00130 
00131         with self.lock:
00132             self.q = arm_angles
00133             self.arm_efforts = arm_efforts
00134             self.qdot = arm_vel
00135             
00136             if self.base_link == 'torso_chest_link': # if/else statement is here because self.base_link is 'torso_chest_link and not 'torso_chest_joint'
00137                 torso_idx = data.name.index('torso_chest_joint')
00138             elif self.base_link == 'base_link':
00139                 torso_idx = data.name.index('base_rev_joint') # crona testing
00140             elif self.base_link == 'torso_lift_link':
00141                 torso_idx = data.name.index('torso_lift_joint')
00142             else:
00143                 torso_idx = data.name.index('torso_lift_joint')            
00144                 #torso_idx = data.name.index(self.base_link)
00145                 
00146             self.torso_position = data.position[torso_idx]
00147 
00148     def set_ep(self, jep, duration=0.15):
00149         jep = copy.copy(jep)
00150         if jep is None or len(jep) != len(self.joint_names_list):
00151             raise RuntimeError("set_jep value is " + str(jep))
00152 
00153         with self.lock:
00154             if len(self.joint_names_list) == 9: 
00155                 arm_trajectory = JointTrajectory()
00156                 arm_trajectory.joint_names = self.joint_names_list[3:]
00157                 jtp = JointTrajectoryPoint()
00158                 jtp.positions = jep[3:]
00159                 jtp.time_from_start = rospy.Duration(duration)
00160                 arm_trajectory.points.append(jtp)
00161                 self.joint_angles_pub.publish(arm_trajectory)
00162 
00163                 torso_trajectory = JointTrajectory()
00164                 torso_trajectory.joint_names = self.joint_names_list[:3]
00165                 jtp = JointTrajectoryPoint()
00166                 jtp.positions = jep[:3]
00167                 jtp.time_from_start = rospy.Duration(duration)
00168                 torso_trajectory.points.append(jtp)
00169                 self.torso_ja_pub.publish(torso_trajectory)
00170 
00171                 self.ep = jep
00172             else:
00173                 trajectory = JointTrajectory()
00174                 trajectory.joint_names = self.joint_names_list
00175                 jtp = JointTrajectoryPoint()
00176                 jtp.positions = jep
00177                 jtp.time_from_start = rospy.Duration(duration)
00178                 trajectory.points.append(jtp)
00179                 self.joint_angles_pub.publish(trajectory)
00180                 self.ep = jep
00181 
00182     def set_delta_ep_callback(self, msg):
00183         delta_jep = msg.data
00184         
00185         if self.ep == None:
00186             self.ep = self.get_joint_angles()
00187         des_jep = (np.array(self.ep) + np.array(delta_jep)).tolist()
00188         
00189         self.set_ep(des_jep)
00190         
00191 #        delta_jep = copy.copy(msg.data)
00192 #        if delta_jep is None or len(delta_jep) != len(self.joint_names_list):
00193 #            raise RuntimeError("set_jep value is " + str(delta_jep))
00194 #
00195 #        with self.lock:
00196 #            if self.ep == None:
00197 #              self.ep = self.get_joint_angles()
00198 #            jep = (np.array(self.ep) + np.array(delta_jep)).tolist()
00199 #            trajectory = JointTrajectory()
00200 #            trajectory.joint_names = self.joint_names_list
00201 #            jtp = JointTrajectoryPoint()
00202 #            jtp.positions = jep
00203 #            jtp.time_from_start = rospy.Duration(0.15)
00204 #            trajectory.points.append(jtp)
00205 #            self.joint_angles_pub.publish(trajectory)
00206 #            self.ep = jep
00207 
00208     def set_ep_callback(self, msg):
00209         des_jep = msg.data        
00210         self.set_ep(des_jep)
00211         
00212         
00213 #        with self.lock:
00214 #            des_jep = copy.copy(msg.data)
00215 #            if des_jep is None or len(des_jep) != len(self.joint_names_list):
00216 #                raise RuntimeError("set_jep value is " + str(des_jep))
00217 ##            self.delta_jep = des_jep
00218 #            jep = (np.array(des_jep)).tolist()
00219 #            trajectory = JointTrajectory()
00220 #            trajectory.joint_names = self.joint_names_list
00221 #            jtp = JointTrajectoryPoint()
00222 #            jtp.positions = jep
00223 #            jtp.time_from_start = rospy.Duration(0.15)
00224 #            trajectory.points.append(jtp)
00225 #            self.joint_angles_pub.publish(trajectory)
00226 #            self.ep = jep
00227 
00228     def wrap_angles(self, q):
00229         for ind in [4, 6]:
00230             while q[ind] < -np.pi:
00231                 q[ind] += 2*np.pi
00232             while q[ind] > np.pi:
00233                 q[ind] -= 2*np.pi
00234         return q
00235 
00236     def publish_rviz_markers(self):
00237         # publish the CEP marker.
00238         o = np.matrix([0.,0.,0.,1.]).T
00239         jep = self.get_ep()
00240         cep, r = self.kinematics.FK(jep)
00241         cep_marker = hv.single_marker(cep, o, 'sphere',
00242                         self.base_link, color=(0., 0., 1., 1.),
00243                         scale = (0.02, 0.02, 0.02), duration=0.,
00244                         m_id=1)
00245         cep_marker.header.stamp = rospy.Time.now()
00246         self.marker_pub.publish(cep_marker)
00247 
00248         q = self.get_joint_angles()
00249         ee, r = self.kinematics.FK(q)
00250         ee_marker = hv.single_marker(ee, o, 'sphere',
00251                         self.base_link, color=(0., 1., 0., 1.),
00252                         scale = (0.02, 0.02, 0.02), duration=0.,
00253                         m_id=2)
00254         ee_marker.header.stamp = rospy.Time.now()
00255         self.marker_pub.publish(ee_marker)
00256 
00257 
00258 if __name__ == '__main__':
00259     rospy.init_node('pr2_arms_test')
00260     robot = URDFArm('l')
00261 
00262     if False:
00263         jep = [0.] * len(robot.joint_names_list) 
00264         jep = np.radians([-30, 0, -90, -60, 0, 0, 0])
00265         rospy.loginfo('Going to home location.')
00266         raw_input('Hit ENTER to go')
00267         robot.set_ep(jep, duration=2.)
00268 
00269     if True:
00270         # simple go_jep example
00271         roslib.load_manifest('equilibrium_point_control')
00272         import equilibrium_point_control.epc as epc
00273         epcon = epc.EPC(robot)
00274 
00275         while robot.get_joint_angles() == None:
00276             rospy.sleep(0.1)
00277 
00278         q = robot.get_joint_angles()
00279         robot.set_ep(q)
00280 
00281         jep = [0.] * len(robot.joint_names_list)
00282         #jep = np.radians([30, 0, 90, -60, -180, -30, 0])  # for left arm
00283         #jep = np.radians([-30, 0, -90, -60, 0, 0, 0]) # for right arm
00284         epcon.go_jep(jep, speed=math.radians(10.))
00285 
00286     if True:
00287         while robot.get_joint_angles() == None:
00288             rospy.sleep(0.1)
00289 
00290         q = robot.get_joint_angles()
00291         ee, r = robot.kinematics.FK(q)
00292         print "ee is at :\n", ee
00293         print "r is :\n", r
00294 


hrl_haptic_mpc
Author(s): Jeff Hawke, Phillip Grice, Marc Killpack, Advait Jain. Advisor and Co-author: Prof. Charlie Kemp. Healthcare Robotics Lab, Georgia Tech
autogenerated on Wed Nov 27 2013 12:27:09