玩命加载中 . . .

ROS自定义srv


自定义 srv 消息

string name
---
int32 age
bool sex

修改 CMakeLists.txt

add_service_files(
  FILES
  stu.srv
)

generate_messages(
  DEPENDENCIES
  std_msgs
  std_srvs
)

代码示例

服务端

#include <ros/ros.h>
#include <iostream>
#include <string>
#include "ros_learning/stu.h"
using namespace std;

// 注意回调函数的参数写法
bool stu_cb(ros_learning::stu::Request &request, ros_learning::stu::Response &response)
{
    string input_name(request.name);
    cout << input_name << endl;
    response.age = 20;
    response.sex = true;
    return true;
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "service");
    ros::NodeHandle nh;
    ros::ServiceServer service = nh.advertiseService("look_up_stu", stu_cb);
    ros::spin();
}

客户端

#include <ros/ros.h>
#include <iostream>
#include <string>
#include "ros_learning/stu.h"
using namespace std;

int main(int argc, char** argv)
{
    ros::init(argc, argv, "client");
    ros::NodeHandle n;
    ros::ServiceClient client = n.serviceClient<ros_learning::stu>("look_up_stu");
    ros_learning::stu srv;
    string inputName;
    while(ros::ok())
    {
        cin >> inputName;
        srv.request.name = inputName;
        if (!inputName.compare("exit"))
            return 0; 
        if (client.call(srv))
        {
            cout << "name: " << srv.request.name << endl;
            cout << "age: " << srv.response.age << endl;
            cout << "sex: " << srv.response.sex << endl;
        }
            
    }
    return 0;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录