ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

But ofcourse lots of errors and lots of problems when compiling.

You should have posted those errors in the question. Anyway, there is only 1 big problem which is fixed below:

service_server = n.advertiseService("add_two_ints", &SubscribeAndPublish::add, this);

You forgot to pass this while calling advertiseService( ... ). Below is the complete working code:

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

#include <sstream>

class SubscribeAndPublish
{
public:
  SubscribeAndPublish()
  {
    chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
    service_server = n.advertiseService("add_two_ints", &SubscribeAndPublish::add, this);
  }

  bool add(beginner_tutorials::AddTwoInts::Request& req, beginner_tutorials::AddTwoInts::Response& res)
  {
    std_msgs::String msg;

    if (req.a == 1)
    {
      msg.data = "hello world";

      chatter_pub.publish(msg);
    }

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

private:
  ros::NodeHandle n;
  ros::Publisher chatter_pub;
  ros::ServiceServer service_server;

};  // End of class SubscribeAndPublish

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

  SubscribeAndPublish SAPObject;

  ROS_INFO("Ready to add two ints.");
  ros::spin();

  return 0;
}

This is how, I executed it:

  • Terminal 1

    $ roscore
    
  • Terminal 2

    $ rosrun beginner_tutorials subscribe_and_publish
    [ INFO] [1665654555.498672244]: Ready to add two ints.
    [ INFO] [1665654646.303484866]: request: x=1, y=2
    [ INFO] [1665654646.303565863]: sending back response: [3]
    [ INFO] [1665654648.388244758]: request: x=1, y=2
    [ INFO] [1665654648.388283809]: sending back response: [3]
    [ INFO] [1665654661.012366878]: request: x=11, y=22
    [ INFO] [1665654661.012465383]: sending back response: [33]
    
  • Terminal 3

    $ rostopic echo /chatter 
    data: "hello world"
    ---
    data: "hello world"
    ---