def waitForInitialPose(self, next_topic, timeout=None):
counter = 0
while not rospy.is_shutdown():
counter = counter + 1
if timeout and counter >= timeout:
return False
try:
self.marker_lock.acquire()
self.initialize_poses = True
topic_suffix = next_topic.split("/")[-1]
if self.initial_poses.has_key(topic_suffix):
self.pre_pose = PoseStamped(pose=self.initial_poses[topic_suffix])
self.initialize_poses = False
return True
else:
rospy.logdebug(self.initial_poses.keys())
rospy.loginfo("Waiting for pose topic of '%s' to be initialized",
topic_suffix)
rospy.sleep(1)
finally:
self.marker_lock.release()
python类sleep()的实例源码
def __init__(self):
State.__init__(self, outcomes=['success'], input_keys=['waypoints'], output_keys=['waypoints'])
# Create publsher to publish waypoints as pose array so that you can see them in rviz, etc.
self.poseArray_publisher = rospy.Publisher('/waypoints', PoseArray, queue_size=1)
# Start thread to listen for reset messages to clear the waypoint queue
def wait_for_path_reset():
"""thread worker function"""
global waypoints
while not rospy.is_shutdown():
data = rospy.wait_for_message('/path_reset', Empty)
rospy.loginfo('Recieved path RESET message')
self.initialize_path_queue()
rospy.sleep(3) # Wait 3 seconds because `rostopic echo` latches
# for three seconds and wait_for_message() in a
# loop will see it again.
reset_thread = threading.Thread(target=wait_for_path_reset)
reset_thread.start()
stacking_blocks.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def zero_sensor(self):
rospy.loginfo("Zeroing sensor...")
# Wait a little bit until we get a message from the sensor
rospy.sleep(1)
self.tip_offset, self.inside_offset = (np.zeros_like(self.tip),
np.zeros_like(self.inside))
inside_vals, tip_vals = [], []
r = rospy.Rate(10)
while not rospy.is_shutdown() and len(inside_vals) < 10:
inside, tip = self.inside, self.tip
# If there are zero values (most likely becase a message
# has not yet been received), skip that. We could also
# initialize them with nans to find out if there's a
# problem
if all(inside) and all(tip):
inside_vals.append(inside)
tip_vals.append(tip)
r.sleep()
# Center around 5000, so ranges are similar to when not centering
self.inside_offset = np.min(inside_vals, axis=0) - 5000
self.tip_offset = np.min(tip_vals, axis=0) - 5000
rospy.loginfo("Zeroing finished")
baxter_cube_calibration.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def y_block_side_scan(self, pose, direction=(0,0,1), y_dir=0.005, sensor_index=13, max_inside = 1000, timeout=50):
while True:
if(not self.sensors_updated()):
return
#rospy.loginfo("Moving to touch (at {})".format(self.inside[6]))
if self.inside[sensor_index] < max_inside:
return
else:
scaled_direction = (di / 100 for di in direction)
#print("Scaled direction: ", scaled_direction)
v_cartesian = self._vector_to(scaled_direction)
v_cartesian[0] = y_dir
#print("cartesian: ", v_cartesian)
v_joint = self.compute_joint_velocities(v_cartesian)
#print("joint : ", v_joint)
self.limb.set_joint_velocities(v_joint)
rospy.sleep(0.25)
demo_graspEventdetect.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def limb_pose(limb_name):
"""Get limb pose at time of OK cuff button press."""
button = CuffOKButton(limb_name)
rate = rospy.Rate(20) # rate at which we check whether button was
# pressed or not
rospy.loginfo(
'Waiting for %s OK cuff button press to save pose' % limb_name)
while not button.pressed and not rospy.is_shutdown():
rate.sleep()
joint_pose = baxter_interface.Limb(limb_name).joint_angles()
# Now convert joint coordinates to end effector cartesian
# coordinates using forward kinematics.
kinematics = baxter_kinematics(limb_name)
endpoint_pose = kinematics.forward_position_kinematics(joint_pose)
# How is this different from
# baxter_interface.Limb(limb_name).endpoint_pose()
print()
print('baxter_interface endpoint pose:')
print(baxter_interface.Limb(limb_name).endpoint_pose())
print('pykdl forward kinematics endpoint pose:')
print(endpoint_pose)
print()
return endpoint_pose
demo_graspEventdetect.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def pick(self, pose, direction=(0, 0, 1), distance=0.1, controller=None):
"""Go to pose + pick_direction * pick_distance, open, go to pose,
close, go to pose + pick_direction * pick_distance.
"""
print(pose)
pregrasp_pose = self.translate(pose, direction, distance)
print(pregrasp_pose)
self.limb.set_joint_position_speed(0.1)
self.move_ik(pregrasp_pose)
# We want to block end effector opening so that the next
# movement happens with the gripper fully opened.
self.gripper.open(block=True)
self.limb.set_joint_position_speed(0.05)
self.move_ik(pose)
if controller is not None:
print ('controller ON!!')
controller.enable()
rospy.sleep(5)
controller.disable()
self.gripper.close(block=True)
#self.gripper.command_position(45, block=True)
rospy.sleep(2)
#self.move_ik(pregrasp_pose)
demo_vision_poseest_pickplace.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def pick(self, pose, direction=(0, 0, 1), distance=0.1, controller=None):
"""Go to pose + pick_direction * pick_distance, open, go to pose,
close, go to pose + pick_direction * pick_distance.
"""
rospy.logdebug("pick pose: %s" % pose)
pregrasp_pose = self.translate(pose, direction, distance)
rospy.logdebug("pregrasp_pose: %s" % pregrasp_pose)
rospy.sleep(1)
self.move_ik(pregrasp_pose)
# We want to block end effector opening so that the next
# movement happens with the gripper fully opened.
self.gripper.open(block=True)
self.move_ik(pose)
if controller is not None:
print ('controller ON!!')
controller.enable()
rospy.sleep(5)
controller.disable()
self.gripper.close(block=True)
self.move_ik(pregrasp_pose)
demo_vision_poseest_pickplace.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def main(limb_name, reset):
"""
Parameters
----------
limb : str
Which limb to use. Choices are {'left', 'right'}
reset : bool
Whether to use previously saved picking and placing poses or
to save new ones by using 0g mode and the OK cuff buttons.
"""
# Initialise ros node
rospy.init_node("pick_and_place", anonymous=False)
b = Baxter(limb_name)
place_pose = limb_pose(limb_name).tolist()
print (place_pose)
block = Blocks()
rospy.sleep(4)
pick_pose = block.pose
rospy.loginfo('Block pose: %s' % pick_pose)
#import ipdb; ipdb.set_trace()
b.pick(pick_pose, controller=None)
b.place(place_pose)
demo_graspsuccessExp.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def limb_pose(limb_name):
"""Get limb pose at time of OK cuff button press."""
button = CuffOKButton(limb_name)
rate = rospy.Rate(20) # rate at which we check whether button was
# pressed or not
rospy.loginfo(
'Waiting for %s OK cuff button press to save pose' % limb_name)
while not button.pressed and not rospy.is_shutdown():
rate.sleep()
joint_pose = baxter_interface.Limb(limb_name).joint_angles()
# Now convert joint coordinates to end effector cartesian
# coordinates using forward kinematics.
kinematics = baxter_kinematics(limb_name)
endpoint_pose = kinematics.forward_position_kinematics(joint_pose)
#print (endpoint_pose)
return endpoint_pose
2017_Task5.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def goto(self, from_frame, to_frame):
'''
Calculates the transfrom from from_frame to to_frame
and commands the arm in cartesian mode.
'''
try:
trans = self.tfBuffer.lookup_transform(from_frame, to_frame, rospy.Time())
except (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):
rate.sleep()
# continue
translation = [trans.transform.translation.x, trans.transform.translation.y, trans.transform.translation.z]
rotation = [trans.transform.rotation.x, trans.transform.rotation.y, trans.transform.rotation.z, trans.transform.rotation.w]
pose_value = translation + rotation
#second arg=0 (absolute movement), arg = '-r' (relative movement)
self.cmmnd_CartesianPosition(pose_value, 0)
2017_Task5.py 文件源码
项目:cu-perception-manipulation-stack
作者: correlllab
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def cmmnd_makeContact_USBPlug(self, sensitivity):
rate = rospy.Rate(100)
while (self.bump_finger_1 < sensitivity)and not rospy.is_shutdown():
print (self.bump_finger_1)
self.cmmnd_CartesianVelocity([-0.03,0,0,0,0,0,1])
rate.sleep()
print ("contact made with the ground")
# def pick_USBlight_1(self, current_finger_position):
# ii = 0
# rate = rospy.Rate(100)
# while self.touch_finger_3 != True and not rospy.is_shutdown():
# current_finger_position[0] += 5 # slowly close finger_1 until contact is made
# print (current_finger_position[0])
# self.cmmnd_FingerPosition([current_finger_position[0], current_finger_position[1], current_finger_position[2]])
# rate.sleep()
# self.touch_finger_1 = False
# return current_finger_position
def pick(self, pose, direction=(0, 0, 1), distance=0.1):
"""Go to pose + pick_direction * pick_distance, open, go to pose,
close, go to pose + pick_direction * pick_distance.
"""
pregrasp_pose = self.translate(pose, direction, distance)
self.move_ik(pregrasp_pose)
rospy.sleep(0.5)
# We want to block end effector opening so that the next
# movement happens with the gripper fully opened. In Baxter,
# that involves sublcassing the gripper class
self.gripper.open()
self.move_ik(pose)
rospy.sleep(0.5)
self.gripper.close()
rospy.sleep(0.5)
self.move_ik(pregrasp_pose)
def run_trial_tf(self, policy, time_to_run=5):
""" Run an async controller from a policy. The async controller receives observations from ROS subscribers
and then uses them to publish actions."""
should_stop = False
consecutive_failures = 0
start_time = time.time()
while should_stop is False:
if self.observations_stale is False:
consecutive_failures = 0
last_obs = tf_obs_msg_to_numpy(self._tf_subscriber_msg)
action_msg = tf_policy_to_action_msg(self.dU,
self._get_new_action(policy, last_obs),
self.current_action_id)
self._tf_publish(action_msg)
self.observations_stale = True
self.current_action_id += 1
else:
rospy.sleep(0.01)
consecutive_failures += 1
if time.time() - start_time > time_to_run and consecutive_failures > 5:
# we only stop when we have run for the trial time and are no longer receiving obs.
should_stop = True
rospy.sleep(0.25) # wait for finished trial to come in.
result = self._trial_service._subscriber_msg
return result # the trial has completed. Here is its message.
def __init__(self):
self.node_name = "face_recog_fisher"
rospy.init_node(self.node_name)
rospy.on_shutdown(self.cleanup)
self.bridge = CvBridge()
self.face_names = StringArray()
self.all_names = StringArray()
self.size = 4
face_haar = 'haarcascade_frontalface_default.xml'
self.haar_cascade = cv2.CascadeClassifier(face_haar)
self.face_dir = 'face_data_fisher'
self.model = cv2.createFisherFaceRecognizer()
# self.model = cv2.createEigenFaceRecognizer()
(self.im_width, self.im_height) = (112, 92)
rospy.loginfo("Loading data...")
# self.fisher_train_data()
self.load_trained_data()
rospy.sleep(3)
# self.img_sub = rospy.Subscriber("/asus/rgb/image_raw", Image, self.img_callback)
self.img_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.img_callback)
# self.img_pub = rospy.Publisher('face_img', Image, queue_size=10)
self.name_pub = rospy.Publisher('face_names', StringArray, queue_size=10)
self.all_names_pub = rospy.Publisher('all_face_names', StringArray, queue_size=10)
rospy.loginfo("Detecting faces...")
def find_station(self, station_id):
station_loc = []
if station_id < 2:
return [0.0, 0.0]
station_loc = self.qr_tag_loc(station_id)
count=0
while not station_loc:
if count == 12:
break
self.rotate_tbot(90.0)
rospy.sleep(4)
station_loc = self.qr_tag_loc(station_id)
# print station_loc
# rospy.sleep(3)
count += 1
return station_loc
def find_person(self, name):
# cv2.imshow("Face Image", self.face_img)
# cv2.waitKey(3)
count=0
found = False
while count < 6 and found != True:
for i in range(len(self.face_names)):
if self.face_names[i] == name:
print self.face_names[i]
return True
break
count += 1
self.rotate_tbot(180.0, 45.0/2)
rospy.sleep(5)
# print count
return found
def go_to_start(self, duration=5):
d = {"abs_z": 0,
"bust_y": 0,
"bust_x": 0,
"head_z": 0,
"head_y": 20,
"l_shoulder_y": 0,
"l_shoulder_x": 0,
"l_arm_z": 20,
"l_elbow_y": 0,
"r_shoulder_y": 0,
"r_shoulder_x": 0,
"r_arm_z": 0,
"r_elbow_y": 0}
self.torso.set_compliant(False)
self.torso.reach(d, duration)
rospy.sleep(duration)
def execute_iteration(self, task, method, iteration, trial, num_iterations):
rospy.logwarn("Controller starts iteration {} {}/{} trial {}".format(method, iteration, num_iterations, trial))
rospy.wait_for_service('ergo/reset') # Ensures Ergo keeps working or wait till it reboots
# After resuming, we keep the same iteration
if self.perception.has_been_pressed('buttons/help'):
rospy.sleep(1.5) # Wait for the robot to fully stop
self.recorder.record(task, method, trial, iteration)
self.perception.switch_led('button_leds/pause', True)
recording = self.perception.record(human_demo=True, nb_points=self.params['nb_points'])
self.torso.set_torque_max(self.torso_params['torques']['reset'])
self.torso.reset(slow=True)
return True
else:
trajectory = self.learning.produce(skill_to_demonstrate=self.demonstrate).torso_trajectory
self.torso.set_torque_max(self.torso_params['torques']['motion'])
self.recorder.record(task, method, trial, iteration)
self.perception.switch_led('button_leds/pause', True)
self.torso.execute_trajectory(trajectory) # TODO: blocking, non-blocking, action server?
recording = self.perception.record(human_demo=False, nb_points=self.params['nb_points'])
self.perception.switch_led('button_leds/pause', False)
recording.demo.torso_demonstration = JointTrajectory()
self.torso.set_torque_max(80)
self.torso.reset(slow=False)
return self.learning.perceive(recording.demo)
def run(self):
self.go_to_start()
self.last_activity = rospy.Time.now()
self.srv_reset = rospy.Service('ergo/reset', Reset, self._cb_reset)
rospy.loginfo('Ergo is ready and starts joystick servoing...')
self.t = rospy.Time.now()
while not rospy.is_shutdown():
now = rospy.Time.now()
self.delta_t = (now - self.t).to_sec()
self.t = now
self.go_or_resume_standby()
self.servo_robot(self.joy_y, self.joy_x)
self.publish_state()
self.publish_button()
# Update the last activity
if abs(self.joy_x) > self.params['min_joy_activity'] or abs(self.joy_y) > self.params['min_joy_activity']:
self.last_activity = rospy.Time.now()
self.rate.sleep()
def _read(self, max_attempts=600):
got_image = False
if self._camera is not None and self._camera.isOpened():
got_image, image = self._camera.read()
if not got_image:
if not self._error:
if max_attempts > 0:
rospy.sleep(0.1)
self._open()
return self._read(max_attempts-1)
rospy.logerr("Reached maximum camera reconnection attempts, abandoning!")
self._error = True
return False, None
return False, None
return True, image