From 7155fc2c5f892b6d1e4d21ffa4c36cd63365d9b9 Mon Sep 17 00:00:00 2001 From: AlexKaravaev Date: Sat, 17 Sep 2022 23:02:16 +0200 Subject: [PATCH] Add publisher with member function example --- examples/minimal_pub_sub/Cargo.toml | 4 ++ .../src/publisher_member_function.rs | 59 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 examples/minimal_pub_sub/src/publisher_member_function.rs diff --git a/examples/minimal_pub_sub/Cargo.toml b/examples/minimal_pub_sub/Cargo.toml index 821c11305..2316573c2 100644 --- a/examples/minimal_pub_sub/Cargo.toml +++ b/examples/minimal_pub_sub/Cargo.toml @@ -21,6 +21,10 @@ path = "src/zero_copy_subscriber.rs" name = "zero_copy_publisher" path = "src/zero_copy_publisher.rs" +[[bin]] +name = "publisher_member_function" +path = "src/publisher_member_function.rs" + [dependencies] anyhow = {version = "1", features = ["backtrace"]} diff --git a/examples/minimal_pub_sub/src/publisher_member_function.rs b/examples/minimal_pub_sub/src/publisher_member_function.rs new file mode 100644 index 000000000..c3a2dcdbf --- /dev/null +++ b/examples/minimal_pub_sub/src/publisher_member_function.rs @@ -0,0 +1,59 @@ +use std::{ + env, + sync::{Arc, Mutex}, + thread, + time::Duration, +}; + +use anyhow::Result; + +struct Publisher { + publisher: Arc>>, + publish_count: Arc>, +} + +unsafe impl Send for Publisher {} + +impl Publisher { + pub fn new(context: &rclrs::Context) -> Self { + let node = rclrs::create_node(context, "publisher").unwrap(); + + let publisher = node + .create_publisher::("topic", rclrs::QOS_PROFILE_DEFAULT) + .unwrap(); + + Self { + publisher: Arc::new(Mutex::new(publisher)), + publish_count: Arc::new(Mutex::new(0)), + } + } + + fn init(&mut self) { + let publish_count = self.publish_count.clone(); + let publisher = self.publisher.clone(); + + thread::spawn(move || loop { + thread::sleep(Duration::from_secs(1)); + + let msg = std_msgs::msg::String { + 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; + }); + } +} + +fn main() -> Result<(), rclrs::RclrsError> { + let context = rclrs::Context::new(env::args())?; + let mut publisher = Publisher::new(&context); + publisher.init(); + while context.ok() { + std::thread::sleep(std::time::Duration::from_millis(100)); + } + Ok(()) +}