我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用rospy.ROSException()。
def ik_solve(limb, pos, orient): ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService" iksvc = rospy.ServiceProxy(ns, SolvePositionIK) ikreq = SolvePositionIKRequest() hdr = Header(stamp=rospy.Time.now(), frame_id='base') poses = { str(limb): PoseStamped(header=hdr, pose=Pose(position=pos, orientation=orient))} ikreq.pose_stamp.append(poses[limb]) try: rospy.wait_for_service(ns, 5.0) resp = iksvc(ikreq) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return 1 if resp.isValid[0]: limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position)) return limb_joints else: return Errors.RaiseNotReachable(pos)
def publish(topic, instructions=None): if type(topic) not in [str, nb_channels.Messages]: rospy.logerr("** Topic must be of type string or Messages in order to publish to cable **") return False if instructions and type(instructions) is not dict: rospy.logerr("** Instructions must be of type dictionary in order to publish to cable **") return False # Properly format topic string topic_val = topic if type(topic) is str else topic.value try: rospy.wait_for_service('ui_send', 0.1) client = UIClient() return client.send( topic_val, json.dumps(instructions) ) except rospy.ROSException: return UIMessageResponse(success=False)
def init_traj(self): try: # self.recorder.init_traj(itr) if self.use_goalimage: goal_img_main, goal_state = self.load_goalimage() goal_img_aux1 = np.zeros([64, 64, 3]) else: goal_img_main = np.zeros([64, 64, 3]) goal_img_aux1 = np.zeros([64, 64, 3]) goal_img_main = self.bridge.cv2_to_imgmsg(goal_img_main) goal_img_aux1 = self.bridge.cv2_to_imgmsg(goal_img_aux1) rospy.wait_for_service('init_traj_visualmpc', timeout=1) self.init_traj_visual_func(0, 0, goal_img_main, goal_img_aux1, self.save_subdir) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) raise ValueError('get_kinectdata service failed')
def save(self, i_save, action, endeffector_pose): self.t_savereq = rospy.get_time() assert self.instance_type == 'main' if self.use_aux: # request save at auxiliary recorders try: rospy.wait_for_service('get_kinectdata', 0.1) resp1 = self.save_kinectdata_func(i_save) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) raise ValueError('get_kinectdata service failed') if self.save_images: self._save_img_local(i_save) if self.save_actions: self._save_state_actions(i_save, action, endeffector_pose) if self.save_gif: highres = cv2.cvtColor(self.ltob.img_cv2, cv2.COLOR_BGR2RGB) print 'highres dim',highres.shape self.highres_imglist.append(highres)
def ik_quaternion(self, quaternion_pose): node = ("ExternalTools/{}/PositionKinematicsNode/" "IKService".format(self.limb_name)) ik_service = rospy.ServiceProxy(node, SolvePositionIK) ik_request = SolvePositionIKRequest() ik_request.pose_stamp.append(quaternion_pose) try: rospy.loginfo('ik: waiting for IK service...') rospy.wait_for_service(node, 5.0) ik_response = ik_service(ik_request) except (rospy.ServiceException, rospy.ROSException) as err: rospy.logerr("ik_move: service request failed: %r" % err) else: if ik_response.isValid[0]: rospy.loginfo("ik_move: valid joint configuration found") limb_joints = dict(zip(ik_response.joints[0].name, ik_response.joints[0].position)) return limb_joints else: rospy.logerr('ik_move: no valid configuration found') return None
def fk_service_client(limb = "right"): ns = "ExternalTools/" + limb + "/PositionKinematicsNode/FKService" fksvc = rospy.ServiceProxy(ns, SolvePositionFK) fkreq = SolvePositionFKRequest() joints = JointState() joints.name = ['right_j0', 'right_j1', 'right_j2', 'right_j3', 'right_j4', 'right_j5', 'right_j6'] joints.position = [0.763331, 0.415979, -1.728629, 1.482985, -1.135621, -1.674347, -0.496337] # Add desired pose for forward kinematics fkreq.configuration.append(joints) # Request forward kinematics from base to "right_hand" link fkreq.tip_names.append('right_hand') try: rospy.wait_for_service(ns, 5.0) resp = fksvc(fkreq) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return False # Check if result valid if (resp.isValid[0]): rospy.loginfo("SUCCESS - Valid Cartesian Solution Found") rospy.loginfo("\nFK Cartesian Solution:\n") rospy.loginfo("------------------") rospy.loginfo("Response Message:\n%s", resp) else: rospy.logerr("INVALID JOINTS - No Cartesian Solution Found.") return False return True
def perform_service_call(service_name): """ POST /api/<version>/service/<service_name> POST to a service to change it somehow. service_name may be a path. For example, to start an environmental recipe in an environment, use the start_recipe service: POST /api/<version>/service/<environment_id>/start_recipe {"recipe_id": <id>} """ # Add leading slash to service_name. ROS qualifies all services with a # leading slash. service_name = '/' + service_name # Find the class that ROS autogenerates from srv files that is associated # with this service. try: ServiceClass = rosservice.get_service_class_by_name(service_name) except rosservice.ROSServiceException as e: return error(e) # If we made it this far, the service exists. # Wait for service to be ready before attempting to use it. try: rospy.wait_for_service(service_name, 1) except rospy.ROSException as e: raise socket.error() # Get JSON args if they exist. If they don't, treat as if empty array # was passed. json = request.get_json(silent=True) args = json if json else [] service_proxy = rospy.ServiceProxy(service_name, ServiceClass) try: # Unpack the list of args and pass to service_proxy function. res = service_proxy(*args) except (rospy.ServiceException, TypeError) as e: return error(e) status_code = 200 if getattr(res, "success", True) else 400 data = {k: getattr(res, k) for k in res.__slots__} return jsonify(data), status_code
def get_endeffector_pos(self, pos_only=True): """ :param pos_only: only return postion :return: """ fkreq = SolvePositionFKRequest() joints = JointState() joints.name = self.ctrl.limb.joint_names() joints.position = [self.ctrl.limb.joint_angle(j) for j in joints.name] # Add desired pose for forward kinematics fkreq.configuration.append(joints) fkreq.tip_names.append('right_hand') try: rospy.wait_for_service(self.name_of_service, 5) resp = self.fksvc(fkreq) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return False pos = np.array([resp.pose_stamp[0].pose.position.x, resp.pose_stamp[0].pose.position.y, resp.pose_stamp[0].pose.position.z]) return pos
def query_action(self): if self.use_robot: if self.use_aux: self.recorder.get_aux_img() imageaux1 = self.recorder.ltob_aux1.img_msg else: imageaux1 = np.zeros((64, 64, 3), dtype=np.uint8) imageaux1 = self.bridge.cv2_to_imgmsg(imageaux1) imagemain = self.bridge.cv2_to_imgmsg(self.recorder.ltob.img_cropped) state = self.get_endeffector_pos() else: imagemain = np.zeros((64,64,3)) imagemain = self.bridge.cv2_to_imgmsg(imagemain) imageaux1 = self.bridge.cv2_to_imgmsg(self.test_img) state = np.zeros(3) try: rospy.wait_for_service('get_action', timeout=240) get_action_resp = self.get_action_func(imagemain, imageaux1, tuple(state), tuple(self.desig_pos_main.flatten()), tuple(self.goal_pos_main.flatten())) action_vec = get_action_resp.action except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) raise ValueError('get action service call failed') return action_vec
def fk_service_client(limb = "right"): ns = "ExternalTools/" + limb + "/PositionKinematicsNode/FKService" fksvc = rospy.ServiceProxy(ns, SolvePositionFK) fkreq = SolvePositionFKRequest() joints = JointState() joints.name = ['right_j0', 'right_j1', 'right_j2', 'right_j3', 'right_j4', 'right_j5', 'right_j6'] joints.position = [0.763331, 0.415979, -1.728629, 1.482985, -1.135621, -1.674347, -0.496337] # Add desired pose for forward kinematics fkreq.configuration.append(joints) # Request forward kinematics from base to "right_hand" link fkreq.tip_names.append('right_hand') try: rospy.wait_for_service(ns, 5.0) resp = fksvc(fkreq) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return False # Check if result valid if (resp.isValid[0]): rospy.loginfo("SUCCESS - Valid Cartesian Solution Found") rospy.loginfo("\nFK Cartesian Solution:\n") rospy.loginfo("------------------") rospy.loginfo("Response Message:\n%s", resp) else: rospy.loginfo("INVALID JOINTS - No Cartesian Solution Found.") return True
def init_traj(self, itr): assert self.instance_type == 'main' # request init service for auxiliary recorders if self.use_aux: try: rospy.wait_for_service('init_traj', timeout=1) resp1 = self.init_traj_func(itr, self.igrp) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) raise ValueError('get_kinectdata service failed') self._init_traj_local(itr) if ((itr+1) % self.ngroup) == 0: self.igrp += 1
def get_aux_img(self): try: rospy.wait_for_service('get_kinectdata', 0.1) resp1 = self.get_kinectdata_func() self.ltob_aux1.img_msg = resp1.image except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) raise ValueError('get_kinectdata service failed')
def execute(self, userdata): global waypoints self.initialize_path_queue() self.path_ready = False # Start thread to listen for when the path is ready (this function will end then) def wait_for_path_ready(): """thread worker function""" data = rospy.wait_for_message('/path_ready', Empty) rospy.loginfo('Recieved path READY message') self.path_ready = True ready_thread = threading.Thread(target=wait_for_path_ready) ready_thread.start() topic = "/initialpose" rospy.loginfo("Waiting to recieve waypoints via Pose msg on topic %s" % topic) rospy.loginfo("To start following waypoints: 'rostopic pub /path_ready std_msgs/Empty -1'") # Wait for published waypoints while not self.path_ready: try: pose = rospy.wait_for_message(topic, PoseWithCovarianceStamped, timeout=1) except rospy.ROSException as e: if 'timeout exceeded' in e.message: continue # no new waypoint within timeout, looping... else: raise e rospy.loginfo("Recieved new waypoint") waypoints.append(pose) # publish waypoint queue as pose array so that you can see them in rviz, etc. self.poseArray_publisher.publish(convert_PoseWithCovArray_to_PoseArray(waypoints)) # Path is ready! return success and move on to the next state (FOLLOW_PATH) return 'success'
def ik_quaternion(self, quaternion_pose): """Take a xyz qxqyqzqw stamped pose and convert it to joint angles using IK. You can call self.limb.move_to_joint_positions to move to those angles """ node = ("ExternalTools/{}/PositionKinematicsNode/" "IKService".format(self.limb_name)) ik_service = rospy.ServiceProxy(node, SolvePositionIK) ik_request = SolvePositionIKRequest() ik_request.pose_stamp.append(quaternion_pose) try: rospy.loginfo('ik: waiting for IK service...') rospy.wait_for_service(node, 5.0) ik_response = ik_service(ik_request) except (rospy.ServiceException, rospy.ROSException) as err: rospy.logerr("ik_move: service request failed: %r" % err) else: if ik_response.isValid[0]: rospy.loginfo("ik_move: valid joint configuration found") # convert response to joint position control dictionary limb_joints = dict(zip(ik_response.joints[0].name, ik_response.joints[0].position)) return limb_joints else: rospy.logerr('ik_move: no valid configuration found') return None
def baxter_ik_move(self, rpy_pose): # quaternion_pose = conversions.list_to_pose_stamped(rpy_pose, "base") quaternion_pose = convert_pose_to_msg(rpy_pose, "base") node = "ExternalTools/" + self.limb + "/PositionKinematicsNode/IKService" ik_service = rospy.ServiceProxy(node, SolvePositionIK) ik_request = SolvePositionIKRequest() hdr = Header(stamp=rospy.Time.now(), frame_id="base") ik_request.pose_stamp.append(quaternion_pose) try: rospy.wait_for_service(node, 5.0) ik_response = ik_service(ik_request) except (rospy.ServiceException, rospy.ROSException), error_message: rospy.logerr("Service request failed: %r" % (error_message,)) print "ERROR - baxter_ik_move - Failed to append pose" return 1 if (ik_response.isValid[0]): # convert response to joint position control dictionary limb_joints = dict(zip(ik_response.joints[0].name, ik_response.joints[0].position)) # move limb self.limb_interface.move_to_joint_positions(limb_joints) else: print "ERROR - baxter_ik_move - No valid joint configuration found" return 2 self.getPose() #Store current pose into self.pose print "Move Executed" return -1 #Because we can't get full moveit_commander on the raspberry pi due to memory limitations, rewritten implementation of the required conversion function
def get_ik_joints(target_x, target_y, initial_z, target_z, target_theta, n_steps): ns = "ExternalTools/left/PositionKinematicsNode/IKService" iksvc = rospy.ServiceProxy(ns, SolvePositionIK) ikreq = SolvePositionIKRequest(seed_mode=SolvePositionIKRequest.SEED_CURRENT) hdr = Header(stamp=rospy.Time.now(), frame_id='base') qx = np.sin(target_theta * 0.5) qy = np.cos(target_theta * 0.5) for z in np.arange(initial_z, target_z, (target_z-initial_z)/n_steps): pose = PoseStamped( header=hdr, pose=Pose( position=Point( x=target_x, y=target_y, z=z, ), orientation=Quaternion( x=qx, y=qy, z=0., w=0., ), ), ) ikreq.pose_stamp.append(pose) try: rospy.wait_for_service(ns, 5.0) resp = iksvc(ikreq) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return 1 return [j for v, j in zip(resp.isValid, resp.joints) if v]
def go_to_pose(lmb, pose_msg, timeout=15.0): """ Given a limb (right or left) and a desired pose as a stamped message, run inverse kinematics to attempt to find a joint configuration to yield the pose and then move limb to the configuration. After 5 seconds of attempts to solve the IK, raise an exception. """ node = "ExternalTools/" + lmb + "/PositionKinematicsNode/IKService" ik_service = rospy.ServiceProxy(node, SolvePositionIK) ik_request = SolvePositionIKRequest() ik_request.pose_stamp.append(pose_msg) # Allow 5 seconds to find an IK solution try: rospy.wait_for_service(node, 5.0) ik_response = ik_service(ik_request) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return 1 # Check if result valid if ik_response.isValid[0]: # convert response to joint position control dictionary limb_joints = dict(zip(ik_response.joints[0].name, ik_response.joints[0].position)) # send limb to joint positions baxter_interface.limb.Limb(lmb).move_to_joint_positions( limb_joints, timeout=timeout) else: raise Exception("Failed to find valid joint configuration.")
def __init__(self, boards, service_check = True, synchronizer = message_filters.TimeSynchronizer, flags = 0, pattern=Patterns.Chessboard, camera_name='', checkerboard_flags = 0): if service_check: # assume any non-default service names have been set. Wait for the service to become ready for svcname in ["camera", "left_camera", "right_camera"]: remapped = rospy.remap_name(svcname) if remapped != svcname: fullservicename = "%s/set_camera_info" % remapped print("Waiting for service", fullservicename, "...") try: rospy.wait_for_service(fullservicename, 5) print("OK") except rospy.ROSException: print("Service not found") rospy.signal_shutdown('Quit') self._boards = boards self._calib_flags = flags self._checkerboard_flags = checkerboard_flags self._pattern = pattern self._camera_name = camera_name lsub = message_filters.Subscriber('left', sensor_msgs.msg.Image) rsub = message_filters.Subscriber('right', sensor_msgs.msg.Image) ts = synchronizer([lsub, rsub], 4) ts.registerCallback(self.queue_stereo) msub = message_filters.Subscriber('image', sensor_msgs.msg.Image) msub.registerCallback(self.queue_monocular) self.set_camera_info_service = rospy.ServiceProxy("%s/set_camera_info" % rospy.remap_name("camera"), sensor_msgs.srv.SetCameraInfo) self.set_left_camera_info_service = rospy.ServiceProxy("%s/set_camera_info" % rospy.remap_name("left_camera"), sensor_msgs.srv.SetCameraInfo) self.set_right_camera_info_service = rospy.ServiceProxy("%s/set_camera_info" % rospy.remap_name("right_camera"), sensor_msgs.srv.SetCameraInfo) self.q_mono = deque([], 1) self.q_stereo = deque([], 1) self.c = None mth = ConsumerThread(self.q_mono, self.handle_monocular) mth.setDaemon(True) mth.start() sth = ConsumerThread(self.q_stereo, self.handle_stereo) sth.setDaemon(True) sth.start()
def get_ik_joints_linear(initial_x, initial_y, initial_z, initial_w2, target_x, target_y, target_z, target_w2, n_steps): ns = "ExternalTools/left/PositionKinematicsNode/IKService" iksvc = rospy.ServiceProxy(ns, SolvePositionIK) ikreq = SolvePositionIKRequest(seed_mode=SolvePositionIKRequest.SEED_CURRENT) hdr = Header(stamp=rospy.Time.now(), frame_id='base') # current_pose = arm.endpoint_pose() x0 = initial_x y0 = initial_y z0 = initial_z # linear interpolate between current pose and target pose for i in xrange(n_steps): t = (i + 1) * 1. / n_steps x = (1. - t) * x0 + t * target_x y = (1. - t) * y0 + t * target_y z = (1. - t) * z0 + t * target_z pose = PoseStamped( header=hdr, pose=Pose( position=Point( x=x, y=y, z=z, ), # endeffector pointing down orientation=Quaternion( x=1., y=0., z=0., w=0., ), ), ) ikreq.pose_stamp.append(pose) try: rospy.wait_for_service(ns, 5.0) resp = iksvc(ikreq) except (rospy.ServiceException, rospy.ROSException), e: rospy.logerr("Service call failed: %s" % (e,)) return [] js = [] # control w2 separately from other joints for i, (v, j) in enumerate(zip(resp.isValid, resp.joints)): t = (i + 1) * 1. / n_steps if v: w2 = (1. - t) * initial_w2 + t * target_w2 j.position = j.position[:-1] + (w2,) js.append(j) return js