Skip to content

Commit

Permalink
Update examples
Browse files Browse the repository at this point in the history
Signed-off-by: Michael X. Grey <greyxmike@gmail.com>
  • Loading branch information
mxgrey committed Dec 9, 2024
1 parent 1f1d826 commit 6d3f7e4
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 60 deletions.
30 changes: 14 additions & 16 deletions examples/minimal_client_service/src/minimal_client.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,32 @@
use anyhow::{Error, Result};
use rclrs::{Context, SpinOptions, Promise};

fn main() -> Result<(), Error> {
let mut executor = rclrs::Context::default_from_env()?.create_basic_executor();
let mut executor = Context::default_from_env()?.create_basic_executor();

let node = executor.create_node("minimal_client")?;

let client = node.create_client::<example_interfaces::srv::AddTwoInts>("add_two_ints")?;

let request = example_interfaces::srv::AddTwoInts_Request { a: 41, b: 1 };

println!("Starting client");

while !client.service_is_ready()? {
std::thread::sleep(std::time::Duration::from_millis(10));
}

client.async_send_request_with_callback(
&request,
move |response: example_interfaces::srv::AddTwoInts_Response| {
println!(
"Result of {} + {} is: {}",
request.a, request.b, response.sum
);
},
)?;
let request = example_interfaces::srv::AddTwoInts_Request { a: 41, b: 1 };

let response: Promise<example_interfaces::srv::AddTwoInts_Response> = client.call(&request).unwrap();

std::thread::sleep(std::time::Duration::from_millis(500));
let promise = executor.commands().run(async move {
let response = response.await.unwrap();
println!(
"Result of {} + {} is: {}",
request.a, request.b, response.sum,
);
});

println!("Waiting for response");
executor
.spin(rclrs::SpinOptions::default())
.map_err(|err| err.into())
executor.spin(SpinOptions::new().until_promise_resolved(promise))?;
Ok(())
}
28 changes: 13 additions & 15 deletions examples/minimal_client_service/src/minimal_client_async.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use anyhow::{Error, Result};
use rclrs::{Context, SpinOptions};

#[tokio::main]
async fn main() -> Result<(), Error> {
let mut executor = rclrs::Context::default_from_env()?.create_basic_executor();
fn main() -> Result<(), Error> {
let mut executor = Context::default_from_env()?.create_basic_executor();

let node = executor.create_node("minimal_client")?;

Expand All @@ -16,19 +16,17 @@ async fn main() -> Result<(), Error> {

let request = example_interfaces::srv::AddTwoInts_Request { a: 41, b: 1 };

let future = client.call_async(&request);
let promise = client.call_then(
&request,
move |response: example_interfaces::srv::AddTwoInts_Response| {
println!(
"Result of {} + {} is: {}",
request.a, request.b, response.sum,
);
}
).unwrap();

println!("Waiting for response");

let rclrs_spin =
tokio::task::spawn_blocking(move || executor.spin(rclrs::SpinOptions::default()));

let response = future.await?;
println!(
"Result of {} + {} is: {}",
request.a, request.b, response.sum
);

rclrs_spin.await.ok();
executor.spin(SpinOptions::new().until_promise_resolved(promise))?;
Ok(())
}
17 changes: 11 additions & 6 deletions examples/minimal_client_service/src/minimal_service.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
use anyhow::{Error, Result};
use rclrs::{Context, ServiceInfo, SpinOptions};

fn handle_service(
_request_header: &rclrs::rmw_request_id_t,
request: example_interfaces::srv::AddTwoInts_Request,
info: ServiceInfo,
) -> example_interfaces::srv::AddTwoInts_Response {
println!("request: {} + {}", request.a, request.b);
let timestamp = info
.received_timestamp
.map(|t| format!(" at [{t:?}]"))
.unwrap_or(String::new());

println!("request{timestamp}: {} + {}", request.a, request.b);
example_interfaces::srv::AddTwoInts_Response {
sum: request.a + request.b,
}
}

fn main() -> Result<(), Error> {
let mut executor = rclrs::Context::default_from_env()?.create_basic_executor();
let mut executor = Context::default_from_env()?.create_basic_executor();

let node = executor.create_node("minimal_service")?;

let _server = node
.create_service::<example_interfaces::srv::AddTwoInts, _>("add_two_ints", handle_service)?;

println!("Starting server");
executor
.spin(rclrs::SpinOptions::default())
.map_err(|err| err.into())
executor.spin(SpinOptions::default())?;
Ok(())
}
18 changes: 10 additions & 8 deletions examples/minimal_pub_sub/src/minimal_subscriber.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
use anyhow::{Error, Result};
use std::sync::Mutex;
use rclrs::{Context, SpinOptions};

fn main() -> Result<(), Error> {
let context = rclrs::Context::default_from_env()?;
let context = Context::default_from_env()?;
let mut executor = context.create_basic_executor();

let node = executor.create_node("minimal_subscriber")?;

let mut num_messages: usize = 0;

let num_messages = Mutex::new(0usize);
let _subscription = node.create_subscription::<std_msgs::msg::String, _>(
"topic",
move |msg: std_msgs::msg::String| {
num_messages += 1;
let mut num = num_messages.lock().unwrap();
*num += 1;
println!("I heard: '{}'", msg.data);
println!("(Got {} messages so far)", num_messages);
println!("(Got {} messages so far)", num);
},
)?;

executor
.spin(rclrs::SpinOptions::default())
.map_err(|err| err.into())
println!("Waiting for messages...");
executor.spin(SpinOptions::default())?;
Ok(())
}
16 changes: 9 additions & 7 deletions examples/minimal_pub_sub/src/zero_copy_subscriber.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
use anyhow::{Error, Result};
use std::sync::Mutex;
use rclrs::ReadOnlyLoanedMessage;

fn main() -> Result<(), Error> {
let mut executor = rclrs::Context::default_from_env()?.create_basic_executor();

let node = executor.create_node("minimal_subscriber")?;

let mut num_messages: usize = 0;
let num_messages = Mutex::new(0usize);

let _subscription = node.create_subscription::<std_msgs::msg::UInt32, _>(
"topic",
move |msg: rclrs::ReadOnlyLoanedMessage<'_, std_msgs::msg::UInt32>| {
num_messages += 1;
move |msg: ReadOnlyLoanedMessage<std_msgs::msg::UInt32>| {
let mut num = num_messages.lock().unwrap();
*num += 1;
println!("I heard: '{}'", msg.data);
println!("(Got {} messages so far)", num_messages);
println!("(Got {} messages so far)", *num);
},
)?;

executor
.spin(rclrs::SpinOptions::default())
.map_err(|err| err.into())
executor.spin(rclrs::SpinOptions::default())?;
Ok(())
}
6 changes: 3 additions & 3 deletions examples/rust_pubsub/src/simple_publisher.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use rclrs::{Context, Executor, Publisher, RclrsError, SpinOptions, QOS_PROFILE_DEFAULT};
use std::{sync::Arc, thread, time::Duration};
use rclrs::{Context, Executor, Publisher, RclrsError, SpinOptions};
use std::{thread, time::Duration};
use std_msgs::msg::String as StringMsg;

struct SimplePublisherNode {
Expand All @@ -26,7 +26,7 @@ impl SimplePublisherNode {

fn main() -> Result<(), RclrsError> {
let mut executor = Context::default_from_env().unwrap().create_basic_executor();
let node = Arc::new(SimplePublisher::new(&executor).unwrap());
let node = SimplePublisherNode::new(&executor).unwrap();
let mut count: i32 = 0;
thread::spawn(move || loop {
thread::sleep(Duration::from_millis(1000));
Expand Down
11 changes: 6 additions & 5 deletions examples/rust_pubsub/src/simple_subscriber.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use rclrs::{Context, Executor, RclrsError, SpinOptions, Subscription, QOS_PROFILE_DEFAULT};
use rclrs::{Context, Executor, RclrsError, SpinOptions, Subscription};
use std::{
sync::{Arc, Mutex},
thread,
Expand All @@ -7,7 +7,8 @@ use std::{
use std_msgs::msg::String as StringMsg;

pub struct SimpleSubscriptionNode {
_subscriber: Arc<Subscription<StringMsg>>,
#[allow(unused)]
subscriber: Subscription<StringMsg>,
data: Arc<Mutex<Option<StringMsg>>>,
}

Expand All @@ -16,15 +17,15 @@ impl SimpleSubscriptionNode {
let node = executor.create_node("simple_subscription").unwrap();
let data: Arc<Mutex<Option<StringMsg>>> = Arc::new(Mutex::new(None));
let data_mut: Arc<Mutex<Option<StringMsg>>> = Arc::clone(&data);
let _subscriber = node
let subscriber = node
.create_subscription::<StringMsg, _>(
"publish_hello",
move |msg: StringMsg| {
*data_mut.lock().unwrap() = Some(msg);
},
)
.unwrap();
Ok(Self { _subscriber, data })
Ok(Self { subscriber, data })
}
fn data_callback(&self) -> Result<(), RclrsError> {
if let Some(data) = self.data.lock().unwrap().as_ref() {
Expand All @@ -37,7 +38,7 @@ impl SimpleSubscriptionNode {
}
fn main() -> Result<(), RclrsError> {
let mut executor = Context::default_from_env().unwrap().create_basic_executor();
let node = Arc::new(SimpleSubscriptionNode::new(&executor).unwrap());
let node = SimpleSubscriptionNode::new(&executor).unwrap();
thread::spawn(move || loop {
thread::sleep(Duration::from_millis(1000));
node.data_callback().unwrap()
Expand Down

0 comments on commit 6d3f7e4

Please sign in to comment.