Skip to content

Commit 164631e

Browse files
authored
Adding a simple helper function for converting rclrs::Time to a ros message (#359)
* Adding a simple helper function for converting `rclrs::Time` to a ros message This commit adds a simple conversion function that would converts Time to builtin_interfaces like the one in rclpy. Signed-off-by: Arjo Chakravarty <arjo@openrobotics.org> * Style Signed-off-by: Arjo Chakravarty <arjo@openrobotics.org> * Update tests Signed-off-by: Arjo Chakravarty <arjo@openrobotics.org> * Remove whitespace Signed-off-by: Arjo Chakravarty <arjo@openrobotics.org> --------- Signed-off-by: Arjo Chakravarty <arjo@openrobotics.org>
1 parent 3fb5e5f commit 164631e

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

rclrs/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ libloading = { version = "0.8", optional = true }
2626
# Needed for the Message trait, among others
2727
rosidl_runtime_rs = "0.4"
2828

29+
[dependencies.builtin_interfaces]
30+
version = "*"
31+
2932
[dev-dependencies]
3033
# Needed for e.g. writing yaml files in tests
3134
tempfile = "3.3.0"

rclrs/src/time.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::rcl_bindings::*;
2+
use std::num::TryFromIntError;
23
use std::ops::{Add, Sub};
34
use std::sync::{Mutex, Weak};
45
use std::time::Duration;
@@ -23,6 +24,17 @@ impl Time {
2324
.ptr_eq(&rhs.clock)
2425
.then(|| f(self.nsec, rhs.nsec))
2526
}
27+
28+
/// Convenience function for converting time to ROS message
29+
pub fn to_ros_msg(&self) -> Result<builtin_interfaces::msg::Time, TryFromIntError> {
30+
let nanosec = self.nsec % 1_000_000_000;
31+
let sec = self.nsec / 1_000_000_000;
32+
33+
Ok(builtin_interfaces::msg::Time {
34+
nanosec: nanosec.try_into()?,
35+
sec: sec.try_into()?,
36+
})
37+
}
2638
}
2739

2840
impl Add<Duration> for Time {
@@ -84,4 +96,17 @@ mod tests {
8496
let t3 = t2 - Duration::from_secs(1);
8597
assert_eq!(t3.nsec, t.nsec);
8698
}
99+
100+
#[test]
101+
fn test_conversion() {
102+
let clock = Clock::system();
103+
let t1 = clock.now();
104+
let time = Time {
105+
nsec: 1_000_000_100,
106+
clock: t1.clock.clone(),
107+
};
108+
let msg = time.to_ros_msg().unwrap();
109+
assert_eq!(msg.nanosec, 100);
110+
assert_eq!(msg.sec, 1);
111+
}
87112
}

0 commit comments

Comments
 (0)