-
Notifications
You must be signed in to change notification settings - Fork 127
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor spin and spin_once to mimic rclcpp's Executor API (#324)
* Added rclcpp/rclpy-like executor * Fix comments
- Loading branch information
Showing
6 changed files
with
187 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
use std::env; | ||
use std::sync::atomic::{AtomicU32, Ordering}; | ||
use std::sync::{Arc, Mutex}; | ||
|
||
use anyhow::{Error, Result}; | ||
|
||
struct MinimalSubscriber { | ||
num_messages: AtomicU32, | ||
node: Arc<rclrs::Node>, | ||
subscription: Mutex<Option<Arc<rclrs::Subscription<std_msgs::msg::String>>>>, | ||
} | ||
|
||
impl MinimalSubscriber { | ||
pub fn new(name: &str, topic: &str) -> Result<Arc<Self>, rclrs::RclrsError> { | ||
let context = rclrs::Context::new(env::args())?; | ||
let node = rclrs::create_node(&context, name)?; | ||
let minimal_subscriber = Arc::new(MinimalSubscriber { | ||
num_messages: 0.into(), | ||
node, | ||
subscription: None.into(), | ||
}); | ||
|
||
let minimal_subscriber_aux = Arc::clone(&minimal_subscriber); | ||
let subscription = minimal_subscriber | ||
.node | ||
.create_subscription::<std_msgs::msg::String, _>( | ||
topic, | ||
rclrs::QOS_PROFILE_DEFAULT, | ||
move |msg: std_msgs::msg::String| { | ||
minimal_subscriber_aux.callback(msg); | ||
}, | ||
)?; | ||
*minimal_subscriber.subscription.lock().unwrap() = Some(subscription); | ||
Ok(minimal_subscriber) | ||
} | ||
|
||
fn callback(&self, msg: std_msgs::msg::String) { | ||
self.num_messages.fetch_add(1, Ordering::SeqCst); | ||
println!("[{}] I heard: '{}'", self.node.name(), msg.data); | ||
println!( | ||
"[{}] (Got {} messages so far)", | ||
self.node.name(), | ||
self.num_messages.load(Ordering::SeqCst) | ||
); | ||
} | ||
} | ||
|
||
fn main() -> Result<(), Error> { | ||
let publisher_context = rclrs::Context::new(env::args())?; | ||
let publisher_node = rclrs::create_node(&publisher_context, "minimal_publisher")?; | ||
|
||
let subscriber_node_one = MinimalSubscriber::new("minimal_subscriber_one", "topic")?; | ||
let subscriber_node_two = MinimalSubscriber::new("minimal_subscriber_two", "topic")?; | ||
|
||
let publisher = publisher_node | ||
.create_publisher::<std_msgs::msg::String>("topic", rclrs::QOS_PROFILE_DEFAULT)?; | ||
|
||
std::thread::spawn(move || -> Result<(), rclrs::RclrsError> { | ||
let mut message = std_msgs::msg::String::default(); | ||
let mut publish_count: u32 = 1; | ||
loop { | ||
message.data = format!("Hello, world! {}", publish_count); | ||
println!("Publishing: [{}]", message.data); | ||
publisher.publish(&message)?; | ||
publish_count += 1; | ||
std::thread::sleep(std::time::Duration::from_millis(500)); | ||
} | ||
}); | ||
|
||
let executor = rclrs::SingleThreadedExecutor::new(); | ||
|
||
executor.add_node(&publisher_node)?; | ||
executor.add_node(&subscriber_node_one.node)?; | ||
executor.add_node(&subscriber_node_two.node)?; | ||
|
||
executor.spin().map_err(|err| err.into()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
use crate::rcl_bindings::rcl_context_is_valid; | ||
use crate::{Node, RclReturnCode, RclrsError, WaitSet}; | ||
use std::sync::{Arc, Mutex, Weak}; | ||
use std::time::Duration; | ||
|
||
/// Single-threaded executor implementation. | ||
pub struct SingleThreadedExecutor { | ||
nodes_mtx: Mutex<Vec<Weak<Node>>>, | ||
} | ||
|
||
impl Default for SingleThreadedExecutor { | ||
fn default() -> Self { | ||
Self::new() | ||
} | ||
} | ||
|
||
impl SingleThreadedExecutor { | ||
/// Creates a new executor. | ||
pub fn new() -> Self { | ||
SingleThreadedExecutor { | ||
nodes_mtx: Mutex::new(Vec::new()), | ||
} | ||
} | ||
|
||
/// Add a node to the executor. | ||
pub fn add_node(&self, node: &Arc<Node>) -> Result<(), RclrsError> { | ||
{ self.nodes_mtx.lock().unwrap() }.push(Arc::downgrade(node)); | ||
Ok(()) | ||
} | ||
|
||
/// Remove a node from the executor. | ||
pub fn remove_node(&self, node: Arc<Node>) -> Result<(), RclrsError> { | ||
{ self.nodes_mtx.lock().unwrap() } | ||
.retain(|n| !n.upgrade().map(|n| Arc::ptr_eq(&n, &node)).unwrap_or(false)); | ||
Ok(()) | ||
} | ||
|
||
/// Polls the nodes for new messages and executes the corresponding callbacks. | ||
/// | ||
/// This function additionally checks that the context is still valid. | ||
pub fn spin_once(&self, timeout: Option<Duration>) -> Result<(), RclrsError> { | ||
for node in { self.nodes_mtx.lock().unwrap() } | ||
.iter() | ||
.filter_map(Weak::upgrade) | ||
.filter(|node| unsafe { rcl_context_is_valid(&*node.rcl_context_mtx.lock().unwrap()) }) | ||
{ | ||
let wait_set = WaitSet::new_for_node(&node)?; | ||
let ready_entities = wait_set.wait(timeout)?; | ||
|
||
for ready_subscription in ready_entities.subscriptions { | ||
ready_subscription.execute()?; | ||
} | ||
|
||
for ready_client in ready_entities.clients { | ||
ready_client.execute()?; | ||
} | ||
|
||
for ready_service in ready_entities.services { | ||
ready_service.execute()?; | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
|
||
/// Convenience function for calling [`SingleThreadedExecutor::spin_once`] in a loop. | ||
pub fn spin(&self) -> Result<(), RclrsError> { | ||
while !{ self.nodes_mtx.lock().unwrap() }.is_empty() { | ||
match self.spin_once(None) { | ||
Ok(_) | ||
| Err(RclrsError::RclError { | ||
code: RclReturnCode::Timeout, | ||
.. | ||
}) => (), | ||
error => return error, | ||
} | ||
} | ||
|
||
Ok(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters