Struct safe_drive::selector::Selector

source ·
pub struct Selector { /* private fields */ }
Expand description

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.

§Example

use safe_drive::context::Context;

let ctx = Context::new().unwrap();
let mut selector = ctx.create_selector(); // Create a new selector.

Implementations§

source§

impl Selector

source

pub fn add_subscriber<T: TypeSupport + 'static>( &mut self, subscriber: Subscriber<T>, handler: Box<dyn FnMut(TakenMsg<T>)>, ) -> bool

Register a subscriber with callback function. The callback function will be invoked when arriving data.

§Error

If a selector takes a subscriber created by a different context, add_subscriber() must fail.

§Example
use safe_drive::{msg::common_interfaces::std_msgs, node::Node, selector::Selector, topic::subscriber::TakenMsg};
use std::sync::Arc;

fn add_new_subscriber(selector: &mut Selector, node: Arc<Node>) {
    // Create a subscriber.
    let subscriber = node.create_subscriber("node_name", None,
    ).unwrap();

    // Add the subscriber with a callback function.
    selector.add_subscriber(
        subscriber,
        Box::new(|msg: TakenMsg<std_msgs::msg::Bool>| /* some tasks */ ()), // Callback function.
    );
}
source

pub fn add_parameter_server( &mut self, param_server: ParameterServer, handler: Box<dyn FnMut(&mut Parameters, BTreeSet<String>)>, )

source

pub fn add_server<T: ServiceMsg + 'static>( &mut self, server: Server<T>, handler: Box<dyn FnMut(<T as ServiceMsg>::Request, Header) -> <T as ServiceMsg>::Response>, ) -> bool

Register a subscriber with callback function. The callback function will be invoked when arriving data.

The callback function must take ServiceMsg::Request and Header and return ServiceMsg::Response.

§Error

If a selector takes a server created by a different context, add_server() must fail.

§Example
use safe_drive::{msg::{common_interfaces::std_srvs, ServiceMsg}, node::Node, selector::Selector};
use std::sync::Arc;

fn add_new_server(selector: &mut Selector, node: Arc<Node>) {
    // Create a server.
    let server = node
        .create_server::<std_srvs::srv::Empty>("select_rs_service", None)
        .unwrap();

    // Add the server with a callback function.
    selector.add_server(
        server,
        Box::new(|request: <std_srvs::srv::Empty as ServiceMsg>::Request, header| {
            // Return the response.
            let response = std_srvs::srv::EmptyResponse::new().unwrap();
            response
        }), // Callback function.
    );
}
source

pub fn add_action_server<T: ActionMsg + 'static, GR, A, CR>( &mut self, server: Server<T>, goal_handler: GR, accept_handler: A, cancel_goal_handler: CR, ) -> bool
where GR: Fn(SendGoalServiceRequest<T>) -> bool + 'static, A: Fn(GoalHandle<T>) + 'static, CR: Fn(&GoalInfo) -> bool + 'static,

Register an action server with a callback. The callback is invoked when requests from action clients arrive.

  • goal_handler is invoked when the action server receives a new goal.
  • cancel_goal_handler is invoked when the action server receives a request to cancel a goal. Requests for goal results are automatically handled.
§Example

fn add_action_server(selector: &mut Selector, server: Server<MyAction>) {
    selector.add_action_server(server,
        // return true to accept the goal
        |req| {
            // do some validation here...
            true
        }
        // executed if accepted
        |handle| {
            // spawn a worker thread
            std::thread::spawn(move || {
                // send a feedback
                let feedback = MyAction_Feedback { c: 4 };
                handle.feedback(feedback).unwrap();

                // send a result when finished
                handle.finish(MyAction_Result { b: 500 }).unwrap();
            });

            true // return true to accept the goal
        },
        /// handler for cancel requests
        |req| { true } // return true to cancel the goal
    );
}
source

pub fn add_timer(&mut self, t: Duration, handler: Box<dyn FnMut()>) -> u64

Add a timer. The handler is called after t seconds later. The handler is called just once.

§Return Value

The identifier of the timer.

§Example
use safe_drive::selector::Selector;
use std::time::Duration;

fn add_new_timer(selector: &mut Selector) {
    // Add a timer.
    selector.add_timer(
        Duration::from_millis(100),
        Box::new(|| /* some tasks */ ()), // Callback function.
    );
}
source

pub fn add_wall_timer( &mut self, name: &str, t: Duration, handler: Box<dyn FnMut()>, ) -> u64

Add a wall timer. The handler is called after t seconds later. The handler will be automatically reloaded after calling it. It means the handler is called periodically.

§Return Value

The identifier of the timer.

§Example
use safe_drive::selector::Selector;
use std::time::Duration;

fn add_new_wall_timer(selector: &mut Selector) {
    // Add a timer.
    selector.add_wall_timer(
        "timer_name",
        Duration::from_millis(100),
        Box::new(|| /* some tasks */ ()), // Callback function.
    );
}
source

pub fn wait_timeout(&mut self, t: Duration) -> Result<bool, DynError>

Wait events and invoke registered callback functions. This function returns after t duration; timeout.

§Return Value
  • Ok(true): Some events has fired
  • Ok(false): Timeout
  • Err(DynError): Error
§Example
use safe_drive::{error::DynError, selector::Selector};

fn wait_events(selector: &mut Selector) -> Result<(), DynError> {
    if selector.wait_timeout(std::time::Duration::from_millis(10))? {
        // Some events has fired.
    } else {
        // Timeout.
    }

    Ok(())
}
source

pub fn remove_timer(&mut self, id: u64)

source

pub fn wait(&mut self) -> Result<(), DynError>

Wait events and invoke registered callback functions.

§Example
use safe_drive::{error::DynError, selector::Selector};

fn wait_events(selector: &mut Selector) -> Result<(), DynError> {
    // Add subscribers, servers, etc.

    // Spin.
    loop {
        selector.wait()?;
    }
}

Trait Implementations§

source§

impl Drop for Selector

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.