ROS学习笔记(二)- 提供服务和调用服务

书接上回 - https://www.cnblogs.com/lihan829/p/17315435.html

前面展示了ROS节点发布和订阅消息,这次展示如何提供服务和调用服务。

提供服务和调用服务很好理解,概念和行为上并不深奥,就是远程过程调用,可类比为http接口的远程调用,grpc接口的远程调用等等。

1,服务提供方,定义服务,服务就是一个可以远程调用的方法,是方法,就要有传入参数和返回值,需要先定义好。在lesson001目录下新建一个srv目录,注意你没有看错,就是srv目录,不是src目录,据说是专门用来存放服务定义的。

cd ~/ros-learning
roscd lesson001
mkdir srv
cd srv
touch Number.srv

Number.srv内容如下:

int64 a
int64 b
---
int64 sum

前两行表示两个传入参数及其类型,三个小减号是分隔符,据说也是专用的,ROS规范的一部分,分隔符下面是返回值及其类型。

2,在srv同层级的src目录下写提供服务和调用服务的python源码:

add_two_numbers_client.py(调用者):

#!/usr/bin/env python
import rospy
from lesson001.srv import Number, NumberRequest

def add_two_numbers_client(x, y):
    rospy.wait_for_service('add_two_numbers')
    try:
        add_two_numbers = rospy.ServiceProxy('add_two_numbers', Number)
        resp = add_two_numbers(x, y)
        return resp.sum
    except rospy.ServiceException as e:
        rospy.logerr("Service call failed: %s" % e)

if __name__ == "__main__":
    rospy.init_node('add_two_numbers_client')
    x = 5
    y = 10
    rospy.loginfo("Requesting %d + %d" % (x, y))
    result = add_two_numbers_client(x, y)
    rospy.loginfo("Sum is %d" % (result))

add_two_numbers_server.py(提供者):

#!/usr/bin/env python
import rospy
from lesson001.srv import Number, NumberResponse

def handle_add_two_ints(req):
    result = req.a + req.b
    rospy.loginfo("Sum of %d and %d is %d" % (req.a, req.b, result))
    return NumberResponse(result)

def add_two_numbers_server():
    rospy.init_node('add_two_numbers_server')
    s = rospy.Service('add_two_numbers', Number, handle_add_two_ints)
    rospy.loginfo("Ready to add two numbers.")
    rospy.spin()

if __name__ == "__main__":
    add_two_numbers_server()

3,在src同级别的package.xml和CMakeLists.txt加入一些内容,注意要加入到对应的位置,找一下不难发现的

package.xml:

<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
<build_depend>std_msgs</build_depend>
<exec_depend>std_msgs</exec_depend>

CMakeLists.txt,注意有些内容本来是注释了的,可以取消注释:

find_package(catkin REQUIRED COMPONENTS
  rospy
  std_msgs
  message_generation
)

add_service_files(
  FILES
  Number.srv
)

generate_messages(
  DEPENDENCIES
  std_msgs
)

catkin_package(
  CATKIN_DEPENDS rospy std_msgs message_runtime
)

4,先给server和client文件赋予执行权限`chmod +x add_two_numbers_server.py add_two_numbers_client.py`,再来到项目根目录也就是`cd ~/ros-learning`,执行`catkin_make`

5,roscore每启动的话先启动,然后分别在不同的终端启动server和client:

#终端1
source devel/setup.bash
roscore

#终端2
source devel/setup.bash
rosrun lesson001 add_two_numbers_server.py

#终端3
source devel/setup.bash
rosrun lesson001 add_two_numbers_client.py

无图无真相:

 

posted @ 2023-04-13 18:19  透明飞起来了  阅读(136)  评论(0编辑  收藏  举报