創建 std_srvs::Empty 型 Service (參數爲空的服務)

參考: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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章