文章目录
- 自定义srv
- 1. 定义srv文件
- 2. 修改 package.xml
- 3. 修改 CMakeLists.txt
- 4. sevice_server.py
- 5. 运行 `catkin build`
- 测试
自定义srv
ros 版本:kinetic
自定义test
包的文件结构如下
|-- test
| |-- CMakeLists.txt
| |-- srv
| | `-- WordCount.srv
| |-- package.xml
| |-- scripts
| | `-- sevice_server.py
srv
和msg
非常相似,有关自定义msg
见链接。
1. 定义srv文件
WordCount.srv
#通常大写字母开头;---
上方表输入,下方表输出。
string words
---
uint32 count
2. 修改 package.xml
向其中添加如下信息,首先是<build_depend>message_generation</build_depend>
和<exec_depend>message_runtime</exec_depend>
;其次,需要使用那些包就添加进去,例如 std_msgs
,roscpp
。
<buildtool_depend>catkin</buildtool_depend><build_depend>rospy</build_depend><build_export_depend>rospy</build_export_depend><build_depend>message_generation</build_depend><build_depend>std_msgs</build_depend><build_depend>roscpp</build_depend><exec_depend>roscpp</exec_depend><exec_depend>rospy</exec_depend><exec_depend>message_runtime</exec_depend><exec_depend>std_msgs</exec_depend>
3. 修改 CMakeLists.txt
find_package(catkin REQUIRED COMPONENTSrospyroscppstd_msgsmessage_generation #放在末尾
)
添加自定义的srv文件
add_service_files(FILESWordCount.srv
)
## Generate added messages and services with any dependencies listed here
generate_messages(DEPENDENCIESstd_msgs # Or other packages containing msgs
)
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES testCATKIN_DEPENDS rospy message_runtime std_msgs roscpp
# DEPENDS system_lib
)
## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
catkin_install_python(PROGRAMSscripts/sevice_server.pyDESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
4. sevice_server.py
#!/usr/bin/env pythonimport rospy
from test.srv import WordCount, WordCountRequest, WordCountResponsedef count_words(request):return WordCountResponse(len(request.words.split()))rospy.init_node("service_server")
service = rospy.Service("word_count", WordCount, count_words)rospy.spin()
5. 运行 catkin build
测试
roscore
rosrun test sevice_server.py
rosservice info word_count
顺利的话,会出现如下结果。