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