在笔记八中,我们学习了通过topic通讯机制进行通讯后,接下来我们学习使用service通讯机制进行通讯。直接上实战!
首先,还是像以前一样,设置环境变量,使用roscd命令直接进入scripts目录下,创建新的python文件。
source catkin_ws/devel/setup.bash
roscd test_pkg/scripts
touch add_two_ints_service.py
touch add_two_ints_client.py
然后,分别使用vim编辑器,对service文件和client文件进行编辑。
首先,对service文件进行编辑。
rosed test_pkg add_two_ints_service
输入以下代码:
#!/usr/bin/env python3
from __future__ import print_function
from test_pkg.srv import AddTwoInts,AddTwoIntsResponse
import rospy
def handle_add_two_ints(req):
print('Returing [%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_sever')
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
print('Ready to add