ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

[ROS2] best practice for composable node publishing data from blocking call

asked 2021-03-16 09:02:32 -0500

fhwedel-hoe gravatar image


I am converting a node from ROS1 to ROS2. This node uses a proprietary SDK to connect to a sensor. The function which reads from the sensor performs a blocking call.

This is the code in ROS1:

while (ros::ok()) {
  data =  get_data_from_sensor(); // may block indefinitely or a very short time

For the ROS2 conversion, I want to make use of the composable node architecture. get_data_from_sensor() will likely become a class member function, but how will I call it? When started as a component, ros::spin() is called on the node. As far as I know, no custom entry point exists.

Since the sensor events do not occur on a regular interval, using a timer does not seem feasible. In the node's constructor, I could create and run a thread with a loop like this:

while (rclcpp::ok()) {
  data =  get_data_from_sensor(); // may block indefinitely or a very short time

However, this feels odd. My gut says, I am not adhering to some ROS2 paradigm. Is there a best practice for composable nodes publishing data from blocking calls at variable intervals?

Kind regards

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-03-23 17:56:42 -0500

alsora gravatar image

I don't think that your loop is particularly odd. There are definitely ways to do it differently (i.e. without having to create a new thread), but they will require more code.

What you could do is to pair the get_data_from_sensor with a condition variable that gets notified when new data from the sensor is available. Then you can write a rclcpp::Waitable object that wraps all of this.

The Waitable object is part of a node and it is added to the executor. When the condition variable is notified, the Waitable object will awake a spinning executor, which in turn will invoke the Waitable execute() method, which in your case would result in the publication of the data.

edit flag offensive delete link more


Thank you for the answer. There is an example at which looks interesting, but rather involved. Maybe I will try both variants to see how they perform.

fhwedel-hoe gravatar image fhwedel-hoe  ( 2021-03-24 06:13:55 -0500 )edit

Ahah I wrote that example some time ago and I forgot about it =) That's exactly what I Indented here.

That approach of using Waitable is currently being used without many changes in rclcpp library.

alsora gravatar image alsora  ( 2021-03-24 07:50:43 -0500 )edit

Question Tools

1 follower


Asked: 2021-03-16 09:02:32 -0500

Seen: 369 times

Last updated: Mar 23 '21