0
$\begingroup$

Rosanswers logo

The add_two_ints_client.cpp file in the ros2/demos repository has the following send request function.

image description

Is there a way to make this send request function generic for other services I have created?


Originally posted by mikepark93 on ROS Answers with karma: 47 on 2019-08-05

Post score: 0


Original comments

Comment by jayess on 2019-08-05:
Please don't use an image to display text/code. Images are not searchable and people cannot copy and paste the text from the image.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

Yes, you can use a template.

template<typename ServiceT>
typename ServiceT::Response::SharedPtr send_request(
  rclcpp::Node::SharedPtr node,
  typename rclcpp::Client<ServiceT>::SharedPtr client,
  typename ServiceT::Request::SharedPtr request)
{
  auto result = client->async_send_request(request);
  // Wait for the result.
  if (rclcpp::spin_until_future_complete(node, result) ==
    rclcpp::executor::FutureReturnCode::SUCCESS)
  {
    return result.get();
  } else {
    return NULL;
  }
}

Then you can call it like this

  using ServiceT1 = ....
  using ServiceT2 = ....

  auto node = rclcpp::Node::make_shared("client_node");
  auto client_1 = node->create_client<ServiceT1>("my_service_1_name");
  auto client_2 = node->create_client<ServiceT2>("my_service_2_name");

  auto request_1 = std::make_shared<ServiceT1::Request>();
  auto result_1 = send_request<ServiceT1>(node, client_1, request_1);

  auto request_2 = std::make_shared<ServiceT2::Request>();
  auto result_2 = send_request<ServiceT2>(node, client_2, request_2);

P.S. In ROS2 this is not the recommended style for creating nodes. You should create a class that extends rclcpp::Node and define the send_request function and the clients as members of this class.


Originally posted by alsora with karma: 1322 on 2019-08-05

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by mikepark93 on 2019-08-05:
When I try building, I get an error saying the following:

error: ‘rclcpp::Client<ServiceT>::SharedPtr’ is not a type rclcpp::Client<ServiceT>::SharedPtr client

Comment by alsora on 2019-08-05:
How have you defined servicet in your code?

Comment by mikepark93 on 2019-08-05:
This was how I defined it before:

rclcpp::Client<orion_sensor::srv::SetFocus>::SharedPtr client

Comment by alsora on 2019-08-05:
So you should use using ServiceT = orion_sensor::srv::SetFocus;. Or you remove this line and you just keep using orion_sensor::srv::SetFocus as before, changing only the send_request function and adding the template parameter when calling it i.e. send_request<orion_sensor::srv::SetFocus>(...)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.