ros2_rust
ros2_rust copied to clipboard
Add publisher with member function example
I thought that it can be quite useful to have this in examples. It's like a mix between one of the rclcpp examples and republisher from tutorial.
What I don't like is that it's still not 100% member function, ideally we would have something like:
fn init(&mut self) {
thread::spawn(move || loop {
self.publish();
});
}
fn publish(&self){
thread::sleep(Duration::from_secs(1));
let mut msg = std_msgs::msg::String::default();
msg.data = format!("Hello, world! {}", publish_count.lock().unwrap());
println!("Publishing: [{}]", msg.data);
publisher.lock().unwrap().publish(msg).unwrap();
let mut num_count = publish_count.lock().unwrap();
*num_count += 1;
}
But then I didn't came up with an elegant solution to that, without any errors on self lifetime.
Hi! This is intended as a port of https://github.com/ros2/examples/blob/rolling/rclcpp/topics/minimal_publisher/member_function.cpp, right?
@nnmm Exactly. For me it was quite tricky actually to write something like that in Rust with ros2, so I thought that having example with that could be helpful to someone else.
@AlexKaravaev thanks a lot for the example! From reading this code, I do wonder how we can make rclrs more suitable for a usecase like this. Perhaps a trait that has a default implementation that standardizes the Node initialization, it'd be similar to how Nodes are created in C++ and that can be used as components.
Something like this:
pub struct Node {}
pub trait ComposableNode {
fn new(node_name: &str) -> Self;
fn init_node(node: &str) -> Node {
// Common initialization
Node {}
}
}
pub struct MinimalPublisher {
node: Node,
}
impl ComposableNode for MinimalPublisher {
fn new(node_name: &str) -> Self {
let composable_node = Self {
node: Self::init_node(&node_name),
};
// do stuff with composable_node
composable_node
}
}
fn main() {
let minimal_publisher = MinimalPublisher::new("mynode");
}
Do you think the addition of a ComposableNode in the rclrs would help here?