15.1 编写Service Node
这里我们将创建服务(“add_two_ints_server”)节点,它将接收两个int并返回总和。
将目录更改为beginner_tutorials包:
$ roscd beginner_tutorials
请确保您已按照上一教程中的说明创建本教程中所需的服务,创建AddTwoInts.srv
15.1.1 The Code
在beginner_tutorials包中创建scripts / add_two_ints_server.py文件,并在其中粘贴以下内容:
#!/usr/bin/env python
from beginner_tutorials.srv import *
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()
不要忘记给节点增加可执行权限
chmod +x scripts/add_two_ints_server.py
15.1.2 The Code Explained
现在,让我们分解代码。使用rospy编写服务相对简单。我们使用init_node()声明节点,然后声明我们的服务:
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
这用AddTwoInts服务类型声明了一个名为add_two_ints的新服务。所有请求都传递给handle_add_two_ints函数。 handle_add_two_ints用AddTwoIntsRequest的实例调用并返回AddTwoIntsResponse的实例。
就像用户示例一样,rospy.spin()可以让您的代码不会退出,直到服务关闭。
Last updated