Module safe_drive::selector

source ·
Expand description

Selector provides functions like select or epoll. This is used to single threaded execution. For multi threaded execution, this is used internally.

§Example

use safe_drive::{
    context::Context, logger::Logger, msg::common_interfaces::std_msgs, pr_info,
};
use std::time::Duration;

// First of all, you need create a context.
let ctx = Context::new().unwrap();

// Create a subscribe node.
let node_sub = ctx
    .create_node("selector_rs", None, Default::default())
    .unwrap();

// Create a subscriber.
let subscriber = node_sub
    .create_subscriber::<std_msgs::msg::String>("selector_topic", None,
).unwrap();

// Create a selector, which is for IO multiplexing.
let mut selector = ctx.create_selector().unwrap();

// Create a logger.
let logger_sub = Logger::new("selector_rs");

// Add subscriber to the selector.
// The 2nd argument is a callback function.
// If data arrive, the callback will be invoked.
selector.add_subscriber(
    subscriber,
    Box::new(move |msg| {
        // Print the message
        pr_info!(logger_sub, "Received: msg = {}", msg.data); // Print a message.
    }),
);

// Create a wall timer, which invoke the callback periodically.
selector.add_wall_timer(
    "timer_name", // name of the timer
    Duration::from_millis(100),
    Box::new(move || ()),
);

// Spin.
for _ in 0..10 {
    selector.wait().unwrap();
}

Structs§

  • Selector invokes callback functions associated with subscribers, services, timers, or condition variables. Selector cannot send to another thread and shared by multiple threads. So, use this for single threaded execution.