ROS Noetic入门笔记(一)在ubuntu20.04中安装ROS Noetic并简单测试
ROS Noetic入门笔记(二)ROS Noetic创建工作空间和功能包
ROS Noetic入门笔记(三)ROS Noetic中的常用命令及工具
ROS Noetic入门笔记(四)使用rqt_console和roslaunch
ROS Noetic入门笔记(五)创建ROS话题消息(msg)和服务数据(srv
ROS Noetic入门笔记(六)使用C++编写简单的Publisher与Suscriber
ROS Noetic入门笔记(七)使用Python编写简单的Publisher与Suscriber
ROS Noetic入门笔记(八)运行Publisher与Suscriber
ROS Noetic入门笔记(九)使用C++编写简单的Server与Client
ROS Noetic入门笔记(十)使用Python编写简单的Server与Client
ROS Noetic入门笔记(十一)使用rosbag实现数据记录与回放
文章目录
1.使用roscd跳转到beginner_tutorials功能包目录
先设置环境变量
$ cd ~/catkin_ws
$ source ./devel/setup.bash
然后roscd到beginner_tutorials功能包
$ roscd beginner_tutorials
2.创建Server
(1) 在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()
(2) 给add_two_ints_server.py可执行权限
$ chmod +x add_two_ints_server.py
3.创建Client
(1) 在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)))
(2) 给add_two_ints_client.py可执行权限
$ chmod +x add_two_ints_server.py
4.运行Server与Client
上一篇:ROS Noetic入门笔记(九)使用C++编写简单的Server与Client
下一篇:ROS Noetic入门笔记(十一)使用rosbag实现数据记录与回放