ROS开发笔记(2):基于RoboWare Studio 与Python编写服务(service)通讯节点(node)

版权声明:转载请注明出处,谢谢。 https://blog.csdn.net/wsc820508/article/details/81452954

1、定义服务

选中srv目录名,右键AddSrvFile,这里定义一个计算字符串单词个数count的服务WordCount.srv,文件内容:

string words
---
uint32 count



同样,添加srv文件需要对CMakeLists.txt、package.xml 进行的修改RoboWare Studio也替我们自动完成了:

CMakeLists.txt主要修改了以下几处:

## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
  message_generation
  roscpp
  rospy
  std_msgs
)

catkin_package(
  CATKIN_DEPENDS
  message_runtime
#  INCLUDE_DIRS include
#  LIBRARIES ros_dev_test
#  CATKIN_DEPENDS rospy std_msgs
#  DEPENDS system_lib
)


## Generate services in the 'srv' folder
add_service_files(FILES
  WordCount.srv
)


## Generate added messages and services with any dependencies listed here
generate_messages(DEPENDENCIES
  std_msgs
)
package.xml 增加了:
<build_depend>message_generation</build_depend>
<build_export_depend>message_generation</build_export_depend>
<exec_depend>message_runtime</exec_depend>

然后就 可以点击 ROS菜单下的Build 重新编译工作空间,生成srv文件_WordCount.py,文件包含WordCount、WordCountRequest、WordCountResponse三个类。下面就基于这三个文件来编写WordCount服务的server端与client端代码。

2、实现服务

实现服务的server端代码及注释如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''service_server ROS Node'''
import rospy
from ros_dev_test.srv import WordCount,WordCountResponse

'''定义服务函数'''
def word_count(request):
    return WordCountResponse(len(request.words.split()))


'''节点初始化'''
rospy.init_node('service_server')

'''声明服务'''
rospy.Service('word_count',WordCount,word_count)

'''进入等待服务请求'''
rospy.spin()

记得运行前先 chmod u+x  service_server .py 添加运行权限。

3、使用服务

使用服务的client端代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''service_client ROS Node'''
import rospy
import sys
from ros_dev_test.srv import WordCount,WordCountRequest


'''创建建节点'''
rospy.init_node('service_client')

'''等待服务端声明服务'''
rospy.wait_for_service('word_count')

'''创建服务本地代理'''
word_counter=rospy.ServiceProxy('word_count',WordCount)

'''将命令行参数用空格连接成字符串'''
words=' '.join(sys.argv[1:])

request=WordCountRequest(words)
word_count=word_counter(request)

print words , '->', word_count.count

记得运行前先 chmod u+x  service_client .py 添加运行权限。

4、一些与服务相关的测试命令

rosservice info word_count

wsc@wsc-pc:~/ros1_ws$ rosservice info word_count
Node: /service_server
URI: rosrpc://wsc-pc:34411
Type: ros_dev_test/WordCount
Args: words



wsc@wsc-pc:~/ros1_ws$ rosservice list
/rosout/get_loggers
/rosout/set_logger_level
/service_server/get_loggers
/service_server/set_logger_level
/word_count

猜你喜欢

转载自blog.csdn.net/wsc820508/article/details/81452954