ROS 2 rclcpp + rcl - lyrical  lyrical
ROS 2 C++ Client Library with ROS Client Library
service.hpp
1 // Copyright 2014 Open Source Robotics Foundation, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef RCLCPP__SERVICE_HPP_
16 #define RCLCPP__SERVICE_HPP_
17 
18 #include <atomic>
19 #include <functional>
20 #include <iostream>
21 #include <memory>
22 #include <mutex>
23 #include <sstream>
24 #include <string>
25 #include <utility>
26 
27 #include "rcl/error_handling.h"
28 #include "rcl/event_callback.h"
29 #include "rcl/service.h"
30 #include "rcl/service_introspection.h"
31 
32 #include "rmw/error_handling.h"
33 #include "rmw/impl/cpp/demangle.hpp"
34 #include "rmw/rmw.h"
35 
36 #include "tracetools/tracetools.h"
37 
38 #include "rclcpp/any_service_callback.hpp"
39 #include "rclcpp/clock.hpp"
40 #include "rclcpp/detail/cpp_callback_trampoline.hpp"
41 #include "rclcpp/exceptions.hpp"
42 #include "rclcpp/expand_topic_or_service_name.hpp"
43 #include "rclcpp/logging.hpp"
44 #include "rclcpp/macros.hpp"
45 #include "rclcpp/qos.hpp"
46 #include "rclcpp/type_support_decl.hpp"
47 #include "rclcpp/visibility_control.hpp"
48 
49 namespace rclcpp
50 {
51 
53 {
54 public:
55  RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(ServiceBase)
56 
57  RCLCPP_PUBLIC
58  explicit ServiceBase(const std::shared_ptr<rcl_node_t> & node_handle);
59 
60  RCLCPP_PUBLIC
61  virtual ~ServiceBase() = default;
62 
64 
65  RCLCPP_PUBLIC
66  const char *
68 
70 
74  RCLCPP_PUBLIC
75  std::shared_ptr<rcl_service_t>
77 
79 
83  RCLCPP_PUBLIC
84  std::shared_ptr<const rcl_service_t>
85  get_service_handle() const;
86 
88 
102  RCLCPP_PUBLIC
103  bool
104  take_type_erased_request(void * request_out, rmw_request_id_t & request_id_out);
105 
106  virtual
107  std::shared_ptr<void>
108  create_request() = 0;
109 
110  virtual
111  std::shared_ptr<rmw_request_id_t>
112  create_request_header() = 0;
113 
114  virtual
115  void
116  handle_request(
117  const std::shared_ptr<rmw_request_id_t> & request_header,
118  const std::shared_ptr<void> & request) = 0;
119 
121 
130  RCLCPP_PUBLIC
131  bool
132  exchange_in_use_by_wait_set_state(bool in_use_state);
133 
135 
146  RCLCPP_PUBLIC
149 
151 
162  RCLCPP_PUBLIC
165 
167 
193  void
194  set_on_new_request_callback(const std::function<void(size_t)> & callback)
195  {
196  if (!callback) {
197  throw std::invalid_argument(
198  "The callback passed to set_on_new_request_callback "
199  "is not callable.");
200  }
201 
202  auto new_callback =
203  [callback, this](size_t number_of_requests) {
204  try {
205  callback(number_of_requests);
206  } catch (const std::exception & exception) {
207  RCLCPP_ERROR_STREAM(
208  node_logger_,
209  "rclcpp::ServiceBase@" << this <<
210  " caught " << rmw::impl::cpp::demangle(exception) <<
211  " exception in user-provided callback for the 'on new request' callback: " <<
212  exception.what());
213  } catch (...) {
214  RCLCPP_ERROR_STREAM(
215  node_logger_,
216  "rclcpp::ServiceBase@" << this <<
217  " caught unhandled exception in user-provided callback " <<
218  "for the 'on new request' callback");
219  }
220  };
221 
222  std::lock_guard<std::recursive_mutex> lock(callback_mutex_);
223 
224  // Set it temporarily to the new callback, while we replace the old one.
225  // This two-step setting, prevents a gap where the old std::function has
226  // been replaced but the middleware hasn't been told about the new one yet.
228  rclcpp::detail::cpp_callback_trampoline<decltype(new_callback), const void *, size_t>,
229  static_cast<const void *>(&new_callback));
230 
231  // Store the std::function to keep it in scope, also overwrites the existing one.
232  on_new_request_callback_ = new_callback;
233 
234  // Set it again, now using the permanent storage.
236  rclcpp::detail::cpp_callback_trampoline<
237  decltype(on_new_request_callback_), const void *, size_t>,
238  static_cast<const void *>(&on_new_request_callback_));
239  }
240 
242  void
244  {
245  std::lock_guard<std::recursive_mutex> lock(callback_mutex_);
246  if (on_new_request_callback_) {
247  set_on_new_request_callback(nullptr, nullptr);
248  on_new_request_callback_ = nullptr;
249  }
250  }
251 
252 protected:
253  RCLCPP_DISABLE_COPY(ServiceBase)
254 
255  RCLCPP_PUBLIC
256  rcl_node_t *
257  get_rcl_node_handle();
258 
259  RCLCPP_PUBLIC
260  const rcl_node_t *
261  get_rcl_node_handle() const;
262 
263  RCLCPP_PUBLIC
264  void
265  set_on_new_request_callback(rcl_event_callback_t callback, const void * user_data);
266 
267  std::shared_ptr<rcl_node_t> node_handle_;
268 
269  std::recursive_mutex callback_mutex_;
270  // It is important to declare on_new_request_callback_ before
271  // service_handle_, so on destruction the service is
272  // destroyed first. Otherwise, the rmw service callback
273  // would point briefly to a destroyed function.
274  std::function<void(size_t)> on_new_request_callback_{nullptr};
275  // Declare service_handle_ after callback
276  std::shared_ptr<rcl_service_t> service_handle_;
277  bool owns_rcl_handle_ = true;
278 
279  rclcpp::Logger node_logger_;
280 
281  std::atomic<bool> in_use_by_wait_set_{false};
282 };
283 
284 template<typename ServiceT>
285 class Service
286  : public ServiceBase,
287  public std::enable_shared_from_this<Service<ServiceT>>
288 {
289 public:
290  using ServiceType = ServiceT;
291  using CallbackType = std::function<
292  void (
293  const std::shared_ptr<typename ServiceT::Request>,
294  std::shared_ptr<typename ServiceT::Response>)>;
295 
296  using CallbackWithHeaderType = std::function<
297  void (
298  const std::shared_ptr<rmw_request_id_t>,
299  const std::shared_ptr<typename ServiceT::Request>,
300  std::shared_ptr<typename ServiceT::Response>)>;
301  RCLCPP_SMART_PTR_DEFINITIONS(Service)
302 
303 
315  std::shared_ptr<rcl_node_t> node_handle,
316  const std::string & service_name,
317  AnyServiceCallback<ServiceT> any_callback,
318  rcl_service_options_t & service_options)
319  : ServiceBase(node_handle), any_callback_(any_callback),
320  srv_type_support_handle_(rosidl_typesupport_cpp::get_service_type_support_handle<ServiceT>())
321  {
322  // rcl does the static memory allocation here
323  service_handle_ = std::shared_ptr<rcl_service_t>(
324  new rcl_service_t, [handle = node_handle_, service_name](rcl_service_t * service)
325  {
326  if (rcl_service_fini(service, handle.get()) != RCL_RET_OK) {
327  RCLCPP_ERROR(
328  rclcpp::get_node_logger(handle.get()).get_child("rclcpp"),
329  "Error in destruction of rcl service handle: %s",
330  rcl_get_error_string().str);
331  rcl_reset_error();
332  }
333  delete service;
334  });
335  *service_handle_.get() = rcl_get_zero_initialized_service();
336 
338  service_handle_.get(),
339  node_handle.get(),
340  srv_type_support_handle_,
341  service_name.c_str(),
342  &service_options);
343  if (ret != RCL_RET_OK) {
344  if (ret == RCL_RET_SERVICE_NAME_INVALID) {
345  auto rcl_node_handle = get_rcl_node_handle();
346  // this will throw on any validation problem
347  rcl_reset_error();
349  service_name,
350  rcl_node_get_name(rcl_node_handle),
351  rcl_node_get_namespace(rcl_node_handle),
352  true);
353  }
354 
355  rclcpp::exceptions::throw_from_rcl_error(ret, "could not create service");
356  }
357  TRACETOOLS_TRACEPOINT(
358  rclcpp_service_callback_added,
359  static_cast<const void *>(get_service_handle().get()),
360  static_cast<const void *>(&any_callback_));
361 #ifndef TRACETOOLS_DISABLED
362  any_callback_.register_callback_for_tracing();
363 #endif
364  }
365 
367 
377  const std::shared_ptr<rcl_node_t> & node_handle,
378  const std::shared_ptr<rcl_service_t> & service_handle,
379  AnyServiceCallback<ServiceT> any_callback)
380  : ServiceBase(node_handle), any_callback_(std::move(any_callback)),
381  srv_type_support_handle_(rosidl_typesupport_cpp::get_service_type_support_handle<ServiceT>())
382  {
383  // check if service handle was initialized
384  if (!rcl_service_is_valid(service_handle.get())) {
385  // *INDENT-OFF* (prevent uncrustify from making unnecessary indents here)
386  throw std::runtime_error(
387  std::string("rcl_service_t in constructor argument must be initialized beforehand."));
388  // *INDENT-ON*
389  }
390 
391  service_handle_ = service_handle;
392  TRACETOOLS_TRACEPOINT(
393  rclcpp_service_callback_added,
394  static_cast<const void *>(get_service_handle().get()),
395  static_cast<const void *>(&any_callback_));
396 #ifndef TRACETOOLS_DISABLED
397  any_callback_.register_callback_for_tracing();
398 #endif
399  }
400 
402 
412  const std::shared_ptr<rcl_node_t> & node_handle,
413  rcl_service_t * service_handle,
414  AnyServiceCallback<ServiceT> any_callback)
415  : ServiceBase(node_handle), any_callback_(std::move(any_callback)),
416  srv_type_support_handle_(rosidl_typesupport_cpp::get_service_type_support_handle<ServiceT>())
417  {
418  // check if service handle was initialized
419  if (!rcl_service_is_valid(service_handle)) {
420  // *INDENT-OFF* (prevent uncrustify from making unnecessary indents here)
421  throw std::runtime_error(
422  std::string("rcl_service_t in constructor argument must be initialized beforehand."));
423  // *INDENT-ON*
424  }
425 
426  // In this case, rcl owns the service handle memory
427  service_handle_ = std::shared_ptr<rcl_service_t>(new rcl_service_t);
428  service_handle_->impl = service_handle->impl;
429  TRACETOOLS_TRACEPOINT(
430  rclcpp_service_callback_added,
431  static_cast<const void *>(get_service_handle().get()),
432  static_cast<const void *>(&any_callback_));
433 #ifndef TRACETOOLS_DISABLED
434  any_callback_.register_callback_for_tracing();
435 #endif
436  }
437 
438  Service() = delete;
439 
440  virtual ~Service()
441  {
442  }
443 
445 
456  bool
457  take_request(typename ServiceT::Request & request_out, rmw_request_id_t & request_id_out)
458  {
459  return this->take_type_erased_request(&request_out, request_id_out);
460  }
461 
462  std::shared_ptr<void>
463  create_request() override
464  {
465  return std::make_shared<typename ServiceT::Request>();
466  }
467 
468  std::shared_ptr<rmw_request_id_t>
469  create_request_header() override
470  {
471  return std::make_shared<rmw_request_id_t>();
472  }
473 
474  void
475  handle_request(
476  const std::shared_ptr<rmw_request_id_t> & request_header,
477  const std::shared_ptr<void> & request) override
478  {
479  auto typed_request = std::static_pointer_cast<typename ServiceT::Request>(request);
480  auto response = any_callback_.dispatch(this->shared_from_this(), request_header, typed_request);
481  if (response) {
482  send_response(*request_header, *response);
483  }
484  }
485 
486  void
487  send_response(rmw_request_id_t & req_id, typename ServiceT::Response & response)
488  {
489  rcl_ret_t ret = rcl_send_response(get_service_handle().get(), &req_id, &response);
490 
491  if (ret == RCL_RET_TIMEOUT) {
492  RCLCPP_WARN(
493  node_logger_.get_child("rclcpp"),
494  "failed to send response to %s (timeout): %s",
495  this->get_service_name(), rcl_get_error_string().str);
496  rcl_reset_error();
497  return;
498  }
499  if (ret != RCL_RET_OK) {
500  rclcpp::exceptions::throw_from_rcl_error(ret, "failed to send response");
501  }
502  }
503 
505 
513  void
515  const Clock::SharedPtr & clock, const QoS & qos_service_event_pub,
516  rcl_service_introspection_state_t introspection_state)
517  {
519  pub_opts.qos = qos_service_event_pub.get_rmw_qos_profile();
520 
522  service_handle_.get(),
523  node_handle_.get(),
524  clock->get_clock_handle(),
525  srv_type_support_handle_,
526  pub_opts,
527  introspection_state);
528 
529  if (RCL_RET_OK != ret) {
530  rclcpp::exceptions::throw_from_rcl_error(ret, "failed to configure service introspection");
531  }
532  }
533 
534 private:
535  RCLCPP_DISABLE_COPY(Service)
536 
537  AnyServiceCallback<ServiceT> any_callback_;
538 
539  const rosidl_service_type_support_t * srv_type_support_handle_;
540 };
541 
542 } // namespace rclcpp
543 
544 #endif // RCLCPP__SERVICE_HPP_
RCLCPP_PUBLIC Logger get_child(const std::string &suffix)
Return a logger that is a descendant of this logger.
Definition: logger.cpp:73
Encapsulation of Quality of Service settings.
Definition: qos.hpp:116
rmw_qos_profile_t & get_rmw_qos_profile()
Return the rmw qos profile.
Definition: qos.cpp:108
RCLCPP_PUBLIC bool exchange_in_use_by_wait_set_state(bool in_use_state)
Exchange the "in use by wait set" state for this service.
Definition: service.cpp:83
RCLCPP_PUBLIC rclcpp::QoS get_request_subscription_actual_qos() const
Get the actual request subscription QoS settings, after the defaults have been determined.
Definition: service.cpp:108
RCLCPP_PUBLIC rclcpp::QoS get_response_publisher_actual_qos() const
Get the actual response publisher QoS settings, after the defaults have been determined.
Definition: service.cpp:89
void clear_on_new_request_callback()
Unset the callback registered for new requests, if any.
Definition: service.hpp:243
RCLCPP_PUBLIC std::shared_ptr< rcl_service_t > get_service_handle()
Return the rcl_service_t service handle in a std::shared_ptr.
Definition: service.cpp:59
RCLCPP_PUBLIC bool take_type_erased_request(void *request_out, rmw_request_id_t &request_id_out)
Take the next request from the service as a type erased pointer.
Definition: service.cpp:38
void set_on_new_request_callback(const std::function< void(size_t)> &callback)
Set a callback to be called when each new request is received.
Definition: service.hpp:194
RCLCPP_PUBLIC const char * get_service_name()
Return the name of the service.
Definition: service.cpp:53
bool take_request(typename ServiceT::Request &request_out, rmw_request_id_t &request_id_out)
Take the next request from the service.
Definition: service.hpp:457
Service(const std::shared_ptr< rcl_node_t > &node_handle, rcl_service_t *service_handle, AnyServiceCallback< ServiceT > any_callback)
Default constructor.
Definition: service.hpp:411
Service(const std::shared_ptr< rcl_node_t > &node_handle, const std::shared_ptr< rcl_service_t > &service_handle, AnyServiceCallback< ServiceT > any_callback)
Default constructor.
Definition: service.hpp:376
void configure_introspection(const Clock::SharedPtr &clock, const QoS &qos_service_event_pub, rcl_service_introspection_state_t introspection_state)
Configure service introspection.
Definition: service.hpp:514
Versions of rosidl_typesupport_cpp::get_message_type_support_handle that handle adapted types.
RCLCPP_PUBLIC std::string expand_topic_or_service_name(const std::string &name, const std::string &node_name, const std::string &namespace_, bool is_service=false)
Expand a topic or service name and throw if it is not valid.
RCL_PUBLIC RCL_WARN_UNUSED const char * rcl_node_get_name(const rcl_node_t *node)
Return the name of the node.
Definition: node.c:416
RCL_PUBLIC RCL_WARN_UNUSED const char * rcl_node_get_namespace(const rcl_node_t *node)
Return the namespace of the node.
Definition: node.c:425
RCL_PUBLIC RCL_WARN_UNUSED rcl_publisher_options_t rcl_publisher_get_default_options(void)
Return the default publisher options in a rcl_publisher_options_t.
Definition: publisher.c:220
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_service_init(rcl_service_t *service, const rcl_node_t *node, const rosidl_service_type_support_t *type_support, const char *service_name, const rcl_service_options_t *options)
Initialize a rcl service.
Definition: service.c:76
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_service_configure_service_introspection(rcl_service_t *service, rcl_node_t *node, rcl_clock_t *clock, const rosidl_service_type_support_t *type_support, const rcl_publisher_options_t publisher_options, rcl_service_introspection_state_t introspection_state)
Configure service introspection features for the service.
Definition: service.c:462
RCL_PUBLIC bool rcl_service_is_valid(const rcl_service_t *service)
Check that the service is valid.
Definition: service.c:416
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_service_fini(rcl_service_t *service, rcl_node_t *node)
Finalize a rcl_service_t.
Definition: service.c:225
RCL_PUBLIC RCL_WARN_UNUSED rcl_service_t rcl_get_zero_initialized_service(void)
Return a rcl_service_t struct with members set to NULL.
Definition: service.c:45
RCL_PUBLIC RCL_WARN_UNUSED rcl_ret_t rcl_send_response(const rcl_service_t *service, rmw_request_id_t *response_header, void *ros_response)
Send a ROS response to a client using a service.
Definition: service.c:375
Structure which encapsulates a ROS Node.
Definition: node.h:45
Options available for a rcl publisher.
Definition: publisher.h:44
rmw_qos_profile_t qos
Middleware quality of service settings for the publisher.
Definition: publisher.h:46
Options available for a rcl service.
Definition: service.h:50
Structure which encapsulates a ROS Service.
Definition: service.h:43
rcl_service_impl_t * impl
Pointer to the service implementation.
Definition: service.h:45
#define RCL_RET_SERVICE_NAME_INVALID
Service name (same as topic name) does not pass validation.
Definition: types.h:49
#define RCL_RET_OK
Success return code.
Definition: types.h:27
#define RCL_RET_TIMEOUT
Timeout occurred return code.
Definition: types.h:31
rmw_ret_t rcl_ret_t
The type that holds an rcl return code.
Definition: types.h:24