-
Notifications
You must be signed in to change notification settings - Fork 163
Refactor spin and spin_once to mimic rclcpp's Executor API #324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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,79 @@ | ||
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. | ||
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 hidden or 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 hidden or 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 hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.