Skip to content

Commit fbb8629

Browse files
committed
Adds an example.
Signed-off-by: Agustin Alba Chicar <[email protected]>
1 parent 91756ca commit fbb8629

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

examples/rclrs_timer_demo/Cargo.toml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[package]
2+
name = "rclrs_timer_demo"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[[bin]]
7+
name="rclrs_timer_demo"
8+
path="src/rclrs_timer_demo.rs"
9+
10+
11+
[dependencies]
12+
rclrs = "*"

examples/rclrs_timer_demo/package.xml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<package format="3">
2+
<name>rclrs_timer_demo</name>
3+
<version>0.1.0</version>
4+
<description>Shows how to implement a timer within a Node using rclrs.</description>
5+
<maintainer email="[email protected]">user</maintainer>
6+
<license>TODO: License declaration.</license>
7+
8+
<depend>rclrs</depend>
9+
10+
<export>
11+
<build_type>ament_cargo</build_type>
12+
</export>
13+
</package>
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/// Creates a SimpleTimerNode, initializes a node and the timer with a callback
2+
/// that prints the timer callback execution iteration. The callback is executed
3+
/// thanks to the spin, which is in charge of executing the timer's events among
4+
/// other entities' events.
5+
use rclrs::{create_node, Context, Node, Timer, RclrsError};
6+
use std::{env, sync::{Arc, Mutex}};
7+
8+
/// Contains both the node and timer.
9+
struct SimpleTimerNode {
10+
node: Arc<Node>,
11+
timer: Arc<Timer>,
12+
}
13+
14+
impl SimpleTimerNode {
15+
16+
/// Creates a node and a timer with a callback.
17+
///
18+
/// The callback will simply print to stdout:
19+
/// "Drinking 🧉 for the <x>th time every <p> nanoseconds."
20+
/// where <x> is the iteration callback counter and <p> is the period of the timer.
21+
fn new(context: &Context, timer_period_ns: i64) -> Result<Self, RclrsError> {
22+
let node = create_node(context, "simple_timer_node")?;
23+
let count: Arc<Mutex<i32>> = Arc::new(Mutex::new(0));
24+
let timer = node.create_timer(
25+
timer_period_ns,
26+
context,
27+
Some(Box::new(move |_| {
28+
let x = *count.lock().unwrap();
29+
println!("Drinking 🧉 for the {}th time every {} nanoseconds.", x, timer_period_ns);
30+
*count.lock().unwrap() = x + 1;
31+
})),
32+
None,
33+
)?;
34+
Ok(Self { node, timer })
35+
}
36+
}
37+
38+
39+
fn main() -> Result<(), RclrsError> {
40+
let timer_period: i64 = 1e9 as i64; // 1 seconds.
41+
let context = Context::new(env::args()).unwrap();
42+
let simple_timer_node = Arc::new(SimpleTimerNode::new(&context, timer_period).unwrap());
43+
rclrs::spin(simple_timer_node.node.clone())
44+
}

0 commit comments

Comments
 (0)