This ROS2 package contains some example C++ applications which demonstrate
how to listen for various events generated by an rclcpp::Node
object.
events_listener.cpp shows how to register
callbacks on rclcpp::Publisher
and rclcpp:Subscription
objects to receive
notification of DDS-level events which are exposed by the rclcpp
layer.
Each callback must be specified through the options data-structures (
rclcpp::PublisherOptions
, and rclcpp::SubscriptionOptions
) when creating
the endpoints.
The example uses a custom helper "listener class" to demonstrate how to tie this events with any custom C++ object. See node_listener.hpp.
In order to receive these notification the Node
and its endpoints must be
attached to a spinning executor.
graph_listener.cpp shows how to receive notification of changes to the "graph" database maintained by each Node.
This is achieved by using the rclcpp::Event
interface along with various
functions exposed by rclcpp::Node
.
Contrary to other ROS2 events (data receival, publisher/subscription events,
timers, etc...), "graph changed" events cannot be dispatched by an executor,
and they thus require the application to spawn a thread to call
rclcpp::Node::wait_for_graph_change()
in parallel to a spinning executor.
-
Clone (or symlink) repository in a new workspace:
mkdir ws-node_listener cd ws-node_listener git clone https://github.com/asorbini/ros2_node_listener
-
Load ROS2 Galactic, build the examples, and load them:
source /opt/ros/galactic/setup.bash colcon build --symlink-install source install/setup.bash
-
(Optional) Make sure to use RTI Connext DDS:
export RMW_IMPLEMENTATION=rmw_connextdds
-
Run
events_listener
example:ros2 run node_listener events_listener # Use ^C to terminate
-
Run
graph_listener
example:# Start listener in backgroun ros2 run node_listener graph_listener & # Generate some "graph changes" with `ros2 topic pub` ros2 topic pub "chatter" example_interfaces/msg/String # Use ^C to terminate the publisher (more changes will print) # Terminate listener fg # then ^C