service通信server-python
service通信server¶
service通信分为server和client端
实现¶
1. 创建package¶
ros2 pkg create --build-type ament_python py_srvcli --dependencies rclpy example_interfaces
可以修改
package.xml
文件如下信息<description>C++ client server tutorial</description> <maintainer email="you@email.com">Your Name</maintainer> <license>Apache License 2.0</license>
2. 编写server节点代码¶
2.1 编写代码¶
- 在package的
py_srvcli
下创建server.py
文件,代码如下
from example_interfaces.srv import AddTwoInts
import rclpy
from rclpy.node import Node
class MyServer(Node):
def __init__(self):
super(MyServer, self).__init__('py_server')
self.service = self.create_service(AddTwoInts, 'py_service', self.call_back)
def call_back(self,req,res):
res.sum = req.a+req.b
return res
def main():
rclpy.init()
node = MyServer()
rclpy.spin(node)
rclpy.shutdown()
if __name__ == '__main__':
main()
2.2 添加配置¶
- 打开
setup.py
文件,在console_scripts
节点下添加配置
'service = py_srvcli.server:main',
3. 编译工程¶
colcon build
4. 运行节点¶
ros2 run py_srvcli service