How to receive subscription callbacks while a loop is running?
Software: python, ros2 (foxy)
I have a main loop in my node, and I would also still like to receive updates from a subscription - however, I can't quite figure out how to make it work. I tried to play around with the executor
but that didn't go quite right... Any help or pointers in the right direction would be greatly appreciated.
Simple example, starting with the simple subscriber:
# subscriber
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
String,
'topic',
self.listener_callback,
10)
self.run_loop()
def run_loop(self):
while True:
pass
def listener_callback(self, msg):
self.get_logger().info('I heard: "%s"' % msg.data)
def main(args=None):
rclpy.init(args=args)
minimal_subscriber = MinimalSubscriber()
rclpy.spin(minimal_subscriber)
minimal_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
The publisher:
# publisher
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = 'Hello World: %d' % self.i
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = MinimalPublisher()
rclpy.spin(minimal_publisher)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
What exactly is happening in your main loop? Maybe this can be solved with async callbacks?
Hi thanks for your comment, I know only of async callbacks in javascript -- would like to know more about what you mean.
The loop is running a webcam class which is classifying data...
This topic and the tutorial there: https://discourse.ros.org/t/how-to-us... is really helpful for understanding SingleThreadedExecutors (default) and MultiThreadedExecutors in ROS2