参考:ros::NodeHandle::advertiseService() API docs 1 包含头文件
#include <std_srvs/Empty.h>
2 创建服务,并绑定服务的回调函数
restart_whole_robot_service_ = nh_.advertiseService("restart_whole_robot", &bp_hdw_common::restart_whole_robot_serviceCB, this);
3 定义服务回调函数功能,注意回调函数的参数为(1)std_srvs::Empty::Request &req; (2)std_srvs::Empty::Response &res
bool bp_hdw_common::restart_whole_robot_serviceCB(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res)
{
return true;
}
在应用中遇到的两个问题: (1)创建服务错误
restart_whole_robot_service_ = nh_.advertiseService("restart_whole_robot", &bp_hdw_common::restart_whole_robot_serviceCB)
报警:
error: no matching function for call to ‘ros::NodeHandle::advertiseService(const char [20], bool (bp_hdw::bp_hdw_common::*)(std_srvs::Empty::Request&, std_srvs::Empty::Response&))’
原因是丢掉了this,函数原型为 advertiseService (const std::string &service, bool(T::*srv_func)(MReq &, MRes &), T *obj),正确结果如下:
restart_whole_robot_service_ = nh_.advertiseService("restart_whole_robot", &bp_hdw_common::restart_whole_robot_serviceCB, this);
(2)通过参考链接将回调函数的参数写为std_srvs::Empty &req 和 std_srvs::Empty &res
restart_whole_robot_serviceCB(std_srvs::Empty &req, std_srvs::Empty &res)
报警:
error: ‘const struct std_srvs::Empty’ has no member named ‘serialize’
正确结果为
restart_whole_robot_serviceCB(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res)