目录
一、编写服务节点
二、编写客户端节点
三、构建节点
四、检验服务和客户端
学习ROSwiki官方教程时的笔记,以便后续回顾
跳转到创建的功能包目录
$ roscd beginner_tutorials
在beginner_tutorials包中创建scripts/add_two_ints_server.py文件:
#!/usr/bin/env python
from __future__ import print_function
from beginner_tutorials.srv import AddTwoInts,AddTwoIntsResponse
import rospy
def handle_add_two_ints(req):
print("Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b)))
return AddTwoIntsResponse(req.a + req.b)
def add_two_ints_server():
rospy.init_node('add_two_ints_server')
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
print("Ready to add two ints.")
rospy.spin()
if __name__ == "__main__":
add_two_ints_server()
给节点添加执行权限(scripts目录下):
$ chmod +x scripts/add_two_ints_server.py
然后将以下内容添加到CMakeLists.txt文件。这样可以确保正确安装Python脚本,并使用合适的Python解释器。(必要性?)
catkin_install_python(PROGRAMS scripts/add_two_ints_server.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
在beginner_tutorials包中创建scripts/add_two_ints_client.py文件:
#!/usr/bin/env python
from __future__ import print_function
import sys
import rospy
from beginner_tutorials.srv import *
def add_two_ints_client(x, y):
rospy.wait_for_service('add_two_ints')
try:
add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
resp1 = add_two_ints(x, y)
return resp1.sum
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def usage():
return "%s [x y]"%sys.argv[0]
if __name__ == "__main__":
if len(sys.argv) == 3:
x = int(sys.argv[1])
y = int(sys.argv[2])
else:
print(usage())
sys.exit(1)
print("Requesting %s+%s"%(x, y))
print("%s + %s = %s"%(x, y, add_two_ints_client(x, y)))
同样给节点添加执行权限:
$ chmod +x scripts/add_two_ints_client.py
然后,修改CMakeLists.txt中编辑catkin_install_python()调用:
catkin_install_python(PROGRAMS scripts/add_two_ints_server.py scripts/add_two_ints_client.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
切换当前目录到你的catkin工作空间,然后运行catkin_make:
$ cd ~/catkin_ws
$ catkin_make
确保roscore已经开启:
$ roscore
打开新终端,运行服务:
rosrun beginner_tutorials add_two_ints_server.py
#或者在scripts目录下运行
$ python add_two_ints_server.py
打开新终端,运行客户端:
rosrun beginner_tutorials add_two_ints_client.py 1 9
#或者在scripts目录下运行
$ python add_two_ints_client.py 1 9
完成!