|
| 1 | +use std::time::Duration; |
| 2 | + |
| 3 | +use futures::{executor::LocalPool, task::LocalSpawnExt}; |
| 4 | + |
| 5 | +use r2r::{std_msgs::msg, std_srvs::srv, QosProfile}; |
| 6 | + |
| 7 | + |
| 8 | +/// This example demonstrates creation of a service, |
| 9 | +/// subscriber and timers with their callback execution traced. |
| 10 | +fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 11 | + let ctx = r2r::Context::create()?; |
| 12 | + let mut node = r2r::Node::create(ctx, "testnode", "")?; |
| 13 | + |
| 14 | + let mut pool = LocalPool::new(); |
| 15 | + let spawner = pool.spawner(); |
| 16 | + |
| 17 | + // The traced callback is supplied directly to `subscribe_traced` |
| 18 | + // and `create_service_traced`functions. |
| 19 | + let subscriber_future = |
| 20 | + node.subscribe_traced("/print", QosProfile::default(), |msg: msg::String| { |
| 21 | + println!("Received message: '{}'", msg.data); |
| 22 | + })?; |
| 23 | + spawner.spawn_local(subscriber_future)?; |
| 24 | + |
| 25 | + let mut value = false; |
| 26 | + let service_future = node.create_service_traced::<srv::SetBool::Service, _>( |
| 27 | + "/set_value", |
| 28 | + QosProfile::default(), |
| 29 | + move |req| { |
| 30 | + if value == req.message.data { |
| 31 | + req.respond(srv::SetBool::Response { |
| 32 | + success: false, |
| 33 | + message: format!("Value is already {value}."), |
| 34 | + }) |
| 35 | + .expect("could not send service response"); |
| 36 | + } else { |
| 37 | + value = req.message.data; |
| 38 | + req.respond(srv::SetBool::Response { |
| 39 | + success: true, |
| 40 | + message: format!("Value set to {value}."), |
| 41 | + }) |
| 42 | + .expect("could not send service response"); |
| 43 | + } |
| 44 | + }, |
| 45 | + )?; |
| 46 | + spawner.spawn_local(service_future)?; |
| 47 | + |
| 48 | + let mut counter = 0; |
| 49 | + let wall_timer_future = |
| 50 | + node.create_wall_timer(Duration::from_millis(500))? |
| 51 | + .on_tick(move |_| { |
| 52 | + counter += 1; |
| 53 | + println!("Wall timer tick: {counter}"); |
| 54 | + }); |
| 55 | + spawner.spawn_local(wall_timer_future)?; |
| 56 | + |
| 57 | + let ros_timer_future = node.create_timer(Duration::from_secs(1))?.on_tick(|diff| { |
| 58 | + println!("ROS timer tick. Time elapsed since last tick: {diff:?}"); |
| 59 | + }); |
| 60 | + spawner.spawn_local(ros_timer_future)?; |
| 61 | + |
| 62 | + loop { |
| 63 | + node.spin_once(std::time::Duration::from_millis(5)); |
| 64 | + pool.run_until_stalled(); |
| 65 | + } |
| 66 | +} |
0 commit comments