본문 바로가기
ros2_python/Ros2 msg,srv,action,parm

ros2 topic spin 중에 등록해도 동작할까

by 알 수 없는 사용자 2023. 8. 28.

 

 

결론 : ㅇㅋ 됨

 

터미널 3개 띄우고

python ros2_sub_test.py

ros2 topic pub /test_1 std_msgs/msg/String data:\ \'\'\

ros2 topic pub /test_2 std_msgs/msg/String data:\ \'\'\

각각 킨 후, python ros2_sub_test.py 내부에선

spin 은 쓰레딩으로 돌리고 /test_1 토픽 등록 --> 5초후 /test_2 토픽 등록

 

5초후 둘다 받음


테스트 예제

 

import rclpy
from rclpy.node import Node

from std_msgs.msg import String

import time
import threading


class MinimalSubscriber():

    def __init__(self):
        self.node_obj:Node = rclpy.create_node('test_node')
        self.node_obj.create_subscription(
            String,
            '/test_1',
            self.listener_callback,
            10)

    def listener_callback(self, msg):
        self.node_obj.get_logger().warning('test_1 ! : "%s"' % msg.data)

    def get_node(self):
        return self.node_obj


def main(args=None):
    rclpy.init(args=args)

    def listener_callback(msg):
        node_obj.get_logger().error(f'test_2 ! : {msg}')

    minimal_subscriber = MinimalSubscriber()

    node_obj = minimal_subscriber.get_node()
    _executor = rclpy.executors.MultiThreadedExecutor()
    _executor.add_node(node_obj)
    _executor_thread = threading.Thread(target=_executor.spin, daemon=True)
    _executor_thread.start()

    # rclpy.spin(minimal_subscriber)

    i = 0
    while True:
        i += 1
        time.sleep(1)
        if i == 5:
            print(f"새로운 SUB 등록")
            node_obj.create_subscription(
                String,
                '/test_2',
                listener_callback,
                10
            )
            print(f"새로운 SUB 등록 완료")

        print(f"node_obj {i}")

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    node_obj.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

 

출력값 : 

댓글