launchros2subscriber

subscriber doesn't receive the topic in case of starting by "ros2 launch"


I'm trying "ros2 launch" command. I encountered the problem for my subscriber node to not receive the specified topic only if started by "ros2 launch" command. The same node works correctly when started by "ros2 run".

my launch file is below:

from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    return LaunchDescription([
        Node(
            package='my_ros2_pkg_w_node',
            namespace='',
            executable='my_node_sub',
            name='my_launch_test_sub'
        ),
    ])

The code for subscriber is below:

import rclpy
from std_msgs.msg import String

def subscriber_node():
    rclpy.init()
    node = rclpy.create_node('subscriber_node')
    subscriber = node.create_subscription(String, '/my_namespace/my_topic', callback, 10)
    rclpy.spin(node)

def callback(msg):
    print('Received: %s' % msg.data)

def main():
    import threading
    thread2 = threading.Thread(target=subscriber_node)
    thread2.start()
    thread2.join()

if __name__ == '__main__':
    main()

Thank you for your cooperation.

BR,


Solution

  • The code has an error of using "print" method and it is the root cause in case that nothing appears on the screen even if subscriber would receive a topic. When it comes to launch ros2 packages by using "ros2 launch", you have to use "node.get_logger().info() to show something, but "print" method.