Python源码示例:rospy.ServiceProxy()
示例1
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
示例2
def _GetDetection(self, obj_name):
"""
Calls the service to get a detection of a particular object.
@param obj_name The name of the object to detect
@return A 4x4 transformation matrix describing the pose of the object
in world frame, None if the object is not detected
"""
#Call detection service for a particular object
detect_vncc = rospy.ServiceProxy(self.service_namespace+'/get_vncc_detections',
vncc_msgs.srv.GetDetections)
detect_resp = detect_vncc(object_name=obj_name)
if detect_resp.ok == False:
return None
#Assumes one instance of object
result = self._MsgToPose(detect_resp.detections[0])
if (self.detection_frame is not None and self.world_frame is not None):
result = self._LocalToWorld(result)
result[:3,:3] = numpy.eye(3)
return result
示例3
def get_object_relative_pose(self, obj_type="SQUARE", obj_color="BLUE", ret_image=True):
service_name = self.__services_name['object_pose_service']
rospy.wait_for_service(service_name)
try:
detection_service = rospy.ServiceProxy(service_name, ObjDetection)
response = detection_service(obj_type=obj_type, obj_color=obj_color,
workspace_ratio=25. / 16, ret_image=ret_image)
ret_status = self.__status_interpreter_obj_detection[response.status]
if ret_status != "SUCCESSFUL":
print "Object not detected: " + ret_status
msg_res = response.obj_pose
obj_type = response.obj_type
obj_color = response.obj_color
if ret_image:
im_ret = extract_img_from_ros_msg(response.img)
else:
im_ret = None
return ret_status, msg_res, obj_type, obj_color, im_ret
except rospy.ServiceException, e:
print "Service call failed: %s" % e
示例4
def __init__(self):
rospy.wait_for_service('niryo_one/tools/ping_and_set_dxl_tool')
rospy.wait_for_service('niryo_one/tools/open_gripper')
rospy.wait_for_service('niryo_one/tools/close_gripper')
rospy.wait_for_service('niryo_one/tools/pull_air_vacuum_pump')
rospy.wait_for_service('niryo_one/tools/push_air_vacuum_pump')
self.service_ping_dxl_tool = rospy.ServiceProxy('niryo_one/tools/ping_and_set_dxl_tool', PingDxlTool)
self.service_open_gripper = rospy.ServiceProxy('niryo_one/tools/open_gripper', OpenGripper)
self.service_close_gripper = rospy.ServiceProxy('niryo_one/tools/close_gripper', CloseGripper)
self.service_pull_air_vacuum_pump = rospy.ServiceProxy('niryo_one/tools/pull_air_vacuum_pump',
PullAirVacuumPump)
self.service_push_air_vacuum_pump = rospy.ServiceProxy('niryo_one/tools/push_air_vacuum_pump',
PushAirVacuumPump)
self.service_setup_digital_output_tool = rospy.ServiceProxy('niryo_one/rpi/set_digital_io_mode', SetDigitalIO)
self.service_activate_digital_output_tool = rospy.ServiceProxy('niryo_one/rpi/set_digital_io_state',
SetDigitalIO)
rospy.loginfo("Interface between Tools Controller and Ros Control has been started.")
示例5
def spawn_model(model_name):
""" Spawns a model in front of the RGBD camera.
Args: None
Returns: None
"""
initial_pose = Pose()
initial_pose.position.x = 0
initial_pose.position.y = 1
initial_pose.position.z = 1
# Spawn the new model #
model_path = rospkg.RosPack().get_path('sensor_stick')+'/models/'
model_xml = ''
with open (model_path + model_name + '/model.sdf', 'r') as xml_file:
model_xml = xml_file.read().replace('\n', '')
spawn_model_prox = rospy.ServiceProxy('gazebo/spawn_sdf_model', SpawnModel)
spawn_model_prox('training_model', model_xml, '', initial_pose, 'world')
示例6
def execute(self, inputs, outputs, gvm):
turtle_name = inputs["turtle_name"]
x = inputs["x_pos"]
y = inputs["y_pos"]
phi = inputs["phi"]
service = "/spawn"
rospy.wait_for_service(service)
spawn_turtle_service = rospy.ServiceProxy(service, Spawn)
resp1 = spawn_turtle_service(x, y, phi, turtle_name)
self.logger.info("ROS external module: executed the {} service".format(service))
turtle_pos_subscriber = rospy.Subscriber("/" + turtle_name + "/pose", Pose, check_turtle_pose)
r = rospy.Rate(10)
global pose_received
# wait until the first pose message was received
while not pose_received:
r.sleep()
return 0
示例7
def __init__(self):
rospy.init_node("mav_control_node")
rospy.Subscriber("/mavros/local_position/pose", PoseStamped, self.pose_callback)
rospy.Subscriber("/mavros/rc/in", RCIn, self.rc_callback)
self.cmd_pos_pub = rospy.Publisher("/mavros/setpoint_position/local", PoseStamped, queue_size=1)
self.cmd_vel_pub = rospy.Publisher("/mavros/setpoint_velocity/cmd_vel_unstamped", Twist, queue_size=1)
self.rc_override = rospy.Publisher("/mavros/rc/override", OverrideRCIn, queue_size=1)
# mode 0 = STABILIZE
# mode 4 = GUIDED
# mode 9 = LAND
self.mode_service = rospy.ServiceProxy('/mavros/set_mode', SetMode)
self.arm_service = rospy.ServiceProxy('/mavros/cmd/arming', CommandBool)
self.takeoff_service = rospy.ServiceProxy('/mavros/cmd/takeoff', CommandTOL)
self.rc = RCIn()
self.pose = Pose()
self.timestamp = rospy.Time()
示例8
def __init__(self):
rospy.init_node("mav_control_node")
rospy.Subscriber("/mavros/local_position/pose", PoseStamped, self.pose_callback)
rospy.Subscriber("/mavros/rc/in", RCIn, self.rc_callback)
self.cmd_pos_pub = rospy.Publisher("/mavros/setpoint_position/local", PoseStamped, queue_size=1)
self.cmd_vel_pub = rospy.Publisher("/mavros/setpoint_velocity/cmd_vel_unstamped", Twist, queue_size=1)
self.rc_override = rospy.Publisher("/mavros/rc/override", OverrideRCIn, queue_size=1)
# mode 0 = STABILIZE
# mode 4 = GUIDED
# mode 9 = LAND
self.mode_service = rospy.ServiceProxy('/mavros/set_mode', SetMode)
self.arm_service = rospy.ServiceProxy('/mavros/cmd/arming', CommandBool)
self.takeoff_service = rospy.ServiceProxy('/mavros/cmd/takeoff', CommandTOL)
self.rc = RCIn()
self.pose = Pose()
self.timestamp = rospy.Time()
示例9
def call_service(self, req):
"""Calling the appropriate service depending on the given request type.
Requests have to inherit from 'HMMRepRequestAbstractclass'.
:param req: The request class instance for the request you want to make
:return: The qsr_type and resulting data tuple. The data is in the data type produced by the response.
"""
assert(issubclass(req.__class__, RepRequestAbstractclass))
s = rospy.ServiceProxy(self.services[req.__class__],QSRProbRep)
try:
s.wait_for_service(timeout=10.)
res = s(QSRProbRepRequest(data=json.dumps(req.kwargs)))
except (rospy.ROSException, rospy.ROSInterruptException, rospy.ServiceException) as e:
rospy.logerr(e)
return None
try:
data = json.loads(res.data)
except ValueError:
data = str(res.data)
return data
示例10
def __init__(self, configs):
self.configs = configs
self.ROT_VEL = self.configs.BASE.MAX_ABS_TURN_SPEED
self.LIN_VEL = self.configs.BASE.MAX_ABS_FWD_SPEED
self.MAP_FRAME = self.configs.BASE.MAP_FRAME
self.BASE_FRAME = self.configs.BASE.VSLAM.VSLAM_BASE_FRAME
self.point_idx = self.configs.BASE.TRACKED_POINT
rospy.wait_for_service(self.configs.BASE.PLAN_TOPIC, timeout=3)
try:
self.plan_srv = rospy.ServiceProxy(self.configs.BASE.PLAN_TOPIC, GetPlan)
except rospy.ServiceException:
rospy.logerr(
"Timed out waiting for the planning service. \
Make sure build_map in script and \
use_map in roslauch are set to the same value"
)
self.start_state = build_pose_msg(0, 0, 0, self.BASE_FRAME)
self.tolerance = self.configs.BASE.PLAN_TOL
self._transform_listener = tf.TransformListener()
示例11
def RequestDMP(u,dt,k_gain,d_gain,num_basis_functions):
ndims = len(u[0])
k_gains = [k_gain]*ndims
d_gains = [d_gain]*ndims
ex = DMPTraj()
for i in range(len(u)):
pt = DMPPoint()
pt.positions = u[i] # always sends positions regardless of actual content
ex.points.append(pt)
ex.times.append(dt * i) # make sure times are reasonable
rospy.wait_for_service('learn_dmp_from_demo')
try:
lfd = rospy.ServiceProxy('learn_dmp_from_demo', LearnDMPFromDemo)
resp = lfd(ex, k_gains, d_gains, num_basis_functions)
except rospy.ServiceException, e:
print "Service call failed: %s"%e
示例12
def __call__(self, **kwargs):
rospy.loginfo('will call service {}'.format(self.service_name))
from tts.srv import Polly
rospy.wait_for_service(self.service_name)
polly = rospy.ServiceProxy(self.service_name, Polly)
return polly(polly_action='SynthesizeSpeech', **kwargs)
示例13
def test_plain_text_to_wav_via_polly_node(self):
rospy.wait_for_service('polly')
polly = rospy.ServiceProxy('polly', Polly)
test_text = 'Mary has a little lamb, little lamb, little lamb.'
res = polly(polly_action='SynthesizeSpeech', text=test_text)
self.assertIsNotNone(res)
self.assertTrue(type(res) is PollyResponse)
r = json.loads(res.result)
self.assertIn('Audio Type', r, 'result should contain audio type')
self.assertIn('Audio File', r, 'result should contain file path')
self.assertIn('Amazon Polly Response Metadata', r, 'result should contain metadata')
audio_type = r['Audio Type']
audio_file = r['Audio File']
md = r['Amazon Polly Response Metadata']
self.assertTrue("'HTTPStatusCode': 200," in md)
self.assertEqual('audio/ogg', audio_type)
self.assertTrue(audio_file.endswith('.ogg'))
import subprocess
o = subprocess.check_output(['file', audio_file], stderr=subprocess.STDOUT)
import re
m = re.search(r'.*Ogg data, Vorbis audi.*', o, flags=re.MULTILINE)
self.assertIsNotNone(m)
示例14
def test_plain_text_via_synthesizer_node(self):
rospy.wait_for_service('synthesizer')
speech_synthesizer = rospy.ServiceProxy('synthesizer', Synthesizer)
text = 'Mary has a little lamb, little lamb, little lamb.'
res = speech_synthesizer(text=text)
self.assertIsNotNone(res)
self.assertTrue(type(res) is SynthesizerResponse)
r = json.loads(res.result)
self.assertIn('Audio Type', r, 'result should contain audio type')
self.assertIn('Audio File', r, 'result should contain file path')
self.assertIn('Amazon Polly Response Metadata', r, 'result should contain metadata')
audio_type = r['Audio Type']
audio_file = r['Audio File']
md = r['Amazon Polly Response Metadata']
self.assertTrue("'HTTPStatusCode': 200," in md)
self.assertEqual('audio/ogg', audio_type)
self.assertTrue(audio_file.endswith('.ogg'))
import subprocess
o = subprocess.check_output(['file', audio_file], stderr=subprocess.STDOUT)
import re
m = re.search(r'.*Ogg data, Vorbis audi.*', o, flags=re.MULTILINE)
self.assertIsNotNone(m)
示例15
def test_plain_text_to_mp3_via_polly_node(self):
rospy.wait_for_service('polly')
polly = rospy.ServiceProxy('polly', Polly)
test_text = 'Mary has a little lamb, little lamb, little lamb.'
res = polly(polly_action='SynthesizeSpeech', text=test_text, output_format='mp3')
self.assertIsNotNone(res)
self.assertTrue(type(res) is PollyResponse)
r = json.loads(res.result)
self.assertIn('Audio Type', r, 'result should contain audio type')
self.assertIn('Audio File', r, 'result should contain file path')
self.assertIn('Amazon Polly Response Metadata', r, 'result should contain metadata')
audio_type = r['Audio Type']
audio_file = r['Audio File']
md = r['Amazon Polly Response Metadata']
self.assertTrue("'HTTPStatusCode': 200," in md)
self.assertEqual('audio/mpeg', audio_type)
self.assertTrue(audio_file.endswith('.mp3'))
import subprocess
o = subprocess.check_output(['file', audio_file], stderr=subprocess.STDOUT)
import re
m = re.search(r'.*MPEG.*layer III.*', o, flags=re.MULTILINE)
self.assertIsNotNone(m)
示例16
def test_simple_ssml_via_polly_node(self):
rospy.wait_for_service('polly')
polly = rospy.ServiceProxy('polly', Polly)
text = '<speak>Mary has a little lamb, little lamb, little lamb.</speak>'
res = polly(polly_action='SynthesizeSpeech', text=text, text_type='ssml')
self.assertIsNotNone(res)
self.assertTrue(type(res) is PollyResponse)
r = json.loads(res.result)
self.assertIn('Audio Type', r, 'result should contain audio type')
self.assertIn('Audio File', r, 'result should contain file path')
self.assertIn('Amazon Polly Response Metadata', r, 'result should contain metadata')
audio_type = r['Audio Type']
audio_file = r['Audio File']
md = r['Amazon Polly Response Metadata']
self.assertTrue("'HTTPStatusCode': 200," in md)
self.assertEqual('audio/ogg', audio_type)
self.assertTrue(audio_file.endswith('.ogg'))
import subprocess
o = subprocess.check_output(['file', audio_file], stderr=subprocess.STDOUT)
import re
m = re.search(r'.*Ogg data, Vorbis audi.*', o, flags=re.MULTILINE)
self.assertIsNotNone(m)
示例17
def do_synthesize(goal):
"""calls synthesizer service to do the job"""
rospy.wait_for_service('synthesizer')
synthesize = rospy.ServiceProxy('synthesizer', Synthesizer)
return synthesize(goal.text, goal.metadata)
示例18
def spawn_urdf(name, description_xml, pose, reference_frame):
rospy.wait_for_service('/gazebo/spawn_urdf_model')
try:
spawn_urdf = rospy.ServiceProxy('/gazebo/spawn_urdf_model', SpawnModel)
resp_urdf = spawn_urdf(name, description_xml, "/", pose, reference_frame)
except rospy.ServiceException as e:
rospy.logerr("Spawn URDF service call failed: {0}".format(e))
示例19
def spawn_sdf(name, description_xml, pose, reference_frame):
rospy.wait_for_service('/gazebo/spawn_sdf_model')
try:
spawn_sdf = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
resp_sdf = spawn_sdf(name, description_xml, "/", pose, reference_frame)
except rospy.ServiceException as e:
rospy.logerr("Spawn SDF service call failed: {0}".format(e))
示例20
def delete_gazebo_models(model_list):
# This will be called on ROS Exit, deleting Gazebo models
# Do not wait for the Gazebo Delete Model service, since
# Gazebo should already be running. If the service is not
# available since Gazebo has been killed, it is fine to error out
try:
delete_model = rospy.ServiceProxy('/gazebo/delete_model', DeleteModel)
for model in model_list:
resp_delete = delete_model(model)
except rospy.ServiceException as e:
print("Delete Model service call failed: {0}".format(e))
示例21
def set_start(x, y, theta):
state = ModelState()
state.model_name = 'robot'
state.reference_frame = 'world' # ''ground_plane'
# pose
state.pose.position.x = x
state.pose.position.y = y
state.pose.position.z = 0
quaternion = tf.transformations.quaternion_from_euler(0, 0, theta)
state.pose.orientation.x = quaternion[0]
state.pose.orientation.y = quaternion[1]
state.pose.orientation.z = quaternion[2]
state.pose.orientation.w = quaternion[3]
# twist
state.twist.linear.x = 0
state.twist.linear.y = 0
state.twist.linear.z = 0
state.twist.angular.x = 0
state.twist.angular.y = 0
state.twist.angular.z = 0
rospy.wait_for_service('/gazebo/set_model_state')
try:
set_state = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)
result = set_state(state)
assert result.success is True
print("set the model state successfully")
except rospy.ServiceException:
print("/gazebo/get_model_state service call failed")
示例22
def get_model_pose(model_name, relative_entity_name='world'):
rospy.wait_for_service('gazebo/get_model_state')
try:
get_model_state = rospy.ServiceProxy('gazebo/get_model_state', gazebo_msgs.srv.GetModelState)
res = get_model_state(model_name, relative_entity_name)
return res.pose
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
示例23
def set_model_pose(model_name, model_pose, relative_entity_name='world'):
rospy.wait_for_service('gazebo/set_model_state')
try:
set_model_state = rospy.ServiceProxy('gazebo/set_model_state', gazebo_msgs.srv.SetModelState)
model_state = gazebo_msgs.msg.ModelState()
model_state.model_name = model_name
model_state.pose = model_pose
model_state.reference_frame = relative_entity_name
set_model_state(model_state)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
示例24
def _GetDetections(self, obj_names):
import simtrack_msgs.srv
"""
Calls the service to get a detection of a particular object.
@param obj_name The name of the object to detect
@return A 4x4 transformation matrix describing the pose of the object
in world frame, None if the object is not detected
"""
#Call detection service for a particular object
detect_simtrack = rospy.ServiceProxy(self.service_namespace+'/detect_objects',
simtrack_msgs.srv.DetectObjects)
detect_resp = detect_simtrack(obj_names, 5.0)
detections = []
for i in xrange(0, len(detect_resp.detected_models)) :
obj_name = detect_resp.detected_models[i];
obj_pose = detect_resp.detected_poses[i];
obj_pose_tf = self._MsgToPose(obj_pose);
if (self.detection_frame is not None and self.world_frame is not None):
obj_pose_tf = self._LocalToWorld(obj_pose_tf)
detections.append((obj_name, obj_pose_tf));
return detections
示例25
def get_forward_kinematic(joints):
try:
rospy.wait_for_service('compute_fk', 2)
except (rospy.ServiceException, rospy.ROSException) as e:
rospy.logerr("Service call failed:", e)
return None
try:
moveit_fk = rospy.ServiceProxy('compute_fk', GetPositionFK)
fk_link = ['base_link', 'tool_link']
joint_names = ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'joint_6']
header = Header(0, rospy.Time.now(), "/world")
rs = RobotState()
rs.joint_state.name = joint_names
rs.joint_state.position = joints
response = moveit_fk(header, fk_link, rs)
except rospy.ServiceException as e:
rospy.logerr("Service call failed:", e)
return None
quaternion = [response.pose_stamped[1].pose.orientation.x, response.pose_stamped[1].pose.orientation.y,
response.pose_stamped[1].pose.orientation.z, response.pose_stamped[1].pose.orientation.w]
rpy = get_rpy_from_quaternion(quaternion)
quaternion = Position.Quaternion(round(quaternion[0], 3), round(quaternion[1], 3), round(quaternion[2], 3),
round(quaternion[3], 3))
point = Position.Point(round(response.pose_stamped[1].pose.position.x, 3),
round(response.pose_stamped[1].pose.position.y, 3),
round(response.pose_stamped[1].pose.position.z, 3))
rpy = Position.RPY(round(rpy[0], 3), round(rpy[1], 3), round(rpy[2], 3))
rospy.loginfo("kinematic forward has been calculated ")
return point, rpy, quaternion
示例26
def activate_learning_mode(activate):
try:
rospy.wait_for_service('/niryo_one/activate_learning_mode', 1)
srv = rospy.ServiceProxy('/niryo_one/activate_learning_mode', SetInt)
resp = srv(int(activate))
return resp.status == 200
except (rospy.ServiceException, rospy.ROSException), e:
return False
示例27
def set_calibration_camera(self, obj_name):
service_name = self.__services_name['set_calibration_camera_service']
rospy.wait_for_service(service_name)
msg = SetCalibrationCamRequest()
# msg.label = "MDRRR"
msg.name = obj_name
try:
calibra_service = rospy.ServiceProxy(service_name, SetCalibrationCam)
res = calibra_service(msg)
return self.__status_interpreter_calibration[res.status]
except rospy.ServiceException, e:
print "Service call failed: %s" % e
示例28
def get_calibration_camera(self):
service_name = self.__services_name['get_calibration_camera_service']
rospy.wait_for_service(service_name)
try:
calibra_service = rospy.ServiceProxy(service_name, GetCalibrationCam)
res = calibra_service(Empty())
return res
except rospy.ServiceException, e:
print "Service call failed: %s" % e
示例29
def get_debug_markers(self):
service_name = self.__services_name['debug_markers']
rospy.wait_for_service(service_name)
try:
service = rospy.ServiceProxy(service_name, DebugMarkers)
response = service()
im_ret = extract_img_from_ros_msg(response.img)
return im_ret
except rospy.ServiceException, e:
print "Service call failed: %s" % e
示例30
def get_debug_colors(self, color):
service_name = self.__services_name['debug_colors']
rospy.wait_for_service(service_name)
try:
service = rospy.ServiceProxy(service_name, DebugColorDetection)
response = service(color)
im_ret = extract_img_from_ros_msg(response.img)
return im_ret
except rospy.ServiceException, e:
print "Service call failed: %s" % e