通常,调试时(尤其是在导航及建图应用中)需要经常修改程序中的参数值,这时无论是修改命令行,还是编写固定修改参数的可执行文件,都无法满足要求。ROS为我们提供了动态参数设置的机制,接下来我们将练习编写具备动态参数设置功能的可执行文件。
创建cfg文件:
创建动态参数ROS包book_dynamic_ param, 加入依赖项roscpp,rospy,dynamic_reconfigure。 在功能包下新建cfg文件夹,并创建DynamicParam.cfg文件, 内容如下:
#!/usr/bin/env python PACKAGE = "book_dynamic_param" from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() gen.add("IntDyParam",int_t,0,"An Int Parameter",0,0,9) gen.add("DouDyParam",double_t,0,"A Double Parameter",1.5,0,9) gen.add("StrDyParam",str_t,0,"A String Parameter","Hello,I'm Robot!") gen.add("BoolDyParam",bool_t,0,"A Bool Parameter",True) student_info = gen.enum([gen.const("Name",str_t,"LiLei","Name Information"), gen.const("Sex",str_t,"Man","Sex Information"), gen.const("Age",str_t,"18","Age Information")], "A set contain a student information") gen.add("StudentInfo",str_t,0,"A studenet information set","LiLei",edit_method=student_info) exit(gen.generate(PACKAGE,"node_DynamicParam","DynamicParam"))
chmod a+x cfg/DynamicParam.cfg
在CMakeL ists.txt文件中添加以下内容:
generate_dynamic_reconfigure_options( cfg/DynamicParam.cfg ) add_dependencies(hell ${PROJECT_NAME}_gencfg)
编译之后,在工作空间目录.../devel/include/book_dynamic_param文件夹下可得到自动生成的DynamicParamConfig.h头文件。
创建动态参数设置可执行文件:
创建book_dyparam.cpp文件, 并添加如下内容:
#include "ros/ros.h" #include "dynamic_reconfigure/server.h" #include "book_dynamic_param/DynamicParamConfig.h" //define call back function void paramCallback(book_dynamic_param::DynamicParamConfig& config,uint32_t level) { ROS_INFO("Request: %d %f %s %s %s", config.IntDyParam,config.DouDyParam, config.StrDyParam.c_str(), config.BoolDyParam?"True":"False", config.StudentInfo.c_str()); } int main(int argc, char** argv) { //initial and name node ros::init(argc,argv,"node_DynamicParam"); //create node handle dynamic_reconfigure::Server<book_dynamic_param::DynamicParamConfig> server; dynamic_reconfigure::Server<book_dynamic_param::DynamicParamConfig>::CallbackType f; f = boost::bind(¶mCallback,_1,_2); server.setCallback(f); ros::spin(); return 0; }
CMakeLists.txt文件内容如下:
cmake_minimum_required(VERSION 2.8.3) project(book_dynamic_param) find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs dynamic_reconfigure) generate_dynamic_reconfigure_options( cfg/DynamicParam.cfg ) catkin_package( ) include_directories( include ${catkin_INCLUDE_DIRS} add_dependencies(hell ${PROJECT_NAME}_gencfg) add_executable(book_dyparam src/book_dyparam.cpp ) add_dependencies(book_dyparam ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) target_link_libraries(book_dyparam ${catkin_LIBRARIES} )
测试:
rosrun book_dynamic_param book_dyparam
rosrun rqt_reconfigure rqt_reconfigure