|
| 1 | +// Copyright 2016 Open Source Robotics Foundation, 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 <chrono> |
| 16 | +#include <memory> |
| 17 | +#include <string> |
| 18 | + |
| 19 | +#include "rclcpp/rclcpp.hpp" |
| 20 | +#include "std_msgs/msg/string.hpp" |
| 21 | + |
| 22 | +using namespace std::chrono_literals; |
| 23 | + |
| 24 | +/* This example creates a subclass of Node and uses a fancy C++11 lambda |
| 25 | + * function to shorten the callback syntax, at the expense of making the |
| 26 | + * code somewhat more difficult to understand at first glance. */ |
| 27 | + |
| 28 | +class MinimalPublisher : public rclcpp::Node { |
| 29 | + public: |
| 30 | + MinimalPublisher() : Node("minimal_publisher"), count_(0) { |
| 31 | + publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10); |
| 32 | + auto timer_callback = [this]() -> void { |
| 33 | + auto message = std_msgs::msg::String(); |
| 34 | + message.data = "Hello, world! " + std::to_string(this->count_++); |
| 35 | + RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str()); |
| 36 | + this->publisher_->publish(message); |
| 37 | + }; |
| 38 | + timer_ = this->create_wall_timer(500ms, timer_callback); |
| 39 | + } |
| 40 | + |
| 41 | + private: |
| 42 | + rclcpp::TimerBase::SharedPtr timer_; |
| 43 | + rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_; |
| 44 | + size_t count_; |
| 45 | +}; |
| 46 | + |
| 47 | +int main(int argc, char* argv[]) { |
| 48 | + rclcpp::init(argc, argv); |
| 49 | + rclcpp::spin(std::make_shared<MinimalPublisher>()); |
| 50 | + rclcpp::shutdown(); |
| 51 | + return 0; |
| 52 | +} |
0 commit comments