<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Publish and Subscribe - safe_drive: Formally Specified Rust Bindings for ROS2</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded "><a href="index.html"><strong aria-hidden="true">1.</strong> Top</a></li><li class="chapter-item expanded "><a href="tutorial.html"><strong aria-hidden="true">2.</strong> Tutorial</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="setup.html"><strong aria-hidden="true">2.1.</strong> Setting-up</a></li><li class="chapter-item expanded "><a href="pubsub.html" class="active"><strong aria-hidden="true">2.2.</strong> Publish and Subscribe</a></li><li class="chapter-item expanded "><a href="timer.html"><strong aria-hidden="true">2.3.</strong> Timer</a></li><li class="chapter-item expanded "><a href="multi_pubsub.html"><strong aria-hidden="true">2.4.</strong> Multi-threaded Publish and Subscribe</a></li><li class="chapter-item expanded "><a href="message.html"><strong aria-hidden="true">2.5.</strong> User Defined Data Structure</a></li><li class="chapter-item expanded "><a href="service.html"><strong aria-hidden="true">2.6.</strong> Service</a></li><li class="chapter-item expanded "><a href="parameter.html"><strong aria-hidden="true">2.7.</strong> Parameter</a></li><li class="chapter-item expanded "><a href="zerocopy.html"><strong aria-hidden="true">2.8.</strong> Zero Copy Publish and Subscribe</a></li><li class="chapter-item expanded "><a href="allocator.html"><strong aria-hidden="true">2.9.</strong> Custom Memory Allocator</a></li><li class="chapter-item expanded "><a href="pusbsub_and_service.html"><strong aria-hidden="true">2.10.</strong> Request to Server in Callback</a></li></ol></li><li class="chapter-item expanded "><a href="contribution.html"><strong aria-hidden="true">3.</strong> Contribution Guide</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="setup_contribution.html"><strong aria-hidden="true">3.1.</strong> Setting-up for Contribution</a></li><li class="chapter-item expanded "><a href="build_and_test.html"><strong aria-hidden="true">3.2.</strong> Build and Test</a></li><li class="chapter-item expanded "><a href="editor_setup.html"><strong aria-hidden="true">3.3.</strong> Editor Setting-up</a></li><li class="chapter-item expanded "><a href="internal_msgs.html"><strong aria-hidden="true">3.4.</strong> Generating Messages Included by safe_drive</a></li><li class="chapter-item expanded "><a href="c_apis.html"><strong aria-hidden="true">3.5.</strong> C APIs</a></li><li class="chapter-item expanded "><a href="document.html"><strong aria-hidden="true">3.6.</strong> Documentation</a></li></ol></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">safe_drive: Formally Specified Rust Bindings for ROS2</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="publish-and-subscribe"><a class="header" href="#publish-and-subscribe">Publish and Subscribe</a></h1>
<p><a href="https://github.com/tier4/safe_drive_tutorial/tree/main/pubsub">Source code</a>.</p>
<p>This chapter introduces a simple example of publish and subscribe communication.
This communication is so-called topic by ROS2.
There are <code>N</code> senders and <code>M</code> receivers in a topic.
This tutorial implements 1 sender (in Rust) and 2 receivers (in Rust and C++).</p>
<p>The following figure is a example topology.</p>
<pre class="mermaid">graph TD;
Publisher1-->TopicA;
Publisher2-->TopicA;
TopicA-->Subscriber1;
TopicA-->Subscriber2;
TopicA-->Subscriber3;
Publisher3-->TopicB;
Publisher4-->TopicB;
Publisher5-->TopicB;
TopicB-->Subscriber4;
TopicB-->Subscriber5;
</pre>
<p>There are 2 topics, <code>TopicA</code> and <code>TopicB</code> in this figure.
If <code>Publisher2</code> of <code>TopicA</code> send a message,
<code>Subscriber1-3</code> subscribing <code>TopicA</code> receive the message.
<code>Subscriber4</code> and <code>Subscriber5</code> can receive messages sent from
<code>Publisher3-5</code>.</p>
<h2 id="directories"><a class="header" href="#directories">Directories</a></h2>
<p>First of all, create working directories as follows.</p>
<pre><code class="language-text">$ mkdir pubsub
$ mkdir pubsub/src
</code></pre>
<p>Then create projects of Rust by using <code>cargo</code> as follows.</p>
<pre><code class="language-text">$ cd pubsub/src
$ cargo new my_talker
$ cargo new my_listener
</code></pre>
<p>Following directories are important directories
we will use throughout this tutorial.</p>
<div class="table-wrapper"><table><thead><tr><th>Directories</th><th>What?</th></tr></thead><tbody>
<tr><td>pubsub/src/my_talker</td><td>publisher in Rust</td></tr>
<tr><td>pubsub/src/my_listener</td><td>subscriber in Rust</td></tr>
<tr><td>pubsub/install</td><td>created by colcon</td></tr>
</tbody></table>
</div>
<h2 id="workspace-of-rust"><a class="header" href="#workspace-of-rust">Workspace of Rust</a></h2>
<p>To handle multiple projects of <code>cargo</code>, we recommend to prepare <code>Cargo.toml</code> for the workspace as follows.</p>
<p><code>pubsub/src/Cargo.toml</code></p>
<pre><code class="language-toml">[workspace]
members = ["my_talker", "my_listener"]
</code></pre>
<p>The workspace enables <code>rust-analyzer</code> and reduces compilation time.</p>
<hr />
<h2 id="talker-in-rust"><a class="header" href="#talker-in-rust">Talker in Rust</a></h2>
<p>Let's start implementing a publisher.
We created and will edit files of the talker as follows.
These files will automatically created when you do <code>cargo new</code> as described before.</p>
<div class="table-wrapper"><table><thead><tr><th>Files</th><th>What?</th></tr></thead><tbody>
<tr><td>my_talker/Cargo.toml</td><td>for Cargo</td></tr>
<tr><td>my_talker/package.xml</td><td>for ROS2</td></tr>
<tr><td>my_talker/src/main.rs</td><td>source code</td></tr>
</tbody></table>
</div>
<h3 id="edit-my_talkercargotoml"><a class="header" href="#edit-my_talkercargotoml">Edit <code>my_talker/Cargo.toml</code></a></h3>
<p><code>Cargo.toml</code> is used to describe a project of Rust.
Add safe_drive to the dependencies of <code>Cargo.toml</code> to use it.
Currently, safe_drive's repository is private,
and we need to specify the path as follows.</p>
<p><code>pubsub/src/my_talker/Cargo.toml</code></p>
<pre><code class="language-toml">[dependencies]
safe_drive = "0.4"
std_msgs = { path = "/tmp/safe_drive_tutorial/pubsub/std_msgs" }
[package.metadata.ros]
msg = ["std_msgs"]
msg_dir = "/tmp/safe_drive_tutorial/pubsub"
safe_drive_version = "0.3"
</code></pre>
<h3 id="edit-my_talkersrcmainrs"><a class="header" href="#edit-my_talkersrcmainrs">Edit <code>my_talker/src/main.rs</code></a></h3>
<p>my_talker is very simple.
This does as follows.</p>
<ol>
<li>Create a context.</li>
<li>Create a node from the context.</li>
<li>Create a publisher from the node.</li>
<li>Send a message periodically.</li>
</ol>
<p>A context is a resource manager of ROS2,
and it must be created first of all.
A node contains publishers, subscribers, servers, and clients.
A node is a functional unit of ROS2.
Publishers and subscribers can be created by a node.</p>
<p>The following figure is an example hierarchy.</p>
<pre class="mermaid">graph TD;
Context-->NodeA
NodeA-->SubscriberA
NodeA-->SubscriberB
NodeA-->PublisherA
NodeA-->PublisherB
NodeA-->PublisherC
</pre>
<p>In this figure, <code>NodeA</code> is created by a context,
and subscribers and publishers are created by the node.</p>
<p>Now, we have understood the basics of ROS2.
The following is a code of my_talker.
You should also understand what this code is doing.</p>
<p><code>pubsub/src/my_talker/src/main.rs</code></p>
<pre><pre class="playground"><code class="language-rust">use safe_drive::{
context::Context, error::DynError, logger::Logger, pr_info
};
use std::time::Duration;
fn main() -> Result<(), DynError> {
// Create a context.
let ctx = Context::new()?;
// Create a node.
let node = ctx.create_node("my_talker", None, Default::default())?;
// Create a publisher.
let publisher = node.create_publisher::<std_msgs::msg::String>("my_topic", None)?;
// Create a logger.
let logger = Logger::new("my_talker");
let mut cnt = 0; // Counter.
let mut msg = std_msgs::msg::String::new().unwrap();
loop {
// Create a message to be sent.
let data = format!("Hello, World!: cnt = {cnt}");
msg.data.assign(&data);
pr_info!(logger, "send: {}", msg.data); // Print log.
// Send a message.
publisher.send(&msg)?;
// Sleep 1s.
cnt += 1;
std::thread::sleep(Duration::from_secs(1));
}
}</code></pre></pre>
<h4 id="my_talker-in-detail"><a class="header" href="#my_talker-in-detail">my_talker in Detail</a></h4>
<p><code>create_node</code> creates a node.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a node.
let node = ctx.create_node("my_talker", None, Default::default())?;
<span class="boring">}</span></code></pre></pre>
<p>The arguments indicate as follows.</p>
<ul>
<li><code>"my_talker"</code> : the name of the node.</li>
<li>Node : namespace.
<ul>
<li>We can pass a namespace like <code>Some("namespace")</code>.</li>
<li>If <code>None</code> is passed, the node has no namespace.</li>
</ul>
</li>
<li><code>Default::default()</code> : option of node.</li>
</ul>
<p><code>create_publisher</code> creates a publisher.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a publisher.
let publisher = node.create_publisher::<std_msgs::msg::String>("my_topic", None)?;
<span class="boring">}</span></code></pre></pre>
<ul>
<li><code><std_msgs::msg::String></code> : the publisher can send values of <code>std_msgs::msg::String</code>.</li>
<li><code>"my_topic"</code> : the topic name to which the publisher send messages.</li>
<li><code>None</code> : QoS of the publisher. QoS will be described in a later chapter.</li>
</ul>
<p>A message can be sent by <code>send</code> method as follows.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a message to be sent.
let data = format!("Hello, World!: cnt = {cnt}");
msg.data.assign(&data);
// Send a message.
publisher.send(&msg)?;
<span class="boring">}</span></code></pre></pre>
<p><code>Logger</code> is used to print some messages.
It can be created as follows.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a logger.
let logger = Logger::new("my_talker");
<span class="boring">}</span></code></pre></pre>
<p>The argument of <code>"my_talker"</code> is the name of the logger.
To print a message, use <code>pr_*</code> macros as follows.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pr_info!(logger, "send: {}", msg.data); // Print log.
<span class="boring">}</span></code></pre></pre>
<p>There are macros for logging as follows.</p>
<ul>
<li><code>pr_debug!</code> : debug</li>
<li><code>pr_info!</code> : information</li>
<li><code>pr_warn!</code> : warning</li>
<li><code>pr_err!</code> : error</li>
<li><code>pr_fatal!</code> : fatal</li>
</ul>
<h3 id="create-my_talkerpackagexml"><a class="header" href="#create-my_talkerpackagexml">Create <code>my_talker/package.xml</code></a></h3>
<p><code>package.xml</code> is used by colcon, which is a build tool used by ROS2.
It contains the package name, maintainer, description, etc, as follows.</p>
<p><code>pubsub/src/my_talker/package.xml</code></p>
<pre><code class="language-xml"><?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>my_talker</name>
<version>0.0.0</version>
<description>My Talker in Rust</description>
<maintainer email="yuuki.takano@tier4.jp">Yuuki Takano</maintainer>
<license>Apache License 2.0</license>
<depend>std_msgs</depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cargo</build_type>
</export>
</package>
</code></pre>
<p>Copy and paste this, then edit it if you want.</p>
<h3 id="execute-the-talker"><a class="header" href="#execute-the-talker">Execute the Talker</a></h3>
<p>Before compiling, ensure that you load setting of ROS2 as follows.
If you have already done so, you do not need this.</p>
<pre><code class="language-text">$ . /opt/ros/iron/setup.bash
</code></pre>
<p>Then compile by using colcon as follows.
Before compiling, change the current directory to <code>pubsub</code>,
which is the top directory of our project.</p>
<pre><code class="language-text">$ cd pubsub
$ colcon build --cargo-args --release
</code></pre>
<p><code>--cargo-args --release</code> is a option to pass the <code>--release</code> argument to <code>cargo</code>.
<code>cargo</code> optimizes the code when <code>--release</code> is specified.</p>
<p>To launch <code>my_talker</code>,
load the setting and use <code>ros2</code> command as follows.</p>
<pre><code class="language-text">$ . ./install/setup.bash
$ ros2 run my_talker my_talker
[INFO] [1656048392.368568500] [my_talker]: send: Hello, World!: cnt = 0
[INFO] [1656048393.368787500] [my_talker]: send: Hello, World!: cnt = 1
[INFO] [1656048394.368994200] [my_talker]: send: Hello, World!: cnt = 2
</code></pre>
<hr />
<h2 id="listener-in-rust"><a class="header" href="#listener-in-rust">Listener in Rust</a></h2>
<p>Let's then implement a listener.
We created and will edit files of the listener as follows.</p>
<div class="table-wrapper"><table><thead><tr><th>Files</th><th>What?</th></tr></thead><tbody>
<tr><td>my_listener/Cargo.toml</td><td>for Cargo</td></tr>
<tr><td>my_listener/package.xml</td><td>for ROS2</td></tr>
<tr><td>my_listener/src/main.rs</td><td>source code</td></tr>
</tbody></table>
</div>
<h3 id="edit-my_listenercargotoml"><a class="header" href="#edit-my_listenercargotoml">Edit <code>my_listener/Cargo.toml</code></a></h3>
<p><code>my_listener</code> also requires safe_drive.
Add safe_drive to the dependencies as follows.</p>
<pre><code class="language-toml"># pubsub/src/my_listener/Cargo.toml
[dependencies]
safe_drive = "0.4"
std_msgs = { path = "/tmp/safe_drive_tutorial/pubsub/std_msgs" }
[package.metadata.ros]
msg = ["std_msgs"]
msg_dir = "/tmp/safe_drive_tutorial/pubsub"
safe_drive_version = "0.3"
</code></pre>
<h3 id="edit-my_listenersrcmainrs"><a class="header" href="#edit-my_listenersrcmainrs">Edit <code>my_listener/src/main.rs</code></a></h3>
<p>To implement subscriber,
we have to prepare a callback function of the subscriber.
This is the main difference from <code>my_talker</code>.</p>
<p><code>pubsub/src/my_listener/src/main.rs</code></p>
<pre><pre class="playground"><code class="language-rust">use safe_drive::{
context::Context, error::DynError, logger::Logger, pr_info,
};
fn main() -> Result<(), DynError> {
// Create a context.
let ctx = Context::new()?;
// Create a node.
let node = ctx.create_node("my_listener", None, Default::default())?;
// Create a subscriber.
let subscriber = node.create_subscriber::<std_msgs::msg::String>("my_topic", None)?;
// Create a logger.
let logger = Logger::new("my_listener");
// Create a selector.
let mut selector = ctx.create_selector()?;
// Add a callback function.
selector.add_subscriber(
subscriber,
Box::new(move |msg| {
pr_info!(logger, "receive: {}", msg.data);
}),
);
// Spin.
loop {
selector.wait()?;
}
}</code></pre></pre>
<h4 id="my_listener-in-detail"><a class="header" href="#my_listener-in-detail"><code>my_listener</code> in Detail</a></h4>
<p>Similar to the publisher,
<code>create_subscriber</code> creates a subscriber.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a subscriber.
let subscriber = node.create_subscriber::<std_msgs::msg::String>("my_topic", None)?;
<span class="boring">}</span></code></pre></pre>
<p>The arguments are as follows.</p>
<ul>
<li><code>"my_topic"</code> : the name of the topic to which the subscriber is subscribing.</li>
<li><code>None</code> : QoS of the subscriber. Discussed in a later chapter.</li>
</ul>
<p>To add and invoke a callback function.
We need to create a selector,
which can wait some events and invoke callback functions of the events.
A selector is similar to <code>select</code> or <code>epoll</code> function,
and equivalent to a executer of ROS2.</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// Create a selector.
let mut selector = ctx.create_selector()?;
// Add a callback function.
selector.add_subscriber(
subscriber,
Box::new(move |msg| {
pr_info!(logger, "receive: {}", msg.data);
}),
);
// Spin.
loop {
selector.wait()?;
}
<span class="boring">}</span></code></pre></pre>
<p>The arguments of <code>add_subscriber</code> method are as follows.</p>
<ul>
<li><code>subscriber</code> : the subscriber.</li>
<li><code>Box::new(move |msg| { pr_info!(logger, "receive: {}", msg.data); })</code> : the callback function.</li>
<li><code>false</code> : the callback function is called only once or not. If <code>false</code> is passed, the callback function is invoked every time and forever.</li>
</ul>
<p><code>selector.wait()</code> wait events.
To receive events forever, use infinite loop.</p>
<h3 id="create-my_listenerpackagexml"><a class="header" href="#create-my_listenerpackagexml">Create <code>my_listener/package.xml</code></a></h3>
<p><code>package.xml</code> is almost same as above.
The only difference is the name of the package,
which is <code>my_listener</code>.</p>
<p><code>pubsub/src/my_listener/package.xml</code></p>
<pre><code class="language-xml"><?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>my_listener</name>
<version>0.0.0</version>
<description>My Listener in Rust</description>
<maintainer email="yuuki.takano@tier4.jp">Yuuki Takano</maintainer>
<license>Apache License 2.0</license>
<depend>std_msgs</depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cargo</build_type>
</export>
</package>
</code></pre>
<h3 id="execute-the-listener"><a class="header" href="#execute-the-listener">Execute the Listener</a></h3>
<p>Before compiling and executing, execute <code>my_talker</code> in other terminal,
and don't forget to load the setting of ROS2 as mentioned above.
The compilation can be done as follows.</p>
<pre><code class="language-text">$ cd pubsub
$ colcon build --cargo-args --release
</code></pre>
<p>To execute <code>my_listener</code>, load the setting of our projects and
execute it by using <code>ros2</code> command as follows.</p>
<pre><code class="language-text">$ . ./install/setup.bash
$ ros2 run my_listener my_listener
[INFO] [1656050459.231579900] [my_listener]: receive: Hello, World!: cnt = 4
[INFO] [1656050460.231831200] [my_listener]: receive: Hello, World!: cnt = 5
[INFO] [1656050461.232120000] [my_listener]: receive: Hello, World!: cnt = 6
</code></pre>
<p>Nicely done!
We are receiving messages sent from <code>my_talker</code>.</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="setup.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="timer.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="setup.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="timer.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js"></script>
<script src="mark.min.js"></script>
<script src="searcher.js"></script>
<script src="clipboard.min.js"></script>
<script src="highlight.js"></script>
<script src="book.js"></script>
<!-- Custom JS scripts -->
<script src="mermaid.min.js"></script>
<script src="mermaid-init.js"></script>
</div>
</body>
</html>