Contenido principal

Subscribe

R2026b

Receive messages from ROS 2 network by polling at each time step or processing immediately on arrival

  • Subscribe ROS 2 block

Libraries:
ROS Toolbox / ROS 2

Description

The Subscribe block creates a Simulink® non-virtual bus that corresponds to the specified ROS 2 message type. The block uses the node of the Simulink model to create a ROS 2 subscriber for a specific topic. This node is created when the model runs and is deleted when the model terminates. If the model does not have a node, the block creates one.

The block supports two message processing modes, which you can select using the Process messages parameter. In synchronous polling mode, the block checks for new messages at each sample time step and outputs them for processing. In asynchronous event-driven mode, the block processes messages immediately upon arrival by triggering an event signal. Depending on the parameter setting, the block uses one of these modes. The IsNew output port is used for polling mode execution. The block supports asynchronous mode only for code generation.

You can assign a ROS 2 callback group to the subscriber using the Callback group type parameter to control how the ROS 2 executor schedules the subscriber callback relative to other callbacks on the same node. This is useful for preventing deadlocks, enabling concurrent callback execution, improving throughput for high-frequency message processing, reducing jitter, and aligning Simulink simulation behavior with generated C++ code execution semantics.

Quality of Service (QoS) events related to different QoS policies trigger default warnings for the Subscribe block. For more information on the different QoS events and the triggered warnings respectively, see QoS Events section in Manage Quality of Service Policies in ROS 2 example.

In generated code, ROS 2 nodes created by this block can use loaned messages for subscribing. This enables zero-copy data transfer through shared memory and reduces processing overhead and improves throughput for large or frequent messages. ROS 2 automatically applies loaned message support in both local and remote deployments, but you can toggle with the environment variable ROS_DISABLE_LOANED_MESSAGES by setting it to 0 for enabling and 1 for disabling.

Currently, only selected RMW implementations support loaned messages, such as Fast DDS. To achieve true zero-copy communication, you must enable shared memory in the middleware by configuring the DEFAULT_FASTRTPS_PROFILES.xml file as shown in this code:

<?xml version="1.0" encoding="UTF-8" ?>
<profiles xmlns="http://www.eprosima.com/XMLSchemas/fastRTPS_Profiles">
    <data_writer profile_name="default publisher profile" is_default_profile="true">
        <qos>
            <publishMode>
                <kind>ASYNCHRONOUS</kind>
            </publishMode>
            <data_sharing>
                <kind>AUTOMATIC</kind>
            </data_sharing>
        </qos>
        <historyMemoryPolicy>PREALLOCATED_WITH_REALLOC</historyMemoryPolicy>
    </data_writer>

    <data_reader profile_name="default subscription profile" is_default_profile="true">
        <qos>
            <data_sharing>
                <kind>AUTOMATIC</kind>
            </data_sharing>
        </qos>
        <historyMemoryPolicy>PREALLOCATED_WITH_REALLOC</historyMemoryPolicy>
    </data_reader>
</profiles>

If a message type does not support loaning (for example, variable-length arrays or strings), the system issues a runtime warning and falls back to regular message handling.

Ports

Output

expand all

New message indicator, returned as 0 or 1 . If the output is 1, then a new message was received since the last sample hit. This output can be used to trigger subsystems for processing new messages received in the ROS 2 network.

This port is used in polling execution (At sample time). When the IsNew port value is set to 1, the Msg port holds the newly received message. When the IsNew port value is set to 0, the Msg port holds the last received message.

Dependencies

To enable this port, set the Process messages parameter to At sample time.

ROS 2 message, returned as a non-virtual bus. The bus corresponds to the ROS 2 message type specified in the Message type parameter. The Subscribe ROS 2 block outputs blank messages until it receives a message on the topic name you specify. These blank messages allow you to create and test full models before the rest of the network has been setup.

Data Types: bus

Event signal to trigger execution of subsystems when a new message arrives, specified as a function-call signal.

Connect this port to a Function-Call Subsystem that contains your message-processing algorithm. When a message arrives, the block issues a function-call event that triggers the connected subsystem.

In generated code, this event maps to a ROS 2 subscriber callback executed by the ROS 2 executor, enabling event-driven, non-polling message processing. During simulation, the asynchronous execution semantics are not active. The block and the connected Function-Call Subsystem appear as an atomic and aperiodic partition in the Timing Legend.

Dependencies

  • To enable this output port, set the Process messages parameter to Immediately on arrival.

Data Types: bus

Parameters

expand all

Main

Source for specifying the topic name, specified as one of the following:

  • Select from ROS network — Use Select to select a topic name. The Topic and Message type parameters are set automatically. You must be connected to a ROS network.

  • Specify your own — Enter a topic name in Topic and specify its message type in Message type. You must match a topic name exactly.

Topic name to subscribe to, specified as a string. When Topic source is set to Select from ROS network, use Select to select a topic from the ROS network. You must be connected to a ROS 2 network to get a list of topics. Otherwise, set Topic source to Specify your own and specify the topic you want.

ROS 2 message type, specified as a string. Use Select to select from a full list of supported ROS 2 messages. Service message types are not supported and are not included in the list.

Incoming message processing mode of subscriber, specified as one of these options:

  • At sample time — Processes messages using synchronous polling at each Simulink sample time step. The block displays outputs at the IsNew and Msg ports.

  • Immediately on arrival — Processes messages asynchronously as soon as they arrive, using an event-driven approach. When you select this option:

    • The OnMsgArrivalEvent port replaces the IsNew port.

    • The Sample time parameter is disabled.

    • The block and the connected Function-Call Subsystem appear as atomic and aperiodic in the Timing Legend.

    • The Linked Subsystem parameter link in the block mask changes to Create a Function-Call subsystem to process the messages.

Path to the subsystem lined to the Subscribe block, specified as the following options:

  • Create a Enabled Subsystem to process the messages — Set the Process messages parameter to At sample time to enable this option. Click it to create a Enabled Subsystem that processes messages at the sample time of the block. The subsystem is triggered by the IsNew output port.

  • Create a Function-Call Subsystem to process the messages — Set the Process messages parameter to Immediately on arrival to enable this option. Click it to create a Function-Call subsystem that processes messages immediately upon arrival. The subsystem is triggered by the OnMsgArrivalEvent output port.

After you create a linked subsystem, clicking the path displays and highlights the subsystem in your model.

Interval between outputs, specified as –1 or a positive scalar. A value of –1 means the block inherits the sample time from the model. In simulation, the sample time follows simulation time and not actual wall-clock time.

This default value indicates that the block sample time is inherited.

For more information about the inherited sample time type, see Specify Sample Time (Simulink).

Dependencies

  • When the Process messages parameter is set to Immediately on arrival, the block ignores this parameter. In asynchronous mode, message processing is event-driven and not governed by a fixed sample time.

Type of ROS 2 callback group to assign to the subscriber, specified as one of these values:

  • Default — Assign the subscriber to the default callback group of the ROS 2 node. The default callback group is mutually exclusive, which means that only one callback in the group can execute at a time. This is the standard ROS 2 behavior.

  • Mutually exclusive — Assign the subscriber to a named mutually exclusive callback group. Only one callback in this group can execute at a time, but callbacks in different groups can execute concurrently. Specify the group name using the Callback Group Name parameter. Blocks that share a name share a group.

  • Reentrant — Assign the subscriber to a reentrant callback group. Multiple callbacks in this group can execute concurrently. Use this option when your algorithm is thread-safe and you need concurrent callback execution for improved throughput.

    Note

    When using a reentrant callback group:

    • The ROS 2 executor might run multiple instances of the same callback concurrently.

    • Messages might be processed out of order.

    Use reentrant callback groups only when your algorithm is thread-safe and does not depend on strict ordering.

Name of the callback group, specified as a character vector. Use this parameter to assign the subscriber to a specific callback group. Multiple blocks that share the same callback group name belong to the same callback group, allowing you to control which callbacks are grouped together for concurrency management.

Dependencies

To enable this parameter, set the Callback group type parameter to Mutually exclusive.

Quality of Service (QoS)

Determines the mode of storing messages in the queue. The queued messages will be sent to late-joining subscribers. If the queue fills with messages waiting to be processed, then old messages will be dropped to make room for new. When set to Keep last, the queue stores the number of messages set by the Depth property. Otherwise, when set to Keep all, the queue stores all messages up to the MATLAB® resource limits. Queued messages are available to late-joining subscribers. If the queue fills, old messages are dropped to make room for new ones. When set to Keep last, the queue stores up to the number of messages specified by the Depth parameter. When set to Keep all, the queue stores all messages up to MATLAB resource limits.

Number of messages stored in the message queue when History is set to Keep last. During simulation, this value controls how many messages can be processed in order per time step, helping avoid message drops at high publish rates.

  • To always receive the most recent message, set the queue size to 1.

  • To process more messages without losing them, set the queue size to a value greater than 1. If multiple messages arrive between simulation steps,the block stores them in the queue and processes them in the same order.

  • Ensure that the QoS Depth value is set large enough to handle the expected message rate between simulation steps, to prevent message drop due to queue overflow.

Affects the guarantee of message delivery. If Reliable, then delivery is guaranteed, but may retry multiple times. If Best effort, then attempt delivery and do not retry.

Affects persistence of messages in publishers, which allows late-joining subscribers to receive the number of old messages specified by Depth. If Volatile, then messages do not persist. If Transient local, then publisher will retain the most recent messages.

Outlines the permissible duration between message receptions by subscriber, specified as a positive scalar. In case the messages are not received within the deadline, the client application receives a notification.

The default value is Inf which implies that expected interval between subsequent message receptions is infinite. If Deadline is set to 3, it ensures that the subscriber subscribes to every succeeding message is published to the topic after 3 seconds of subscribing to the preceding message.

Defines the duration a message is deemed valid, beyond which it will not be received by subscriber, specified as a positive scalar. Messages that have expired are silently discarded.

The default value is Inf which implies that a message is deemed valid and received by subscriber for infinite duration. If Lifespan is set to 5, it means that a message is considered valid for 5 seconds after being published. If subscriber has not received the message within that time frame, the message is considered expired.

Determines the reporting standard expected from the publishers to which they are subscribed, specified as a string.

Liveliness set to "automatic" implies that when any of the publishers has published a message, the system will consider all publishers of the node to be alive for an additional Lease Duration.

Defines the maximum duration for which a subscriber expects a publisher to demonstrate its liveliness before the system considers it to have lost liveliness, specified as a positive scalar. Losing liveliness could serve as an indication of failure.

The default value is Inf which implies that a publisher can assert its liveliness for infinite period of time. If the Lease Duration is set to 5, it implies that the subscriber can expect the publisher to demonstrate its liveliness within a maximum of 5 seconds. If the publisher does not send any messages or explicitly assert its liveliness within that time frame, it is considered to have lost liveliness.

Extended Capabilities

expand all

Version History

Introduced in R2019b

expand all