ROS 2节点以交换数据的主要机制是发送和接收messages。消息在a上传输话题和每个主题都有一个惟一名称2 netw ROSork. If a node wants to share information, it must use a发行商to send data to a topic. A node that wants to receive that information must use a订户for that same topic. Besides its unique name, each topic also has amessage type,它确定允许在特定主题中传输的消息类型。
该发布商用户通信具有以下特征:
此示例显示如何在ROS 2网络中发布和订阅主题。它还显示了如何:
先决条件:Get Started with ROS 2,Connect to a ROS 2 Network
Subscribe and Wait for Messages
使用多个发布商和订阅者创建示例ROS 2网络。
采用ROS2主题列表
to see which topics are available.
/ parameter_events / pose / rosout / scan
假设你想订阅/扫描
话题。采用ros2subscriber
to subscribe to the/扫描
话题。使用订阅者指定节点的名称。如果主题已存在于ROS 2网络中,ros2subscriber
自动检测其消息类型,因此您无需指定它。
采用收到
等待一条新留言。指定10秒的超时。输出scanData
包含收到的消息数据。status
指示是否已成功收到消息Statustext.
provides additional information about thestatus
。
您现在可以删除订阅者激光
和与它相关联的节点。
使用回调函数订阅
Instead of using收到
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.
订阅/姿势
话题, using the callback functionexampleHelperROS2PoseCallback
,它将收到的消息作为输入。在主工作空间和回调函数之间共享数据的一种方法是使用全局变量。定义两个全局变量p
和东方
。
全局变量p
和东方
are assigned in theexampleHelperROS2PoseCallback
在接收到新的消息数据时功能/姿势
话题。
functionexamplehelperros2posecallback(消息)% Declare global variables to store position and orientation全球的p全球的东方%从ROS消息中提取位置和方向并分配%数据到全局变量。pos = [message.linear.x message.linear.y message.linear.z];Orient = [message.angular.x message.angular.y message.angular.z];end
等待网络发布另一个时刻/姿势
信息。显示更新的值。
如果you type inp
和东方
在命令行中有几次,您可以看到持续更新值。
通过清除订户变量来停止姿势用户
Note:除了使用全局之外,还有其他方法可以从回调函数中提取来自回调函数的信息。例如,您可以将句柄对象作为回调函数的其他参数传递给回调函数。看看回调定义documentation for more information about defining callback functions.
发布消息
Create a publisher that sends ROS 2 string messages to the/chatter
话题。
创建和填充ROS 2消息以发送到/chatter
话题。
采用ROS2主题列表
验证/chatter
ROS 2网络中有主题可用。
/ chatter / parameter_events / pose / rosout / scan
Define a subscriber for the/chatter
话题。exampleHelperROS2ChatterCallback
收到新消息时被调用,并在消息中显示字符串内容。
chatterSub = ros2subscriber with properties: TopicName: '/chatter' LatestMessage: [] MessageType: 'std_msgs/String' NewMessageFcn: @exampleHelperROS2ChatterCallback History: 'keeplast' Depth: 10 Reliability: 'reliable' Durability: 'volatile'
发布消息/chatter
话题。观察字符串由订户回调显示。
TheexampleHelperROS2ChatterCallback
function was called when the subscriber received the string message.
断开ROS 2网络连接
从ROS 2网络删除样本节点,发布者和订阅者。还清除全局变量p
和东方
Next Steps