• ROS 接口调参 加载参数 动态参数 从NodeHandle中加载参数


    参数类型

    ROS 参数服务器本质上是可以网络访问的参数词典, ROS 参数服务器能保存的数据类型包括字符串 、整型、浮点型、布尔型、列表、词典等;
    参数根据类型不同可以分为全局参数、相对参数、私有参数等;
    其中以 “/” 开头的参数为全局参数,以 开头的参数为私有参数,其他参数为相对参数;

    参数接口

    操作参数的四种方法:
    ROS 提供了两种管理参数的 API 实时的存储、获取参数:
    一个是通过 ros::param 命令空间                      一个是通过 ros::NodeHandle 接口
    Launch 文件中加载参数
    从参数文件中加载参数
    通过动态参数 dynamic_reconfigure 接口调整参数

    获取的两种方式:

    通过NodeHandle操作参数

    参数的设置、删除、获取、查询等操作方式。
    void NodeHandle::setParam(const std::string& key, double d)                             设置
    bool NodeHandle::deleteParam(const std::string& key)                                        删除
    bool NodeHandle::getParam(const std::string& key, double& d)                           获取
    bool NodeHandle::searchParam(const std::string& key, std::string& result_out)   查询
      

    查看参数

    ROS 中,
    rosparam 命令可以用来查看参数。需注意,利用 rosparam 操作参数必须在 roscore 启动后才能
    进行,主要方法有:
    # 设置参数            $rosparam set [参数名 ]
    # 删除参数            $rosparam delete
    # 获取参数            $rosparam get [参数名 ]
    # 查看参数列表     $rosparam list

    从NodeHandle中加载参数---实例查看参数:

    1. #include
    2. int main(int argc, char **argv){
    3. ros::init(argc,argv,"hello"); // 初始化节点
    4. ros::NodeHandle nh("~"); // 初始化句柄
    5. bool isRun = false;
    6. nh.setParam("is_run",true); // 注入全局参数
    7. nh.setParam("/is_test",true);
    8. if(nh.hasParam("is_run") == true){ // 判断是否有该节点
    9. nh.getParam("is_run",isRun);
    10. ROS_INFO("the status is %d",isRun);
    11. }else{
    12. ROS_INFO("the is_run status is not defined");
    13. }
    14. return 0;
    15. }

    从launch文件中加载参数

    参数通过 param 标签实现。
    参数为全局参数, param 标签作为 launch 标签的子标签
    参数为相对参数, param 标签作为 node 标签的子标签
    1. "serial" value="5"/>
    2. "client" pkg="example_3" type="client" output="screen">
    3. "client_x" type="int" value="1" />

    从配置文件中加载参数

             YAML 是一种可读性高、轻量级的标记语言,
             广泛用于 ROS Spring 等框架的配置,它对大小写敏感,
             使用缩进表示层级关系,但缩进使用空格(2个或者4个)而非Tab 键表示。
             YAML 支持对象、数组、常量三种 数据类型。
    参数配置在 YAML 文件中,注意冒号后面有空格
    YAML 文件通常放置于程序包的 config 目录下
    通过 launch 文件的 rosparam 标签加载配置文件来完成参数配置,添加路径
    1. "yaml" pkg="example_2" type="yaml" clear_params="true" output="screen">
    2. "$(find example_2)/config/test.yaml"/>

    加载参数示例

     步骤1: 创建 load.launch (从 Launch 中加载参数)
     步骤2: 创建配置文件 config/test.yaml
     步骤3: 创建 yaml.launch (从配置文件中加载参数)
     步骤4: 读取参数,创建 yaml.cpp
     步骤5: 修改 CMakeLists.txt
     步骤1: 创建load.launch
    1. "isLoad" type="bool" value="true"/> #定义全局标签 bool
    2. "yaml" pkg="example_2" type="yaml" clear_params="true" output="screen">
    3. #四个相对应的参数
    4. "first_name" type="string" value="fabio" />
    5. "last_name" type="string" value="miao" />
    6. "age" type="int" value="39" />
    7. "score" type="int" value="150" />

     步骤2:创建配置文件config/test.yaml

    1. first_name: fabio
    2. last_name: miaozl
    3. age: 37
    4. score: 100
    5. #注意中间一定需要空格

     步骤4:读取参数,创建yaml.cpp

    1. #include
    2. int main(int argc, char **argv)
    3. {
    4. ros::init(argc, argv, "yaml"); // 生成yaml的节点
    5. ros::NodeHandle nh; //
    6. std::string first,last;
    7. int age = 0 , score = 100;
    8. bool isLoad = false;
    9. nh.getParam("/yaml/first_name",first); // 读出节点中的值加入读出
    10. nh.getParam("/yaml/last_name",last);
    11. ROS_INFO("his first name is %s,his last name is %s",first.c_str(),last.c_str());
    12. nh.getParam("/yaml/age",age); // 读年龄 读分数
    13. ROS_INFO("first name is %d",age);
    14. nh.getParam("/yaml/score",score);
    15. ROS_INFO("first name is %d",score);
    16. nh.getParam("/isLoad",isLoad);
    17. if(isLoad){
    18. ROS_INFO("the param is load");
    19. }else{
    20. ROS_INFO("the param isn't load");
    21. }
    22. }

     步骤5:修改CMakeLists.txt

    主要添加修改文件 ---  编译link Libraries 库文件

    1. cmake_minimum_required(VERSION 3.0.2)
    2. project(example_2)
    3. ## Compile as C++11, supported in ROS Kinetic and newer
    4. # add_compile_options(-std=c++11)
    5. ## Find catkin macros and libraries
    6. ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
    7. ## is used, also find other catkin packages
    8. find_package(catkin REQUIRED COMPONENTS
    9. roscpp
    10. rospy
    11. std_msgs
    12. message_generation
    13. dynamic_reconfigure
    14. )
    15. ## System dependencies are found with CMake's conventions
    16. # find_package(Boost REQUIRED COMPONENTS system)
    17. ## Uncomment this if the package has a setup.py. This macro ensures
    18. ## modules and global scripts declared therein get installed
    19. ## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
    20. # catkin_python_setup()
    21. ################################################
    22. ## Declare ROS messages, services and actions ##
    23. ################################################
    24. ## To declare and build messages, services or actions from within this
    25. ## package, follow these steps:
    26. ## * Let MSG_DEP_SET be the set of packages whose message types you use in
    27. ## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
    28. ## * In the file package.xml:
    29. ## * add a build_depend tag for "message_generation"
    30. ## * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
    31. ## * If MSG_DEP_SET isn't empty the following dependency has been pulled in
    32. ## but can be declared for certainty nonetheless:
    33. ## * add a exec_depend tag for "message_runtime"
    34. ## * In this file (CMakeLists.txt):
    35. ## * add "message_generation" and every package in MSG_DEP_SET to
    36. ## find_package(catkin REQUIRED COMPONENTS ...)
    37. ## * add "message_runtime" and every package in MSG_DEP_SET to
    38. ## catkin_package(CATKIN_DEPENDS ...)
    39. ## * uncomment the add_*_files sections below as needed
    40. ## and list every .msg/.srv/.action file to be processed
    41. ## * uncomment the generate_messages entry below
    42. ## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)
    43. ## Generate messages in the 'msg' folder
    44. # add_message_files(
    45. # FILES
    46. # Message1.msg
    47. # Message2.msg
    48. # )
    49. ## Generate services in the 'srv' folder
    50. # add_service_files(
    51. # FILES
    52. # Service1.srv
    53. # Service2.srv
    54. # )
    55. ## Generate actions in the 'action' folder
    56. # add_action_files(
    57. # FILES
    58. # Action1.action
    59. # Action2.action
    60. # )
    61. ## Generate added messages and services with any dependencies listed here
    62. # generate_messages(
    63. # DEPENDENCIES
    64. # std_msgs
    65. # )
    66. ################################################
    67. ## Declare ROS dynamic reconfigure parameters ##
    68. ################################################
    69. ## To declare and build dynamic reconfigure parameters within this
    70. ## package, follow these steps:
    71. ## * In the file package.xml:
    72. ## * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
    73. ## * In this file (CMakeLists.txt):
    74. ## * add "dynamic_reconfigure" to
    75. ## find_package(catkin REQUIRED COMPONENTS ...)
    76. ## * uncomment the "generate_dynamic_reconfigure_options" section below
    77. ## and list every .cfg file to be processed
    78. ## Generate dynamic reconfigure parameters in the 'cfg' folder
    79. generate_dynamic_reconfigure_options(
    80. cfg/Test.cfg
    81. )
    82. ###################################
    83. ## catkin specific configuration ##
    84. ###################################
    85. ## The catkin_package macro generates cmake config files for your package
    86. ## Declare things to be passed to dependent projects
    87. ## INCLUDE_DIRS: uncomment this if your package contains header files
    88. ## LIBRARIES: libraries you create in this project that dependent projects also need
    89. ## CATKIN_DEPENDS: catkin_packages dependent projects also need
    90. ## DEPENDS: system dependencies of this project that dependent projects also need
    91. catkin_package(
    92. # INCLUDE_DIRS include
    93. # LIBRARIES example_2
    94. # CATKIN_DEPENDS roscpp rospy std_msgs
    95. # DEPENDS system_lib
    96. )
    97. ###########
    98. ## Build ##
    99. ###########
    100. ## Specify additional locations of header files
    101. ## Your package locations should be listed before other locations
    102. include_directories(
    103. # include
    104. ${catkin_INCLUDE_DIRS}
    105. )
    106. ## Declare a C++ library
    107. # add_library(${PROJECT_NAME}
    108. # src/${PROJECT_NAME}/example_2.cpp
    109. # )
    110. ## Add cmake target dependencies of the library
    111. ## as an example, code may need to be generated before libraries
    112. ## either from message generation or dynamic reconfigure
    113. # add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
    114. ## Declare a C++ executable
    115. ## With catkin_make all packages are built within a single CMake context
    116. ## The recommended prefix ensures that target names across packages don't collide
    117. # add_executable(${PROJECT_NAME}_node src/example_2_node.cpp)
    118. add_executable(yaml src/yaml.cpp)
    119. add_executable(param src/param.cpp)
    120. ## Rename C++ executable without prefix
    121. ## The above recommended prefix causes long target names, the following renames the
    122. ## target back to the shorter version for ease of user use
    123. ## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
    124. # set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")
    125. ## Add cmake target dependencies of the executable
    126. ## same as for the library above
    127. # add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
    128. ## Specify libraries to link a library or executable target against
    129. # target_link_libraries(${PROJECT_NAME}_node
    130. # ${catkin_LIBRARIES}
    131. # )
    132. target_link_libraries(yaml
    133. ${catkin_LIBRARIES}
    134. )
    135. target_link_libraries(param
    136. ${catkin_LIBRARIES}
    137. )
    138. #############
    139. ## Install ##
    140. #############
    141. # all install targets should use catkin DESTINATION variables
    142. # See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html
    143. ## Mark executable scripts (Python etc.) for installation
    144. ## in contrast to setup.py, you can choose the destination
    145. # catkin_install_python(PROGRAMS
    146. # scripts/my_python_script
    147. # DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    148. # )
    149. ## Mark executables for installation
    150. ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
    151. # install(TARGETS ${PROJECT_NAME}_node
    152. # RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
    153. # )
    154. ## Mark libraries for installation
    155. ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
    156. # install(TARGETS ${PROJECT_NAME}
    157. # ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    158. # LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
    159. # RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
    160. # )
    161. ## Mark cpp header files for installation
    162. # install(DIRECTORY include/${PROJECT_NAME}/
    163. # DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
    164. # FILES_MATCHING PATTERN "*.h"
    165. # PATTERN ".svn" EXCLUDE
    166. # )
    167. ## Mark other files for installation (e.g. launch and bag files, etc.)
    168. # install(FILES
    169. # # myfile1
    170. # # myfile2
    171. # DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
    172. # )
    173. #############
    174. ## Testing ##
    175. #############
    176. ## Add gtest based cpp test target and link libraries
    177. # catkin_add_gtest(${PROJECT_NAME}-test test/test_example_2.cpp)
    178. # if(TARGET ${PROJECT_NAME}-test)
    179. # target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
    180. # endif()
    181. ## Add folders to be run by python nosetests
    182. # catkin_add_nosetests(test)

    执行launch后得到

    1. ... logging to /home/xtark/.ros/log/deb4219e-2151-11ed-a25f-874955d4690a/roslaunch-xtark-vmpc-6737.log
    2. Checking log directory for disk usage. This may take a while.
    3. Press Ctrl-C to interrupt
    4. Done checking log file disk usage. Usage is <1GB.
    5. started roslaunch server http://xtark-vmpc:33649/
    6. SUMMARY
    7. ========
    8. CLEAR PARAMETERS
    9. * /yaml/
    10. PARAMETERS
    11. * /isLoad: True
    12. * /rosdistro: noetic
    13. * /rosversion: 1.15.13
    14. * /yaml/age: 39
    15. * /yaml/first_name: fabio
    16. * /yaml/last_name: miao
    17. * /yaml/score: 150
    18. NODES
    19. /
    20. yaml (example_2/yaml)
    21. ROS_MASTER_URI=http://localhost:11311
    22. process[yaml-1]: started with pid [6755]
    23. [ INFO] [1661087150.225233609]: his first name is fabio,his last name is miao
    24. [ INFO] [1661087150.226000645]: first name is 39
    25. [ INFO] [1661087150.226231003]: first name is 150
    26. [ INFO] [1661087150.226447102]: the param is load
    27. [yaml-1] process has finished cleanly
    28. log file: /home/xtark/.ros/log/deb4219e-2151-11ed-a25f-874955d4690a/yaml-1*.log
    29. all processes on machine have died, roslaunch will exit
    30. shutting down processing monitor...
    31. ... shutting down processing monitor complete
    32. done

  • 相关阅读:
    uni-app+vue3会遇到哪些问题
    软考备考-程序员-备考笔记
    Unity工具 - 工具聚合页(UEWindow)
    docker 构建并运行 python项目
    docker使用bind9实现域名解析
    MySQL(十一) 用户管理
    原生Js Canvas去除视频绿幕背景
    基于低能耗自适应聚类层次结构(LEACH)(Matlab代码实现)
    设计模式3、工厂方法模式 Factory Method
    六、数组及其操作《2022 solidity8.+ 版本教程到实战》
  • 原文地址:https://blog.csdn.net/weixin_44025389/article/details/126455136