scenario_simulator_v2 C++ API
subscriber_wrapper.hpp
Go to the documentation of this file.
1 // Copyright 2015 TIER IV, Inc. All rights reserved.
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 CONCEALER__SUBSCRIBER_WRAPPER_HPP_
16 #define CONCEALER__SUBSCRIBER_WRAPPER_HPP_
17 
18 #include <memory>
19 #include <rclcpp/rclcpp.hpp>
20 
21 namespace concealer
22 {
23 enum class ThreadSafety : bool { unsafe, safe };
24 
25 template <typename MessageType, ThreadSafety thread_safety = ThreadSafety::unsafe>
27 {
28  typename MessageType::ConstSharedPtr current_value = std::make_shared<const MessageType>();
29 
30  typename rclcpp::Subscription<MessageType>::SharedPtr subscription;
31 
32 public:
33  auto operator()() const -> decltype(auto)
34  {
35  if constexpr (thread_safety == ThreadSafety::unsafe) {
36  return *current_value;
37  } else {
38  return *std::atomic_load(&current_value);
39  }
40  }
41 
42  template <typename NodeInterface>
44  const std::string & topic, NodeInterface & autoware_interface,
45  const std::function<void(const MessageType &)> & callback = {})
46  : subscription(autoware_interface.template create_subscription<MessageType>(
47  topic, 1, [this, callback](const typename MessageType::ConstSharedPtr message) {
48  if constexpr (thread_safety == ThreadSafety::safe) {
49  std::atomic_store(&current_value, message);
50  if (current_value and callback) {
51  callback(*std::atomic_load(&current_value));
52  }
53  } else {
54  if (current_value = message; current_value and callback) {
55  callback(*current_value);
56  }
57  }
58  }))
59  {
60  }
61 };
62 } // namespace concealer
63 
64 #endif // CONCEALER__SUBSCRIBER_WRAPPER_HPP_
Definition: subscriber_wrapper.hpp:27
auto operator()() const -> decltype(auto)
Definition: subscriber_wrapper.hpp:33
SubscriberWrapper(const std::string &topic, NodeInterface &autoware_interface, const std::function< void(const MessageType &)> &callback={})
Definition: subscriber_wrapper.hpp:43
Definition: autoware.hpp:30
ThreadSafety
Definition: subscriber_wrapper.hpp:23
std::string string
Definition: junit5.hpp:26