|
| 1 | +/** |
| 2 | + * @brief Sample application to demonstrate create_timer with use_sim_time support |
| 3 | + * |
| 4 | + * This sample creates a timer using agnocast::Node::create_timer() which supports |
| 5 | + * ROS_TIME (simulation time). When use_sim_time:=true, the timer will use the |
| 6 | + * /clock topic time instead of wall clock time. |
| 7 | + * |
| 8 | + * Usage: |
| 9 | + * # Terminal 1: Run with use_sim_time enabled |
| 10 | + * ros2 run agnocast_sample_application sim_time_timer --ros-args -p use_sim_time:=true |
| 11 | + * |
| 12 | + * # Terminal 2: Publish clock messages |
| 13 | + * ros2 topic pub /clock rosgraph_msgs/msg/Clock "{clock: {sec: 0, nanosec: 0}}" --once |
| 14 | + * ros2 topic pub /clock rosgraph_msgs/msg/Clock "{clock: {sec: 1, nanosec: 0}}" --once |
| 15 | + * ros2 topic pub /clock rosgraph_msgs/msg/Clock "{clock: {sec: 2, nanosec: 0}}" --once |
| 16 | + * |
| 17 | + * # Or run without use_sim_time (uses wall clock) |
| 18 | + * ros2 run agnocast_sample_application sim_time_timer |
| 19 | + */ |
| 20 | + |
| 21 | +#include "agnocast/agnocast.hpp" |
| 22 | + |
| 23 | +#include <chrono> |
| 24 | + |
| 25 | +using namespace std::chrono_literals; |
| 26 | + |
| 27 | +class SimTimeTimerNode : public agnocast::Node |
| 28 | +{ |
| 29 | +public: |
| 30 | + SimTimeTimerNode() : agnocast::Node("sim_time_timer_node") |
| 31 | + { |
| 32 | + // Log whether we're using sim time |
| 33 | + const bool use_sim_time = this->get_parameter("use_sim_time").as_bool(); |
| 34 | + RCLCPP_INFO( |
| 35 | + this->get_logger(), "Starting timer node (use_sim_time: %s)", |
| 36 | + use_sim_time ? "true" : "false"); |
| 37 | + |
| 38 | + // Create timer using create_timer() which supports ROS_TIME |
| 39 | + // This timer will respect use_sim_time parameter |
| 40 | + timer_ = this->create_timer(500ms, std::bind(&SimTimeTimerNode::timer_callback, this)); |
| 41 | + |
| 42 | + RCLCPP_INFO( |
| 43 | + this->get_logger(), "Timer created with period 500ms, clock type: %s", |
| 44 | + timer_->is_steady() ? "STEADY_TIME" : "ROS_TIME"); |
| 45 | + } |
| 46 | + |
| 47 | +private: |
| 48 | + void timer_callback() |
| 49 | + { |
| 50 | + const auto now = this->now(); |
| 51 | + const int64_t sec = now.seconds(); |
| 52 | + const int64_t nsec = now.nanoseconds() % 1000000000; |
| 53 | + |
| 54 | + RCLCPP_INFO( |
| 55 | + this->get_logger(), "Timer callback! Current time: %ld.%09ld (count: %d)", sec, nsec, |
| 56 | + callback_count_++); |
| 57 | + } |
| 58 | + |
| 59 | + agnocast::TimerBase::SharedPtr timer_; |
| 60 | + int callback_count_ = 0; |
| 61 | +}; |
| 62 | + |
| 63 | +int main(int argc, char * argv[]) |
| 64 | +{ |
| 65 | + agnocast::init(argc, argv); |
| 66 | + |
| 67 | + agnocast::AgnocastOnlySingleThreadedExecutor executor; |
| 68 | + auto node = std::make_shared<SimTimeTimerNode>(); |
| 69 | + executor.add_node(node); |
| 70 | + executor.spin(); |
| 71 | + |
| 72 | + return 0; |
| 73 | +} |
0 commit comments