ros2_control - rolling
Loading...
Searching...
No Matches
realtime_publisher.hpp
1// Copyright (c) 2008, Willow Garage, Inc.
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8//
9// * Redistributions in binary form must reproduce the above copyright
10// notice, this list of conditions and the following disclaimer in the
11// documentation and/or other materials provided with the distribution.
12//
13// * Neither the name of the Willow Garage, Inc. nor the names of its
14// contributors may be used to endorse or promote products derived from
15// this software without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28
29/*
30 * Publishing ROS messages is difficult, as the publish function is
31 * not realtime safe. This class provides the proper locking so that
32 * you can call publish in realtime and a separate (non-realtime)
33 * thread will ensure that the message gets published over ROS.
34 *
35 * Author: Stuart Glaser
36 */
37#ifndef REALTIME_TOOLS__REALTIME_PUBLISHER_HPP_
38#define REALTIME_TOOLS__REALTIME_PUBLISHER_HPP_
39
40#include <atomic>
41#include <chrono>
42#include <condition_variable>
43#include <memory>
44#include <mutex>
45#include <string>
46#include <thread>
47#include <utility>
48
49#include "rclcpp/create_publisher.hpp"
50#include "rclcpp/publisher.hpp"
51
52namespace realtime_tools
53{
54template <class MessageT>
56{
57public:
59 using PublisherType = rclcpp::Publisher<MessageT>;
60 using PublisherSharedPtr = typename rclcpp::Publisher<MessageT>::SharedPtr;
61
62 using PublishedType = typename rclcpp::TypeAdapter<MessageT>::custom_type;
63 using ROSMessageType = typename rclcpp::TypeAdapter<MessageT>::ros_message_type;
64
65 RCLCPP_SMART_PTR_DEFINITIONS(RealtimePublisher<MessageT>)
66
67
79 template <typename NodeT>
81 NodeT && node, const std::string & topic_name, const rclcpp::QoS & qos,
82 const rclcpp::PublisherOptions & options = rclcpp::PublisherOptions())
83 {
84 initialize([&]() {
85 return rclcpp::create_publisher<MessageT>(
86 std::forward<NodeT>(node), topic_name, qos, options);
87 });
88 }
89
99 [[deprecated("Use the constructor that creates the publisher internally instead.")]]
100 explicit RealtimePublisher(PublisherSharedPtr publisher)
101 {
102 initialize([&]() { return publisher; });
103 }
104
107 {
108 RCLCPP_DEBUG(rclcpp::get_logger("realtime_tools"), "Waiting for publishing thread to stop....");
109 stop();
110 while (is_running()) {
111 std::this_thread::sleep_for(std::chrono::microseconds(100));
112 }
113 RCLCPP_DEBUG(
114 rclcpp::get_logger("realtime_tools"), "Publishing thread stopped, joining thread....");
115 if (thread_.joinable()) {
116 thread_.join();
117 }
118 }
119
127 void stop()
128 {
129 {
130 std::unique_lock<std::mutex> lock(msg_mutex_);
131 keep_running_ = false;
132 }
133 updated_cond_.notify_one(); // So the publishing loop can exit
134 }
135
140 bool can_publish() const
141 {
142 std::unique_lock<std::mutex> lock(msg_mutex_, std::try_to_lock);
143 return can_publish(lock);
144 }
145
155 bool try_publish(const MessageT & msg)
156 {
157 std::unique_lock<std::mutex> lock(msg_mutex_, std::try_to_lock);
158 if (can_publish(lock)) {
159 {
160 std::unique_lock<std::mutex> scoped_lock(std::move(lock));
161 msg_ = msg;
162 turn_.store(State::NON_REALTIME, std::memory_order_release);
163 }
164 updated_cond_.notify_one(); // Notify the publishing thread
165 return true;
166 }
167 return false;
168 }
169
175 std::thread & get_thread() { return thread_; }
176
182 const std::thread & get_thread() const { return thread_; }
183
187 std::mutex & get_mutex() { return msg_mutex_; }
188
192 const std::mutex & get_mutex() const { return msg_mutex_; }
193
194private:
195 template <typename PublisherCreator>
196 void initialize(PublisherCreator && creator)
197 {
198 publisher_ = creator();
199 is_running_ = false;
200 keep_running_ = true;
201 turn_ = State::LOOP_NOT_STARTED;
202
203 thread_ = std::thread(&RealtimePublisher::publishingLoop, this);
204
205 // Wait for the thread to be ready before proceeding
206 // This is important to ensure that the thread is properly initialized and ready to handle
207 // messages before any other operations are performed on the RealtimePublisher instance.
208 while (!thread_.joinable() ||
209 turn_.load(std::memory_order_acquire) == State::LOOP_NOT_STARTED) {
210 std::this_thread::sleep_for(std::chrono::microseconds(100));
211 }
212 }
213
219 bool can_publish(std::unique_lock<std::mutex> & lock) const
220 {
221 return turn_.load(std::memory_order_acquire) == State::REALTIME && lock.owns_lock();
222 }
223
224 // non-copyable
225 RealtimePublisher(const RealtimePublisher &) = delete;
226 RealtimePublisher & operator=(const RealtimePublisher &) = delete;
227
228 bool is_running() const { return is_running_; }
229
241 void publishingLoop()
242 {
243 is_running_ = true;
244
245 while (keep_running_) {
246 MessageT outgoing;
247
248 {
249 turn_.store(State::REALTIME, std::memory_order_release);
250 // Locks msg_ and copies it to outgoing
251 std::unique_lock<std::mutex> lock_(msg_mutex_);
252 updated_cond_.wait(lock_, [&] { return turn_ == State::NON_REALTIME || !keep_running_; });
253 outgoing = msg_;
254 }
255
256 // Sends the outgoing message
257 if (keep_running_) {
258 publisher_->publish(outgoing);
259 }
260 }
261 is_running_ = false;
262 }
263
264 PublisherSharedPtr publisher_;
265 std::atomic<bool> is_running_;
266 std::atomic<bool> keep_running_;
267
268 std::thread thread_;
269
270 MessageT msg_;
271
272 mutable std::mutex msg_mutex_; // Protects msg_
273 std::condition_variable updated_cond_;
274
275 enum class State : int { REALTIME, NON_REALTIME, LOOP_NOT_STARTED };
276 std::atomic<State> turn_; // Who's turn is it to use msg_?
277};
278
279template <class MessageT>
280using RealtimePublisherSharedPtr = std::shared_ptr<RealtimePublisher<MessageT>>;
281
282} // namespace realtime_tools
283#endif // REALTIME_TOOLS__REALTIME_PUBLISHER_HPP_
Definition realtime_publisher.hpp:56
std::mutex & get_mutex()
Get the mutex protecting the stored message.
Definition realtime_publisher.hpp:187
void stop()
Stop the realtime publisher.
Definition realtime_publisher.hpp:127
RealtimePublisher(NodeT &&node, const std::string &topic_name, const rclcpp::QoS &qos, const rclcpp::PublisherOptions &options=rclcpp::PublisherOptions())
Constructor for the realtime publisher that creates the publisher internally.
Definition realtime_publisher.hpp:80
bool try_publish(const MessageT &msg)
Try to publish the given message.
Definition realtime_publisher.hpp:155
RealtimePublisher(PublisherSharedPtr publisher)
Constructor for the realtime publisher.
Definition realtime_publisher.hpp:100
std::thread & get_thread()
Get the thread object for the publishing thread.
Definition realtime_publisher.hpp:175
~RealtimePublisher()
Destructor.
Definition realtime_publisher.hpp:106
rclcpp::Publisher< MessageT > PublisherType
Provide various typedefs to resemble the rclcpp::Publisher type.
Definition realtime_publisher.hpp:59
bool can_publish() const
Check if the realtime publisher is in a state to publish messages.
Definition realtime_publisher.hpp:140
const std::mutex & get_mutex() const
Get the mutex protecting the stored message.
Definition realtime_publisher.hpp:192
const std::thread & get_thread() const
Get the thread object for the publishing thread.
Definition realtime_publisher.hpp:182
A pthread mutex wrapper that provides a mutex with the priority inheritance protocol and a priority c...
Definition async_function_handler.hpp:42