Writing a Simple Service and Client (C++)

Here we‘ll create the service ("add_two_ints_server") node which will receive two ints and return the sum.

Change directories to your beginner_tutorials package you created in your catkin workspace previous tutorials:

roscd beginner_tutorials

Writing a Service Node

Please make sure you have followed the directions in the previous tutorial for creating the service needed in this tutorial, creating the AddTwoInts.srv (be sure to choose the right version of build tool you‘re using at the top of wiki page in the link).

#include "ros/ros.h"
#include "beginner_tutorials/AddTwoInts.h"

bool add(beginner_tutorials::AddTwoInts::Request  &req,
         beginner_tutorials::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, "add_two_ints_server");
  ros::NodeHandle n;

  ros::ServiceServer service = n.advertiseService("add_two_ints", add);
  ROS_INFO("Ready to add two ints.");
  ros::spin();

  return 0;
}

Code Explained

#include "ros/ros.h"
#include "beginner_tutorials/AddTwoInts.h"

beginner_tutorials/AddTwoInts.h is the header file generated from the srv file that we created earlier.

bool add(beginner_tutorials::AddTwoInts::Request  &req,
         beginner_tutorials::AddTwoInts::Response &res)

This function provides the service for adding two ints, it takes in the request and response type defined in the srv file and returns a boolean.

{
  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;
}

Here the two ints are added and stored in the response. Then some information about the request and response are logged. Finally the service returns true when it is complete.

  ros::ServiceServer service = n.advertiseService("add_two_ints", add);

Here the service is created and advertised over ROS.

Writing the Client Node

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

int main(int argc, char **argv)
{
  ros::init(argc, argv, "add_two_ints_client");
  if (argc != 3)
  {
    ROS_INFO("usage: add_two_ints_client X Y");
    return 1;
  }

  ros::NodeHandle n;
  ros::ServiceClient client = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints");
  beginner_tutorials::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_ERROR("Failed to call service add_two_ints");
    return 1;
  }

  return 0;
}

Code Explained

ros::ServiceClient client = n.serviceClient<beginner_tutorials::AddTwoInts>("add_two_ints");

This creates a client for the add_two_ints service. The ros::ServiceClient object is used to call the service later on.

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

Here we instantiate an autogenerated service class, and assign values into its request member. A service class contains two members, request and response. It also contains two class definitions, Request and Response.

if (client.call(srv))

This actually calls the service. Since service calls are blocking, it will return once the call is done. If the service call succeeded, call() will return true and the value in srv.response will be valid. If the call did not succeed, call() will return false and the value in srv.response will be invalid.

Building your nodes

(CMakeLists.txt) add the following at the end:

add_executable(add_two_ints_server src/add_two_ints_server.cpp)
target_link_libraries(add_two_ints_server ${catkin_LIBRARIES})
add_dependencies(add_two_ints_server beginner_tutorials_gencpp)

add_executable(add_two_ints_client src/add_two_ints_client.cpp)
target_link_libraries(add_two_ints_client ${catkin_LIBRARIES})
add_dependencies(add_two_ints_client beginner_tutorials_gencpp)

This will create two executables, add_two_ints_server and add_two_ints_client, which by default will go into package directory of your devel space, located by default at ~/catkin_ws/devel/lib/<package name>. You can invoke executables directly or you can use rosrun to invoke them. They are not placed in ‘<prefix>/bin‘ because that would pollute the PATH when installing your package to the system. If you wish for your executable to be on the PATH at installation time, you can setup an install target, see: catkin/CMakeLists.txt

catkin_make

Examining

rosrun beginner_tutorials add_two_ints_server
#Ready to add two ints.
rosrun beginner_tutorials add_two_ints_client 1 3
#Requesting 1+3
#1 + 3 = 4
时间: 2024-10-13 04:25:29

Writing a Simple Service and Client (C++)的相关文章

ROS学习笔记_编写客户端和服务器(service and client)_C++(五)

注意要区分service.client和publisher.subscriber这两组概念的区别. 先占坑... 参考链接:Writing a Simple Service and Client (C++)

ROS 新手测试简单的Service和Client

ROS 新手测试简单的Service和Client 编写简单的Service和Client (C++) Description: 本教程介绍如何用C++编写Service和Client节点. Tutorial Level: BEGINNER Next Tutorial: 测试简单的Service和Client 编写Service节点 这里,我们将创建一个简单的service节点("add_two_ints_server"),该节点将接收到两个整形数字,并返回它们的和. 进入先前你在ca

用C#基于WCF创建TCP的Service供Client端调用

本文将详细讲解用C#基于WCF创建TCP的Service供Client端调用的详细过程 1):首先创建一个Windows Service的工程 2):生成的代码工程结构如下所示 3):我们将Service1改名为MainService 4): 添加一个Interface来定义Service的契约 4.1):截图如下所示 4.2):IOrderService.cs的代码如下所示 using System; using System.Collections.Generic; using System

Learning WCF Chapter1 Generating a Service and Client Proxy

In the previous lab,you created a service and client from scratch without leveraging the tools available to WCF developers. Although this helps you to understand the raw requirements for sending messages between clients and services,in reality,develo

Writing a Simple Publisher and Subscriber (Python)

Writing a Service Node Here we'll create the service ("add_two_ints_server") node which will receive two ints and return the sum. Change directory into the beginner_tutorials package, you created in the earlier tutorial, creating a package: $ ro

Writing a Simple Publisher and Subscriber

Writing the Publisher Node #!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String def talker(): pub = rospy.Publisher('chatter', String, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.R

java的myeclipse生成webservice的service和client

前言:朋友们开始以下教程前,请先看第五大点的注意事项,以避免不必要的重复操作. 一.准备工作(以下为本实例使用工具) 1.MyEclipse10.7.1 2.JDK 1.6.0_22 二.创建服务端 1.创建[Web Service Project],命名为[TheService].   2.创建[Class]类,命名为[ServiceHello],位于[com.hyan.service]包下.   3.编写供客户端调用的方法,即编译方法代码. 4.进行编译 说明:编译失败的话,请将该项目引用的

【11】Writing a Simple Publisher and Subscriber (C++)

Publisher #include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> int main(int argc, char **argv) { ros::init(argc, argv, "talker");   //1.启动该节点 2.并设置其名称(名称要唯一) ros::NodeHandle n; //设置节点句柄 ros::Publisher ch

Writing a Simple Action Server using the Execute Callback

fibonacci_server.cpp /* 黄金分割数列,指的是这样一个数列:1.1.2.3.5.8.13.21.--在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*) */ #include <ros/ros.h> #include <actionlib/server/simple_action_server.h>//action lib #include <learning_actionli