|
| 1 | +// Copyright 2021, Apex.AI Inc. |
| 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 | +#include <rclcpp/rclcpp.hpp> |
| 16 | +#include <std_msgs/msg/string.hpp> |
| 17 | +#include <random> |
| 18 | + |
| 19 | +using namespace std::chrono_literals; |
| 20 | + |
| 21 | +class RandomTalker : public rclcpp::Node |
| 22 | +{ |
| 23 | +public: |
| 24 | + RandomTalker() |
| 25 | + : Node("random_talker"), |
| 26 | + pub1_(this->create_publisher<std_msgs::msg::String>("topicA", 10)), |
| 27 | + pub2_(this->create_publisher<std_msgs::msg::String>("topicB", 10)), |
| 28 | + pub3_(this->create_publisher<std_msgs::msg::String>("topicC", 10)), |
| 29 | + rand_engine_(std::chrono::system_clock::now().time_since_epoch().count()) |
| 30 | + { |
| 31 | + publish_functions_.emplace_back( |
| 32 | + ([this]() { |
| 33 | + std_msgs::msg::String msg; |
| 34 | + msg.data = "A"; |
| 35 | + RCLCPP_INFO(this->get_logger(), "Publishing: %s", msg.data.c_str()); |
| 36 | + pub1_->publish(msg); |
| 37 | + })); |
| 38 | + publish_functions_.emplace_back( |
| 39 | + ([this]() { |
| 40 | + std_msgs::msg::String msg; |
| 41 | + msg.data = "B"; |
| 42 | + RCLCPP_INFO(this->get_logger(), "Publishing: %s", msg.data.c_str()); |
| 43 | + pub2_->publish(msg); |
| 44 | + })); |
| 45 | + publish_functions_.emplace_back( |
| 46 | + ([this]() { |
| 47 | + std_msgs::msg::String msg; |
| 48 | + msg.data = "C"; |
| 49 | + RCLCPP_INFO(this->get_logger(), "Publishing: %s", msg.data.c_str()); |
| 50 | + pub3_->publish(msg); |
| 51 | + })); |
| 52 | + auto timer_callback = |
| 53 | + [this]() -> void { |
| 54 | + std::shuffle(publish_functions_.begin(), publish_functions_.end(), rand_engine_); |
| 55 | + for (const auto & f : publish_functions_) {f();} |
| 56 | + }; |
| 57 | + timer_ = this->create_wall_timer(1s, timer_callback); |
| 58 | + } |
| 59 | + |
| 60 | +private: |
| 61 | + rclcpp::TimerBase::SharedPtr timer_; |
| 62 | + rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub1_; |
| 63 | + rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub2_; |
| 64 | + rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub3_; |
| 65 | + std::vector<std::function<void()>> publish_functions_; |
| 66 | + std::default_random_engine rand_engine_; |
| 67 | +}; |
0 commit comments