Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions rclrs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ libloading = { version = "0.8", optional = true }
# Needed for the Message trait, among others
rosidl_runtime_rs = "0.4"

[dependencies.builtin_interfaces]
version = "*"

[dev-dependencies]
# Needed for e.g. writing yaml files in tests
tempfile = "3.3.0"
Expand Down
25 changes: 25 additions & 0 deletions rclrs/src/time.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::rcl_bindings::*;
use std::num::TryFromIntError;
use std::ops::{Add, Sub};
use std::sync::{Mutex, Weak};
use std::time::Duration;
Expand All @@ -23,6 +24,17 @@ impl Time {
.ptr_eq(&rhs.clock)
.then(|| f(self.nsec, rhs.nsec))
}

/// Convenience function for converting time to ROS message
pub fn to_ros_msg(&self) -> Result<builtin_interfaces::msg::Time, TryFromIntError> {
let nanosec = self.nsec % 1_000_000_000;
let sec = self.nsec / 1_000_000_000;

Ok(builtin_interfaces::msg::Time {
nanosec: nanosec.try_into()?,
sec: sec.try_into()?,
})
}
}

impl Add<Duration> for Time {
Expand Down Expand Up @@ -84,4 +96,17 @@ mod tests {
let t3 = t2 - Duration::from_secs(1);
assert_eq!(t3.nsec, t.nsec);
}

#[test]
fn test_conversion() {
let clock = Clock::system();
let t1 = clock.now();
let time = Time {
nsec: 1_000_000_100,
clock: t1.clock.clone(),
};
let msg = time.to_ros_msg().unwrap();
assert_eq!(msg.nanosec, 100);
assert_eq!(msg.sec, 1);
}
}