ros2_control - iron
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 MessageT msg_;
68
81 template <typename NodeT>
83 NodeT && node, const std::string & topic_name, const rclcpp::QoS & qos,
84 const rclcpp::PublisherOptions & options = rclcpp::PublisherOptions())
85 {
86 initialize([&]() {
87 return rclcpp::create_publisher<MessageT>(
88 std::forward<NodeT>(node), topic_name, qos, options);
89 });
90 }
91
101 explicit RealtimePublisher(PublisherSharedPtr publisher)
102 {
103 initialize([&]() { return publisher; });
104 }
105
106 [[deprecated(
107 "Use constructor with rclcpp::Publisher<T>::SharedPtr instead - this class does not make sense "
108 "without a real publisher")]]
110 : is_running_(false), keep_running_(false), turn_(State::LOOP_NOT_STARTED)
111 {
112 }
113
116 {
117 RCLCPP_DEBUG(rclcpp::get_logger("realtime_tools"), "Waiting for publishing thread to stop....");
118 stop();
119 while (is_running()) {
120 std::this_thread::sleep_for(std::chrono::microseconds(100));
121 }
122 RCLCPP_DEBUG(
123 rclcpp::get_logger("realtime_tools"), "Publishing thread stopped, joining thread....");
124 if (thread_.joinable()) {
125 thread_.join();
126 }
127 }
128
136 void stop()
137 {
138 {
139 std::unique_lock<std::mutex> lock(msg_mutex_);
140 keep_running_ = false;
141 }
142 updated_cond_.notify_one(); // So the publishing loop can exit
143 }
144
153 bool trylock()
154 {
155 return turn_.load(std::memory_order_acquire) == State::REALTIME && msg_mutex_.try_lock();
156 }
157
163 bool can_publish() const
164 {
165 std::unique_lock<std::mutex> lock(msg_mutex_, std::try_to_lock);
166 return can_publish(lock);
167 }
168
178 bool try_publish(const MessageT & msg)
179 {
180 std::unique_lock<std::mutex> lock(msg_mutex_, std::try_to_lock);
181 if (can_publish(lock)) {
182 {
183 std::unique_lock<std::mutex> scoped_lock(std::move(lock));
184 msg_ = msg;
185 turn_.store(State::NON_REALTIME, std::memory_order_release);
186 }
187 updated_cond_.notify_one(); // Notify the publishing thread
188 return true;
189 }
190 return false;
191 }
192
204 [[deprecated(
205 "Use try_publish() method instead of this method. This method may be removed in future "
206 "versions.")]]
207 bool tryPublish(const MessageT & msg)
208 {
209 return try_publish(msg);
210 }
211
220 {
221 turn_.store(State::NON_REALTIME, std::memory_order_release);
222 unlock();
223 }
224
231 void lock() { msg_mutex_.lock(); }
232
237 void unlock()
238 {
239 msg_mutex_.unlock();
240 updated_cond_.notify_one();
241 }
242
243 std::thread & get_thread() { return thread_; }
244
245 const std::thread & get_thread() const { return thread_; }
246
247 const MessageT & get_msg() const { return msg_; }
248
249 std::mutex & get_mutex() { return msg_mutex_; }
250
251 const std::mutex & get_mutex() const { return msg_mutex_; }
252
253private:
254 template <typename PublisherCreator>
255 void initialize(PublisherCreator && creator)
256 {
257 publisher_ = creator();
258 is_running_ = false;
259 keep_running_ = true;
260 turn_ = State::LOOP_NOT_STARTED;
261
262 thread_ = std::thread(&RealtimePublisher::publishingLoop, this);
263
264 // Wait for the thread to be ready before proceeding
265 // This is important to ensure that the thread is properly initialized and ready to handle
266 // messages before any other operations are performed on the RealtimePublisher instance.
267 while (!thread_.joinable() ||
268 turn_.load(std::memory_order_acquire) == State::LOOP_NOT_STARTED) {
269 std::this_thread::sleep_for(std::chrono::microseconds(100));
270 }
271 }
272
279 bool can_publish(std::unique_lock<std::mutex> & lock) const
280 {
281 return turn_.load(std::memory_order_acquire) == State::REALTIME && lock.owns_lock();
282 }
283
284 // non-copyable
285 RealtimePublisher(const RealtimePublisher &) = delete;
286 RealtimePublisher & operator=(const RealtimePublisher &) = delete;
287
288 bool is_running() const { return is_running_; }
289
301 void publishingLoop()
302 {
303 is_running_ = true;
304
305 while (keep_running_) {
306 MessageT outgoing;
307
308 {
309 turn_.store(State::REALTIME, std::memory_order_release);
310 // Locks msg_ and copies it to outgoing
311 std::unique_lock<std::mutex> lock_(msg_mutex_);
312 updated_cond_.wait(lock_, [&] { return turn_ == State::NON_REALTIME || !keep_running_; });
313 outgoing = msg_;
314 }
315
316 // Sends the outgoing message
317 if (keep_running_) {
318 publisher_->publish(outgoing);
319 }
320 }
321 is_running_ = false;
322 }
323
324 PublisherSharedPtr publisher_;
325 std::atomic<bool> is_running_;
326 std::atomic<bool> keep_running_;
327
328 std::thread thread_;
329
330 mutable std::mutex msg_mutex_; // Protects msg_
331 std::condition_variable updated_cond_;
332
333 enum class State : int { REALTIME, NON_REALTIME, LOOP_NOT_STARTED };
334 std::atomic<State> turn_; // Who's turn is it to use msg_?
335};
336
337template <class MessageT>
338using RealtimePublisherSharedPtr = std::shared_ptr<RealtimePublisher<MessageT>>;
339
340} // namespace realtime_tools
341#endif // REALTIME_TOOLS__REALTIME_PUBLISHER_HPP_
Definition realtime_publisher.hpp:56
void stop()
Stop the realtime publisher.
Definition realtime_publisher.hpp:136
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:82
bool try_publish(const MessageT &msg)
Try to publish the given message.
Definition realtime_publisher.hpp:178
RealtimePublisher(PublisherSharedPtr publisher)
Constructor for the realtime publisher.
Definition realtime_publisher.hpp:101
bool tryPublish(const MessageT &msg)
Try to publish the given message (deprecated)
Definition realtime_publisher.hpp:207
bool trylock()
Try to acquire the data lock for non-realtime message publishing.
Definition realtime_publisher.hpp:153
~RealtimePublisher()
Destructor.
Definition realtime_publisher.hpp:115
void unlock()
Unlocks the data without publishing anything.
Definition realtime_publisher.hpp:237
void unlockAndPublish()
Unlock the msg_ variable for the non-realtime thread to start publishing.
Definition realtime_publisher.hpp:219
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:163
void lock()
Acquire the data lock.
Definition realtime_publisher.hpp:231
A pthread mutex wrapper that provides a mutex with the priority inheritance protocol and a priority c...
Definition async_function_handler.hpp:42