最近看的一些代码多是基于ros平台的,相应参数的配置文件写在.yaml文件,而该配置文件的路径又写在launch文件中,通过launch文件传递到参数服务器。
本博客的目的就是写一个上述问题的测试程序。
1.首先我的.yaml配置文件为
%YAML:1.0
id: "1001"
name: "jinye"
age: 24
weight: 62.4
2.配置文件的路径由launch文件获得
这里在补充一下param和arg标签的区别:
param:launch文件执行后,param就加载到ROS的参数服务器上了,可以被节点使用。
arg:不储存在参数服务器中,不能提供给节点使用,只能在launch文件中使用。
3.函数readParam从参数服务器中取参数值并返回
template
T readParam(ros::NodeHandle &n, std::string name)
{
T ans;
if (n.getParam(name, ans))
{
ROS_INFO_STREAM("Loaded " << name << ": " << ans);
}
else
{
ROS_ERROR_STREAM("Failed to load " << name);
n.shutdown();
}
return ans;
}
4.调用readParam函数获得我的配置文件的路径
std::string config_file;
config_file = readParam<:string>(pn, "config_file");
有了配置文件的路径后,就通过cv::FileStorage从里面读取我们所需要的参数
//create FileStorage
cv::FileStorage fs(config_file.c_str(), cv::FileStorage::READ);
//judge open
if(!fs.isOpened())
{
std::cerr << "ERROR: Wrong path to settings" << std::endl;
exit(-1);
}
//read data
std::string id, name;
int age;
double weight;
fs["id"] >> id;
fs["name"] >> name;
fs["age"] >> age;
fs["weight"] >> weight;
5.最后我们看一下效果
执行launch文件后,看一下参数服务器中有哪些参数
其中,/n_arg是我设置的全局命名空间的参数,/node/config_file,/node/pn_arg是私有命名空间下的参数,
/config_file就是我需要的配置文件路径的参数。
有了配置路径后通过cv::FileStorage读取里面的配置参数值
完整的测试程序在这儿
参考
https://www.jianshu.com/p/02ee8f513295
https://www.cnblogs.com/linuxAndMcu/p/10648577.html