CodeTheRobot

C++ Advanced · Lesson 13 of 23

Services

Request and response calls with create_service and create_client.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain services in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

A service is a short request and response, like a function call between nodes. The server registers a callback that fills in the response; the client sends a request and receives a future for the answer. Use it for quick queries and commands, such as 'reset the counter'.

Do not call spin_until_future_complete inside a callback, and do not use a service for work that takes seconds; that is a job for an action. Check that the service is available with wait_for_service before calling.

Guided lesson

Work through these steps

  1. 1.

    Read the services example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include "example_interfaces/srv/add_two_ints.hpp"
// A ready-made service type with a and b in the request, sum in the response.
class AddServer : public rclcpp::Node {
// The server node.
public:
// Public interface.
  AddServer() : Node("add_server") {
// Name the node.
    srv_ = create_service<example_interfaces::srv::AddTwoInts>("add",
// Offer a service named /add.
      [](const std::shared_ptr<example_interfaces::srv::AddTwoInts::Request> req,
// The callback receives the request...
         std::shared_ptr<example_interfaces::srv::AddTwoInts::Response> res) {
// ...and a response object to fill in.
        res->sum = req->a + req->b;
// Compute the answer.
      });
// End of the callback.
  }
// End of the constructor.
private:
// Hidden state.
  rclcpp::Service<example_interfaces::srv::AddTwoInts>::SharedPtr srv_;
// Keep the service alive with the node.
};
// End of the class.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Messages between nodes

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

requestresponseclientservercalls answered: 0MESSAGES BETWEEN NODES

Demo for Services. Expected result: ros2 service call /add example_interfaces/srv/AddTwoInts '{a: 2, b: 3}' -> sum=5

Practice code

Now type it yourself

Copy the starter into your ROS 2 package, replace every TODO, then build with colcon build and run it from a sourced terminal.

// src/add_server.cpp
#include "example_interfaces/srv/add_two_ints.hpp"
#include "rclcpp/rclcpp.hpp"

using AddTwoInts = example_interfaces::srv::AddTwoInts;

class AddServer : public rclcpp::Node {
 public:
  AddServer() : Node("add_server") {
    // TODO: create the "add" service: put req->a + req->b into res->sum
  }

 private:
  rclcpp::Service<AddTwoInts>::SharedPtr srv_;
};

int main(int argc, char** argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<AddServer>());
  rclcpp::shutdown();
  return 0;
}

Expected output

ros2 service call /add example_interfaces/srv/AddTwoInts '{a: 2, b: 3}'  ->  sum=5
Stuck? Show the full solution (try it yourself first)
// src/add_server.cpp
#include "example_interfaces/srv/add_two_ints.hpp"
#include "rclcpp/rclcpp.hpp"

using AddTwoInts = example_interfaces::srv::AddTwoInts;

class AddServer : public rclcpp::Node {
 public:
  AddServer() : Node("add_server") {
    srv_ = create_service<AddTwoInts>(
        "add", [](const std::shared_ptr<AddTwoInts::Request> req,
                  std::shared_ptr<AddTwoInts::Response> res) { res->sum = req->a + req->b; });
  }

 private:
  rclcpp::Service<AddTwoInts>::SharedPtr srv_;
};

int main(int argc, char** argv) {
  rclcpp::init(argc, argv);
  rclcpp::spin(std::make_shared<AddServer>());
  rclcpp::shutdown();
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Implement the AddServer and a client that calls it with 2 and 3. Test with ros2 service call, then stop the server and confirm the client's wait_for_service times out instead of hanging forever.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.