-
step1
到目标package下
mkdir srv
创建一个srv文件
-
step2
修改CMakeLists.txt
step3
修改package.xml
添加这两句
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
-
step4
到工作空间目录下
catkin_make
在Python中call一个service
import rospy
from gazebo_msgs.srv import DeleteModel ,DeleteModelRequest
from roscpp.srv import GetLoggers,GetLoggersRequest
import sys
rospy.init_node('service_client')
rospy.wait_for_service('/gazebo/delete_model')
delete_model_service=rospy.ServiceProxy('/gazebo/delete_model',DeleteModel)
kk=DeleteModelRequest()
kk.model_name="unit_box"
result=delete_model_service(kk)
print(result)
rospy.wait_for_service('gazebo_gui/get_loggers')
get_loggers_service=rospy.ServiceProxy('gazebo_gui/get_loggers',GetLoggers)
# gg=GetLoggersRequest()
result=get_loggers_service()
print('get Result:\n{}'.format(result))
上面这段代码是两个例子,一个是GAZEBO删除模型,一个是/rosout/get_loggers
首先是检查service是否可用,wait_for_service 的作用如下:
Blocks until service is available. Use this in initialization code if your program depends on a service already running
如果你的service需要request的话,就要import <你的service的名字>Request
然后使用它。
写一个service server
上面我们加了一个srv文件,现在我们来为它写一个service server。
这个srv需要传入一个float64,一个int32,然后执行一系列操作后返回成功或失败(这个例子里只有True)
具体来说就是让turtlesim里的小海龟画一个正方形,radius是这个正方形的边长,repetitions决定走几遍。
#! /usr/bin/env python
import rospy
from test_package.srv import my_custom_service_message,my_custom_service_messageRequest,my_custom_service_messageResponse
from geometry_msgs.msg import Twist
from math import radians
def my_cus_callback(req):
print(req.radius)
print(req.repetitions)
turtle1_draw_square(req.radius,req.repetitions)
return my_custom_service_messageResponse(True)
def turtle1_draw_square(radius,repetitions):
pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
rate = rospy.Rate(10)
move_cmd = Twist()
move_cmd.linear.x = radius
turn_cmd = Twist()
turn_cmd.angular.z = radians(90)
print('go forward')
for rep in range(repetitions):
for i in range(4):
for x in range(20):
pub.publish(move_cmd)
rate.sleep()
print('turn right')
for z in range(10):
pub.publish(turn_cmd)
rate.sleep()
rospy.init_node('service_server')
my_cus_service=rospy.Service('my_cus_service',my_custom_service_message,my_cus_callback)
rospy.spin()