Nav2 Navigation Stack - lyrical  lyrical
ROS 2 Navigation Stack
dummy_service.hpp
1 // Copyright (c) 2020 Sarthak Mittal
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. Reserved.
14 
15 #ifndef BEHAVIOR_TREE__DUMMY_SERVICE_HPP_
16 #define BEHAVIOR_TREE__DUMMY_SERVICE_HPP_
17 
18 #include <memory>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 #include <chrono>
23 
24 #include "rclcpp_action/rclcpp_action.hpp"
25 #include "rclcpp/node.hpp"
26 #include "rclcpp/service.hpp"
27 
28 namespace nav2_system_tests
29 {
30 
31 template<class ServiceT>
33 {
34 public:
35  explicit DummyService(
36  const rclcpp::Node::SharedPtr & node,
37  std::string service_name)
38  : node_(node),
39  service_name_(service_name),
40  request_count_(0),
41  disabled_(false)
42  {
43  service_ = node->create_service<ServiceT>(
44  service_name,
45  std::bind(&DummyService::handle_service, this, _1, _2, _3));
46  }
47 
48  virtual ~DummyService() = default;
49 
50  void disable()
51  {
52  service_.reset();
53  disabled_ = true;
54  }
55 
56  void enable()
57  {
58  if (disabled_) {
59  service_ = node_->create_service<ServiceT>(
60  service_name_,
61  std::bind(&DummyService::handle_service, this, _1, _2, _3));
62  disabled_ = false;
63  }
64  }
65 
66  void reset()
67  {
68  enable();
69  request_count_ = 0;
70  }
71 
72  int getRequestCount() const
73  {
74  return request_count_;
75  }
76 
77 protected:
78  virtual void fillResponse(
79  const std::shared_ptr<typename ServiceT::Request>/*request*/,
80  const std::shared_ptr<typename ServiceT::Response>/*response*/) {}
81 
82  void handle_service(
83  const std::shared_ptr<rmw_request_id_t>/*request_header*/,
84  const std::shared_ptr<typename ServiceT::Request> request,
85  const std::shared_ptr<typename ServiceT::Response> response)
86  {
87  request_count_++;
88  fillResponse(request, response);
89  }
90 
91 private:
92  rclcpp::Node::SharedPtr node_;
93  typename rclcpp::Service<ServiceT>::SharedPtr service_;
94  std::string service_name_;
95  int request_count_;
96  bool disabled_;
97 };
98 
99 } // namespace nav2_system_tests
100 
101 #endif // BEHAVIOR_TREE__DUMMY_SERVICE_HPP_