Nav2 Navigation Stack - rolling  main
ROS 2 Navigation Stack
service_server.hpp
1 // Copyright (c) 2025 Maurice Alexander Purnawan
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 NAV2_ROS_COMMON__SERVICE_SERVER_HPP_
16 #define NAV2_ROS_COMMON__SERVICE_SERVER_HPP_
17 
18 #include <string>
19 #include <memory>
20 #include "rclcpp/rclcpp.hpp"
21 #include "rclcpp_lifecycle/lifecycle_node.hpp"
22 #include "nav2_ros_common/node_utils.hpp"
23 
24 namespace nav2
25 {
26 
31 template<class ServiceT>
33 {
34 public:
35  using RequestType = typename ServiceT::Request;
36  using ResponseType = typename ServiceT::Response;
37  using CallbackType = std::function<void(const std::shared_ptr<rmw_request_id_t>,
38  const std::shared_ptr<RequestType>, std::shared_ptr<ResponseType>)>;
39  using SharedPtr = std::shared_ptr<ServiceServer<ServiceT>>;
40  using UniquePtr = std::unique_ptr<ServiceServer<ServiceT>>;
41 
42  template<typename NodeT>
43  explicit ServiceServer(
44  const std::string & service_name,
45  const NodeT & node,
46  CallbackType callback,
47  rclcpp::CallbackGroup::SharedPtr callback_group = nullptr)
48  : service_name_(service_name), callback_(callback)
49  {
50  server_ = rclcpp::create_service<ServiceT>(
51  node->get_node_base_interface(),
52  node->get_node_services_interface(),
53  service_name,
54  [this](const std::shared_ptr<rmw_request_id_t> request_header,
55  const std::shared_ptr<RequestType> request, std::shared_ptr<ResponseType> response) {
56  this->callback_(request_header, request, response);
57  },
58  rclcpp::ServicesQoS(), // Use consistent QoS settings
59  callback_group);
60 
61  nav2::setIntrospectionMode(this->server_,
62  node->get_node_parameters_interface(), node->get_clock());
63  }
64 
65 protected:
66  std::string service_name_;
67  CallbackType callback_;
68  typename rclcpp::Service<ServiceT>::SharedPtr server_;
69 };
70 
71 } // namespace nav2
72 
73 
74 #endif // NAV2_ROS_COMMON__SERVICE_SERVER_HPP_
A simple wrapper on ROS2 services server.