实现参数服务器参数的增删改查操作
支持整型,浮点型,字符串,布尔,vector,map等
#include "ros/ros.h"
/*
需要实现参数的新增和修改
需求:首先设置机器人的共享参数,类型、半径
再修改半径
实现:
ros::NodeHandle
setParam("键", 值)
ros::param
set("键", 值)
修改只需要继续调用setParam或set函数,保证键是已经存在的,那么值会覆盖
*/
int main(int argc, char *argv[])
{
//初始化ROS节点
ros::init(argc,argv,"set_param_c");
//创建ROS节点句柄
ros::NodeHandle n;
//参数增----------------------------------------------------
//方案1:n
n.setParam("type","xiaoHuang");
n.setParam("radius",0.15);
//方案2:ross::param
ros::param::set("type_param","xiaoBai");
ros::param::set("radius_param",0.15);
//参数改----------------------------------------------------
//方案1:n
n.setParam("radius",0.2); //覆盖
return 0;
ros::param::set("radius_param",0.25);
}
当然别忘了在CMakeLists里头修改配置。
实现效果:
增加:
$ catkin_make
$ source ./devel/setup.bash
$ rosrun server_demo server_demo_set
$ rosparam list
$ rosparam get /type
$ rosparam get /radius
修改:
$ rosparam get /radius
可以看到参数radius已经修改过了
#include "ros/ros.h"
/*
实现参数的查询
*/
int main(int argc, char *argv[])
{
//设置编码
setlocale(LC_ALL,"");
ros::init(argc,argv,"get_param_c");
ros::NodeHandle n;
//ros::NodeHandle------------------------------
//1.param(键,默认值)
//存在,返回对应结果,否则返回默认值
double radius = n.param("radius",0.5);
ROS_INFO("radius = %.2f", radius);
//2.getParam(键,存储结果的变量)
//存在,返回 true,且将值赋值给参数2
//如果键不存在,那么返回值为 false,且不为参数2赋值
double radius2 = 0.0;
bool result = n.getParam("radius2",radius2);
if(result) ROS_INFO("获取的半径是: %.2f",radius2);
else ROS_INFO("被查询的变量不存在");
//3.getParamCached(键,存储结果的变量)--提高变量获取效率
//存在,返回 true,且将值赋值给参数2
//如果键不存在,那么返回值为 false,且不为参数2赋值
double radius3 = 0.0;
bool result2 = n.getParam("radius2",radius3);
if(result2) ROS_INFO("获取的半径是: %.2f",radius3);
else ROS_INFO("被查询的变量不存在");
//4.getParamNames(std::vector)
//获取所有的键,并存储在参数 vector 中
std::vector<std::string> names;
n.getParamNames(names);
for(auto &&name : names)
ROS_INFO("遍历的元素: %s", name.c_str());
//5.hasParam(键)
//是否包含某个键,存在返回 true,否则返回 false
bool flag1 = n.hasParam("radius");
bool flag2 = n.hasParam("radius2");
ROS_INFO("radius 存在吗? %d", flag1);
ROS_INFO("radius2 存在吗? %d", flag2);
//6.searchParam(参数1,参数2)
//搜索键,参数1是被搜索的键,参数2存储搜索结果的变量
std::string key;
n.searchParam("radius", key);
ROS_INFO("搜索结果: %s",key.c_str());
return 0;
}
#include "ros/ros.h"
/*
演示参数删除
ros::NodeHandle
delParam()
ros::param
del()
*/
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
ros::init(argc,argv,"param_del_c");
ros::NodeHandle n;
//删除:NodeHandle-------------------------
bool flag1 = n.deleteParam("radius");
if(flag1) ROS_INFO("删除成功");
else ROS_INFO("删除失败");
//删除:ros::param-------------------------
bool flag2 = ros::param::del("radius_param");
if(flag2) ROS_INFO("删除成功");
else ROS_INFO("删除失败");
return 0;
}