ros2subscriber
Subscribe to messages on a topic
Description
Use the ros2subscriber to receive messages on a topic. When ROS 2 nodes publish messages on that topic, MATLAB® will receive those message through this subscriber.
Creation
Syntax
Description
creates a subscriber, sub
= ros2subscriber(node
,topic
)sub
, for a topic with name
topic
that already exists on the ROS 2 network.
node
is the ros2node
object to which this subscriber attaches. The subscriber gets the
topic message type from the network topic list.
Note
The topic must be on the network topic list.
creates a subscriber for a topic and adds that topic to the network topic list. If the
topic list already contains a matching topic, sub
= ros2subscriber(node
,topic
,type
)sub
will be added to
the list of subscribers for that topic. The type
must be the same as
the topic. Use this syntax to avoid errors when it is possible for the subscriber to
subscribe to a topic before a topic has been added to the network.
specifies a callback function, sub
= ros2subscriber(node
,topic
,callback
)callback
, and optional data, to run
when the subscriber object handle receives a topic message. Use this syntax if action
needs to be taken on every message, while not blocking code execution.
callback
can be a single function handle or a cell array. The first
element of the cell array needs to be a function handle or a string containing the name of
a function. The remaining elements of the cell array can be arbitrary user data that will
be passed to the callback function.
Note
The subscriber callback function uses a single input argument, the received
message object, msg
. The function header for the callback is as
follows:
function subCallback(msg)
specifies additional options using one or more name-value pair arguments. Specify
name-value pair arguments after all other input arguments.sub
= ros2subscriber(___,Name,Value
)
Input Arguments
node
— ROS 2 node
ros2node
structure
A ros2node
object on the network.
topic
— Name of the published topic
string scalar | char array
Name of the published topic, specified as a string scalar or character vector. If the topic does not exist, the object creates the topic based on the associated message type.
Example: "/chatter"
type
— Subscribed message type
string scalar | char array
This property is read-only.
The message type of subscribed messages.
Example: "std_msgs/String"
Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN
, where Name
is
the argument name and Value
is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose
Name
in quotes.
History
— Mode of storing messages in the queue
"keeplast"
(default) | "keepall"
Determines the mode of storing messages in the queue. If the queue fills with
messages waiting to be processed, then old messages will be dropped to make room for
new. If set to "keeplast"
, the queue stores the number of
messages set by the Depth
property. If set to
"keepall"
, the queue stores all messages up to the MATLAB resource limits.
Depth
— Size of the message queue
non-negative scalar integer
(default)
Number of messages stored in the message queue when History
is set to "keeplast"
.
Example: 42
Data Types: double
Reliability
— Delivery guarantee of messages
"reliable"
(default) | "besteffort"
Requirement on the guarantee of message delivery. If
"reliable"
, then delivery is guaranteed, but may retry multiple
times. If "besteffort"
, then attempt delivery and do not
retry.
Example: "reliable"
Data Types: char
| string
Durability
— Persistence of messages
"volatile"
(default) | "transientlocal"
Requirement on the persistence of messages in connected publishers, which allows
late-joining subscribers to receive the number of old messages specified by
Depth
. If "volatile"
, then message
persistence is not required and no messages are requested when the subscriber joins
the network. If "transientlocal"
, then the subscriber will
require publishers to persist messages, and will request the number of messages
specified by Depth
.
Example: "volatile"
Data Types: char
| string
Deadline
— Expected interval between consecutive message receptions
Inf
(default) | positive scalar
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.
Example: 3
Data Types: double
Lifespan
— Message validity window between publishing and reception
Inf
(default) | positive scalar
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.
Example: 5
Data Types: double
Liveliness
— Publisher aliveness asserting protocol
"automatic"
(default)
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
.
Example: "automatic"
Data Types: char
| string
Lease Duration
— Maximum time window between liveliness assertions
Inf
(default) | positive scalar
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.
Example: 5
Data Types: double
IncompatibleQoSCallback
— Callback function to handle incompatible QoS settings
function handle
Callback function to handle incompatible QoS settings in subscriber, specified as a function handle with the following input arguments:
total_count
total_count_change
last_policy_kind
This is an example of the function signature header:
pub = ros2publisher(myNode, "/my_topic", "sensor_msgs/Image", "IncompatibleQoSCallback", @incompatibleQoS_callback); function incompatibleQoS_callback(total_count, total_count_change, last_policy_kind)
Data Types: function_handle
DeadlineMissedCallback
— Callback function to handle deadline missed event
function handle
Callback function to handle deadline missed event when the subscriber does not receive any messages within the specified deadline, specified as a function handle with the following input arguments:
total_count
total_count_change
This is an example of the function signature header:
pub = ros2publisher(myNode, "/my_topic", "sensor_msgs/Image", "DeadlineMissedCallback", @deadlineMissed_callback); function deadlineMissed_callback(total_count, total_count_change)
Data Types: function_handle
LivelinessLostCallback
— Callback function to handle liveliness lost event
function handle
Callback function to handle liveliness lost event when the subscriber has noticed that one or more publishers on the topic did not assert their liveliness within the lease duration, specified as a function handle with the following input arguments:
alive_count
not_alive_count
alive_count_change
not_alive_count_change
This is an example of the function signature header:
pub = ros2publisher(myNode, "/my_topic", "sensor_msgs/Image", "LivelinessLostCallback", @livelinessLost_callback); function livelinessLost_callback(alive_count, not_alive_count, alive_count_change, not_alive_count_change)
Data Types: function_handle
MessageLostCallback
— Callback function to handle message lost event
function handle
Callback function to handle message lost event when he subscriber missed receiving messages because of network issues, buffer overflows, or other communication problems, causing message loss; specified as a function handle with the following input arguments:
total_count
–– Total number of messages lost.total_count_change
–– Number of messages lost since last callback.
This is an example of the function signature header:
sub = ros2subscriber(myNode, "/my_topic", "sensor_msgs/Image", "MessageLostCallback", @messageLost_callback); function messageLost_callback(total_count, total_count_change)
Data Types: function_handle
Properties
TopicName
— Name of the published topic
string scalar | character vector
Name of the published topic, specified as a string scalar or character vector. If the topic does not exist, the object creates the topic based on the associated message type.
Example: "/chatter"
Data Types: char
MessageType
— Subscribed message type
string scalar | character vector
This property is read-only.
The message type of subscribed messages.
Example: "std_msgs/String"
Data Types: char
| string
LatestMessage
— Latest received message
Message
object handle
This property is read-only.
The most recently received ROS 2 message, specified as a Message
object handle, received.
NewMessageFcn
— Subscriber callback function
function
handle
This property is read-only.
Callback function for subscriber callbacks.
Note
The subscriber callback function uses a single input argument, the received
message object, msg
. The function header for the callback is as
follows:
function subCallback(msg)
History
— Message queue mode
"keeplast"
(default) | "keepall"
This property is read-only.
Determines the mode of storing messages in the queue. If the queue fills with
messages waiting to be processed, then old messages will be dropped to make room for
new. When set to "keeplast"
, the queue stores the number of messages
set by the Depth
property. Otherwise, when set to
"keepall"
, the queue stores all messages up to the MATLAB resource limits.
Example: "keeplast"
Data Types: char
| string
Depth
— Size of the message queue
non-negative scalar integer
This property is read-only.
Number of messages stored in the message queue when History
is
set to "keeplast"
.
Example: 42
Data Types: double
Reliability
— Delivery guarantee of messages
"reliable"
(default) | "besteffort"
This property is read-only.
Requirement on the guarantee of message delivery. If "reliable"
,
then delivery is guaranteed, but may retry multiple times. If
"besteffort"
, then attempt delivery and do not retry.
Example: "reliable"
Data Types: char
| string
Durability
— Persistence of messages
"volatile"
(default) | "transientlocal"
This property is read-only.
Requirement on the persistence of messages in connected publishers, which allows
late-joining subscribers to receive the number of old messages specified by
Depth
. If "volatile"
, then message persistence
is not required and no messages are requested when the subscriber joins the network. If
"transientlocal"
, then the subscriber will require publishers to
persist messages, and will request the number of messages specified by
Depth
.
Example: "volatile"
Data Types: char
| string
Deadline
— Expected interval between consecutive message receptions
Inf
(default) | positive scalar
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.
Example: 3
Data Types: double
Lifespan
— Message validity window between publishing and reception
Inf
(default) | positive scalar
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.
Example: 5
Data Types: double
Liveliness
— Publisher aliveness asserting protocol
"automatic"
(default)
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
.
Example: "automatic"
Data Types: char
| string
Lease Duration
— Maximum time window between liveliness assertions
Inf
(default) | positive scalar
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.
Example: 5
Data Types: double
Object Functions
receive | Wait for new message |
ros2message | Create ROS 2 message structures |
Examples
Exchange Data with ROS 2 Publishers and Subscribers
This example shows how to publish and subscribe to topics in a ROS 2 network.
The primary mechanism for ROS 2 nodes to exchange data is to send and receive messages. Messages are transmitted on a topic and each topic has a unique name in the ROS 2 network. If a node wants to share information, it must use a publisher to send data to a topic. A node that wants to receive that information must use a subscriber for that same topic. Besides its unique name, each topic also has a message type, which determines the type of messages that are allowed to be transmitted in the specific topic.
This publisher-subscriber communication has these characteristics:
Topics are used for many-to-many communication. Multiple publishers can send messages to the same topic and multiple subscribers can receive them.
Publisher and subscribers are decoupled through topics and can be created and destroyed in any order. A message can be published to a topic even if there are no active subscribers.
Besides how to publish and subscribe to topics in a ROS 2 network, this example also shows how to:
Wait until a new message is received, or
Use callbacks to process new messages in the background
Prerequisites: Get Started with ROS 2, Connect to a ROS 2 Network
Subscribe and Wait for Messages
Create a sample ROS 2 network with several publishers and subscribers.
exampleHelperROS2CreateSampleNetwork
Use ros2 topic list
to see which topics are available.
ros2 topic list
/parameter_events /pose /rosout /scan
Assume you want to subscribe to the /scan
topic. Use ros2subscriber
to subscribe to the /scan
topic. Specify the name of the node with the subscriber. If the topic already exists in the ROS 2 network, ros2subscriber
detects its message type automatically, so you do not need to specify it.
detectNode = ros2node("/detection"); pause(5) laserSub = ros2subscriber(detectNode,"/scan"); pause(5)
Use receive
to wait for a new message. Specify a timeout of 10 seconds. The output scanData
contains the received message data. status
indicates whether a message was received successfully and statustext
provides additional information about the status
.
[scanData,status,statustext] = receive(laserSub,10);
You can now remove the subscriber laserSub
and the node associated to it.
clear laserSub clear detectNode
Subscribe Using Callback Functions
Instead of using receive
to get data, you can specify a function to be called when a new message is received. This allows other MATLAB code to execute while the subscriber is waiting for new messages. Callbacks are essential if you want to use multiple subscribers.
Subscribe to the /pose
topic, using the callback function exampleHelperROS2PoseCallback
, which takes a received message as the input. One way of sharing data between your main workspace and the callback function is to use global variables. Define two global variables pos
and orient
.
controlNode = ros2node("/base_station"); pause(5) poseSub = ros2subscriber(controlNode,"/pose",@exampleHelperROS2PoseCallback); global pos global orient
The global variables pos
and orient
are assigned in the exampleHelperROS2PoseCallback
function when new message data is received on the /pose
topic.
function exampleHelperROS2PoseCallback(message) % Declare global variables to store position and orientation global pos global orient % Extract position and orientation from the ROS message and assign the % data to the global variables. pos = [message.linear.x message.linear.y message.linear.z]; orient = [message.angular.x message.angular.y message.angular.z]; end
Wait a moment for the network to publish another /pose
message. Display the updated values.
pause(3) disp(pos)
0.00235920447111606 -0.0201184589892978 0.0203969078651195
disp(orient)
-0.0118389124011118 0.00676849978014866 0.0387860955311228
If you type in pos
and orient
a few times in the command line you can see that the values are continuously updated.
Stop the pose subscriber by clearing the subscriber variable
clear poseSub clear controlNode
Note: There are other ways to extract information from callback functions besides using globals. For example, you can pass a handle object as additional argument to the callback function. See the Create Callbacks for Graphics Objects documentation for more information about defining callback functions.
Publish Messages
Create a publisher that sends ROS 2 string messages to the /chatter
topic.
chatterPub = ros2publisher(node_1,"/chatter","std_msgs/String");
Create and populate a ROS 2 message to send to the /chatter
topic.
chatterMsg = ros2message(chatterPub);
chatterMsg.data = 'hello world';
Use ros2 topic list
to verify that the /chatter
topic is available in the ROS 2 network.
ros2 topic list
/chatter /parameter_events /pose /rosout /scan
Define a subscriber for the /chatter
topic. exampleHelperROS2ChatterCallback
is called when a new message is received, and displays the string content in the message.
chatterSub = ros2subscriber(node_2,"/chatter",@exampleHelperROS2ChatterCallback)
chatterSub = ros2subscriber with properties: TopicName: '/chatter' LatestMessage: [] MessageType: 'std_msgs/String' NewMessageFcn: @exampleHelperROS2ChatterCallback History: 'keeplast' Depth: 10 Reliability: 'reliable' Durability: 'volatile'
Publish a message to the /chatter
topic. Observe that the string is displayed by the subscriber callback.
send(chatterPub,chatterMsg) pause(3)
ans = 'hello world'
The exampleHelperROS2ChatterCallback
function was called when the subscriber received the string message.
Disconnect From ROS 2 Network
Remove the sample nodes, publishers and subscribers from the ROS 2 network. Also clear the global variables pos
and orient
clear global pos orient clear
Next Steps
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
MessageType
argument must be specified.Callback functions must be assigned at the time of
ros2subscriber
object creation, and cannot be changed during run-time.When no message is received, the
LatestMessage
property returns a message with default values based on the message type.MEX code generation not supported.
Version History
Introduced in R2019b
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)