Esempio n. 1
0
    def test_publisher_constructor(self):
        callbacks = PublisherEventCallbacks()
        liveliness_callback = Mock()
        deadline_callback = Mock()

        # No arg
        publisher = self.node.create_publisher(EmptyMsg, 'test_topic', 10)
        self.assertEqual(len(publisher.event_handlers), 0)
        self.node.destroy_publisher(publisher)

        # Arg with no callbacks
        publisher = self.node.create_publisher(
            EmptyMsg, 'test_topic', 10, event_callbacks=callbacks)
        self.assertEqual(len(publisher.event_handlers), 0)
        self.node.destroy_publisher(publisher)

        # Arg with one of the callbacks
        callbacks.deadline = deadline_callback
        publisher = self.node.create_publisher(
            EmptyMsg, 'test_topic', 10, event_callbacks=callbacks)
        self.assertEqual(len(publisher.event_handlers), 1)
        self.node.destroy_publisher(publisher)

        # Arg with both callbacks
        callbacks.liveliness = liveliness_callback
        publisher = self.node.create_publisher(
            EmptyMsg, 'test_topic', 10, event_callbacks=callbacks)
        self.assertEqual(len(publisher.event_handlers), 2)
        self.node.destroy_publisher(publisher)
Esempio n. 2
0
    def test_publisher_constructor(self):
        callbacks = PublisherEventCallbacks()
        liveliness_callback = Mock()
        deadline_callback = Mock()
        incompatible_qos_callback = Mock()
        expected_num_event_handlers = 0 if self.is_fastrtps else 1

        # No arg
        publisher = self.node.create_publisher(EmptyMsg, self.topic_name, 10)
        self.assertEqual(len(publisher.event_handlers),
                         expected_num_event_handlers)
        self.node.destroy_publisher(publisher)

        # Arg with no callbacks
        publisher = self.node.create_publisher(EmptyMsg,
                                               self.topic_name,
                                               10,
                                               event_callbacks=callbacks)
        self.assertEqual(len(publisher.event_handlers),
                         expected_num_event_handlers)
        self.node.destroy_publisher(publisher)

        # Arg with one of the callbacks
        callbacks.deadline = deadline_callback
        expected_num_event_handlers += 1
        publisher = self.node.create_publisher(EmptyMsg,
                                               self.topic_name,
                                               10,
                                               event_callbacks=callbacks)
        self.assertEqual(len(publisher.event_handlers),
                         expected_num_event_handlers)
        self.node.destroy_publisher(publisher)

        # Arg with two callbacks
        callbacks.liveliness = liveliness_callback
        expected_num_event_handlers += 1
        publisher = self.node.create_publisher(EmptyMsg,
                                               self.topic_name,
                                               10,
                                               event_callbacks=callbacks)
        self.assertEqual(len(publisher.event_handlers),
                         expected_num_event_handlers)
        self.node.destroy_publisher(publisher)

        # Arg with three callbacks
        callbacks.incompatible_qos = incompatible_qos_callback
        try:
            publisher = self.node.create_publisher(EmptyMsg,
                                                   self.topic_name,
                                                   10,
                                                   event_callbacks=callbacks)
            self.assertEqual(len(publisher.event_handlers), 3)
            self.node.destroy_publisher(publisher)
        except UnsupportedEventTypeError:
            self.assertTrue(self.is_fastrtps)
Esempio n. 3
0
    def __init__(self):

        custom_callback = lambda event: print("Custom Incompatible Callback!")
        callbacks = PublisherEventCallbacks()
        callbacks.incompatible_qos = custom_callback

        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(String,
                                                'topic',
                                                10,
                                                event_callbacks=callbacks)
        timer_period = 0.5  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0
Esempio n. 4
0
    def __init__(
        self,
        publisher_handle: Handle,
        msg_type: MsgType,
        topic: str,
        qos_profile: QoSProfile,
        event_callbacks: PublisherEventCallbacks,
        callback_group: CallbackGroup,
    ) -> None:
        """
        Create a container for a ROS publisher.

        .. warning:: Users should not create a publisher with this constuctor, instead they should
           call :meth:`.Node.create_publisher`.

        A publisher is used as a primary means of communication in a ROS system by publishing
        messages on a ROS topic.

        :param publisher_handle: Capsule pointing to the underlying ``rcl_publisher_t`` object.
        :param msg_type: The type of ROS messages the publisher will publish.
        :param topic: The name of the topic the publisher will publish to.
        :param qos_profile: The quality of service profile to apply to the publisher.
        """
        self.__handle = publisher_handle
        self.msg_type = msg_type
        self.topic = topic
        self.qos_profile = qos_profile

        self.event_handlers = event_callbacks.create_event_handlers(
            callback_group, publisher_handle)
Esempio n. 5
0
def main(args=None):
    parsed_args = parse_args()
    rclpy.init(args=args)

    topic = 'qos_deadline_chatter'
    deadline = Duration(seconds=parsed_args.deadline / 1000.0)

    qos_profile = QoSProfile(depth=10, deadline=deadline)

    subscription_callbacks = SubscriptionEventCallbacks(
        deadline=lambda event: get_logger('Listener').info(str(event)))
    listener = Listener(topic,
                        qos_profile,
                        event_callbacks=subscription_callbacks)

    publisher_callbacks = PublisherEventCallbacks(
        deadline=lambda event: get_logger('Talker').info(str(event)))
    talker = Talker(topic, qos_profile, event_callbacks=publisher_callbacks)

    publish_for_seconds = parsed_args.publish_for / 1000.0
    pause_for_seconds = parsed_args.pause_for / 1000.0
    pause_timer = talker.create_timer(  # noqa: F841
        publish_for_seconds, lambda: talker.pause_for(pause_for_seconds))

    executor = SingleThreadedExecutor()
    executor.add_node(listener)
    executor.add_node(talker)
    try:
        executor.spin()
    except KeyboardInterrupt:
        pass
    except ExternalShutdownException:
        sys.exit(1)
    finally:
        rclpy.try_shutdown()
Esempio n. 6
0
def publisher(
    node: Node,
    message_type: MsgType,
    topic_name: str,
    values: dict,
    period: float,
    print_nth: int,
    once: bool,
    qos_profile: QoSProfile,
) -> Optional[str]:
    """Initialize a node with a single publisher and run its publish loop (maybe only once)."""
    msg_module = get_message(message_type)
    values_dictionary = yaml.safe_load(values)
    if not isinstance(values_dictionary, dict):
        return 'The passed value needs to be a dictionary in YAML format'

    publisher_callbacks = PublisherEventCallbacks(
        incompatible_qos=handle_incompatible_qos_event)
    try:
        pub = node.create_publisher(msg_module,
                                    topic_name,
                                    qos_profile,
                                    event_callbacks=publisher_callbacks)
    except UnsupportedEventTypeError:
        pub = node.create_publisher(msg_module, topic_name, qos_profile)

    msg = msg_module()
    try:
        set_message_fields(msg, values_dictionary)
    except Exception as e:
        return 'Failed to populate field: {0}'.format(e)

    print('publisher: beginning loop')
    count = 0

    def timer_callback():
        nonlocal count
        count += 1
        if print_nth and count % print_nth == 0:
            print('publishing #%d: %r\n' % (count, msg))
        pub.publish(msg)

    timer = node.create_timer(period, timer_callback)
    if once:
        rclpy.spin_once(node)
        time.sleep(
            0.1)  # make sure the message reaches the wire before exiting
    else:
        rclpy.spin(node)

    node.destroy_timer(timer)
Esempio n. 7
0
def main(args=None):
    parsed_args = parse_args()
    rclpy.init(args=args)

    topic = 'qos_liveliness_chatter'
    liveliness_lease_duration = Duration(
        seconds=parsed_args.liveliness_lease_duration / 1000.0)
    liveliness_policy = POLICY_MAP[parsed_args.policy]

    qos_profile = QoSProfile(
        depth=10,
        liveliness=liveliness_policy,
        liveliness_lease_duration=liveliness_lease_duration)

    subscription_callbacks = SubscriptionEventCallbacks(
        liveliness=lambda event: get_logger('Listener').info(str(event)))
    listener = Listener(topic,
                        qos_profile,
                        event_callbacks=subscription_callbacks)

    publisher_callbacks = PublisherEventCallbacks(
        liveliness=lambda event: get_logger('Talker').info(str(event)))
    talker = Talker(topic,
                    qos_profile,
                    event_callbacks=publisher_callbacks,
                    assert_node_period=parsed_args.node_assert_period / 1000.0,
                    assert_topic_period=parsed_args.topic_assert_period /
                    1000.0)

    executor = SingleThreadedExecutor()

    def kill_talker():
        if liveliness_policy == QoSLivelinessPolicy.RMW_QOS_POLICY_LIVELINESS_AUTOMATIC:
            executor.remove_node(talker)
            talker.destroy_node()
        elif liveliness_policy == QoSLivelinessPolicy.RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_NODE:
            talker.stop()
        elif liveliness_policy == QoSLivelinessPolicy.RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC:
            talker.stop()
        kill_timer.cancel()

    if parsed_args.kill_publisher_after > 0:
        kill_timer = listener.create_timer(  # noqa: F841
            parsed_args.kill_publisher_after / 1000.0, kill_talker)

    executor.add_node(listener)
    executor.add_node(talker)
    executor.spin()

    rclpy.shutdown()
Esempio n. 8
0
def main(args=None):
    # Argument parsing and usage
    parser = get_parser()
    parsed_args = parser.parse_args()

    # Configuration variables
    qos_policy_name = parsed_args.incompatible_qos_policy_name
    qos_profile_publisher = QoSProfile(depth=10)
    qos_profile_subscription = QoSProfile(depth=10)

    if qos_policy_name == 'durability':
        print('Durability incompatibility selected.\n'
              'Incompatibility condition: publisher durability kind <'
              'subscripition durability kind.\n'
              'Setting publisher durability to: VOLATILE\n'
              'Setting subscription durability to: TRANSIENT_LOCAL\n')
        qos_profile_publisher.durability = \
            QoSDurabilityPolicy.RMW_QOS_POLICY_DURABILITY_VOLATILE
        qos_profile_subscription.durability = \
            QoSDurabilityPolicy.RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL
    elif qos_policy_name == 'deadline':
        print(
            'Deadline incompatibility selected.\n'
            'Incompatibility condition: publisher deadline > subscription deadline.\n'
            'Setting publisher durability to: 2 seconds\n'
            'Setting subscription durability to: 1 second\n')
        qos_profile_publisher.deadline = Duration(seconds=2)
        qos_profile_subscription.deadline = Duration(seconds=1)
    elif qos_policy_name == 'liveliness_policy':
        print('Liveliness Policy incompatibility selected.\n'
              'Incompatibility condition: publisher liveliness policy <'
              'subscripition liveliness policy.\n'
              'Setting publisher liveliness policy to: AUTOMATIC\n'
              'Setting subscription liveliness policy to: MANUAL_BY_TOPIC\n')
        qos_profile_publisher.liveliness = \
            QoSLivelinessPolicy.RMW_QOS_POLICY_LIVELINESS_AUTOMATIC
        qos_profile_subscription.liveliness = \
            QoSLivelinessPolicy.RMW_QOS_POLICY_LIVELINESS_MANUAL_BY_TOPIC
    elif qos_policy_name == 'liveliness_lease_duration':
        print(
            'Liveliness lease duration incompatibility selected.\n'
            'Incompatibility condition: publisher liveliness lease duration >'
            'subscription liveliness lease duration.\n'
            'Setting publisher liveliness lease duration to: 2 seconds\n'
            'Setting subscription liveliness lease duration to: 1 second\n')
        qos_profile_publisher.liveliness_lease_duration = Duration(seconds=2)
        qos_profile_subscription.liveliness_lease_duration = Duration(
            seconds=1)
    elif qos_policy_name == 'reliability':
        print(
            'Reliability incompatibility selected.\n'
            'Incompatibility condition: publisher reliability < subscripition reliability.\n'
            'Setting publisher reliability to: BEST_EFFORT\n'
            'Setting subscription reliability to: RELIABLE\n')
        qos_profile_publisher.reliability = \
            QoSReliabilityPolicy.RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT
        qos_profile_subscription.reliability = \
            QoSReliabilityPolicy.RMW_QOS_POLICY_RELIABILITY_RELIABLE
    else:
        print('{name} not recognised.'.format(name=qos_policy_name))
        parser.print_help()
        return 0

    # Initialization and configuration
    rclpy.init(args=args)
    topic = 'incompatible_qos_chatter'
    num_msgs = 5

    publisher_callbacks = PublisherEventCallbacks(
        incompatible_qos=lambda event: get_logger('Talker').info(str(event)))
    subscription_callbacks = SubscriptionEventCallbacks(
        incompatible_qos=lambda event: get_logger('Listener').info(str(event)))

    try:
        talker = Talker(topic,
                        qos_profile_publisher,
                        event_callbacks=publisher_callbacks,
                        publish_count=num_msgs)
        listener = Listener(topic,
                            qos_profile_subscription,
                            event_callbacks=subscription_callbacks)
    except UnsupportedEventTypeError as exc:
        print()
        print(exc, end='\n\n')
        print('Please try this demo using a different RMW implementation')
        return -1

    executor = SingleThreadedExecutor()
    executor.add_node(listener)
    executor.add_node(talker)

    try:
        while talker.publish_count < num_msgs:
            executor.spin_once()
    except KeyboardInterrupt:
        pass

    rclpy.shutdown()

    return 0