[ROS2] Correct usage of spin_once to receive multiple callbacks synchronized
Hello everyone,
I can't figure out which is the correct way of using rclpy.spin_once()
to get the output from multiple existing callbacks at once. Right now I'm using a simple while that loops until all callbacks have new values. Simplified code:
def __init__(self):
rclpy.init(args=None)
self.node = rclpy.create_node(self.__class__.__name__)
self.sub1 = self.node.create_subscription( ... obs1)
...
self.sub6 = self.node.create_subscription( ... obs6)
// callbacks
def obs1(self, message):
self.obsJointStates[0] = message.position
...
def obs6(self, message):
self.obsJointStates[5] = message.position
// This is the function that is called constantly in every new step (Reinforcement Learning)
def take_observation(self):
rclpy.spin_once(self.node)
while None in self.obsJointStates:
rclpy.spin_once(self.node)
self.obsJointStates = np.array([None, None, None, None, None, None])
Inside take_observation
function, the while loop waiting for complete callbacks can loop around 100 times currently. I believe there has to be a solution to get fast callbacks and not use this hacky code. Meaning one single call to spin_once()
or whatever it is, should be enough.
Few things I tried with no success:
- Callback group
- Multithread executor
- Use timeout_sec in spin_once
Any idea which is the correct approach?
Thanks in advance,
Nestor