ROS机器人操作系统:从入门到放弃(五)服务中的Server和Cliet

感情迁移 提交于 2019-11-26 14:13:12

编写AddTwoInts.srv文件

int64 a
int64 b
---
int64 sum

编写Server代码

#include <ros/ros.h>
#include <example2/AddTwoInts.h>////beginner_tutorials/AddTwoInts.h是由编译系统自动根据我们先前创建的srv文件生成的对应该srv文件的头文件。

bool add(example2::AddTwoInts::Request &req,
         example2::AddTwoInts::Response &res)
{
    res.sum = req.a + req.b;
    ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
    ROS_INFO("sending back response: [%ld]", (long int)res.sum);

    return true;
}

int main(int argc, char ** argv)
{
    ros::init(argc, argv, "example2_server");
    ros::NodeHandle n;
    ros::ServiceServer service = n.advertiseService("AddTwoInts", add);
    ROS_INFO("Ready to add two ints.");
    ros::spin();

    return 0;
}

编写Client代码

#include<cstdlib>
#include "ros/ros.h"
#include<example2/AddTwoInts.h>

int main(int argc, char ** argv)
{
    ros::init(argc, argv, "example2_client");

    if(argc != 3)
    {
        ROS_INFO("usage: add_two_ints_client X Y");
        return 1;
    }

    ros::NodeHandle n;
    ros::ServiceClient client = n.serviceClient<example2::AddTwoInts>("AddTwoInts");

    example2::AddTwoInts srv;
    srv.request.a = atoll(argv[1]);
    srv.request.b = atoll(argv[2]);

    if(client.call(srv))
    {
        ROS_INFO("Sum: %ld", (long int)srv.response.sum);
    }
    else
    {
        ROS_INFO("Failed to call service add_two_ints");
        return 1;
    }
    return 0;
}

运行代码

$ roscore
$ rosrun example2 server
$ rosrun example2 client 4 5
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!