Skip to content

[Question] How to use actions in ros2_rust? #607

@drewlwhitney

Description

@drewlwhitney

Hey there!

I'm trying to write an action server in Rust, but it looks like some of the documentation is still in-progress. Could someone help me understand how we do this in Rust? This is what I have so far:

use motor_control_interfaces::action::TestAction;
use rclrs::*;
use std::time::Duration;


fn main() {
    // set up ROS
    let mut executor = Context::default_from_env()
        .expect("Failed to create ROS context")
        .create_basic_executor();
    let node = executor.create_node("test_node").expect("Failed to create node");

    // create action
    let _action = node
        .create_action_server("test_action", async |request: RequestedGoal<TestAction>| {
            let task = request.accept().execute();
            let number_of_prints = task.goal().number_of_prints;
            let terminated_goal = if let Err(_) = task.unless_cancel_requested((async || {
                // print and publish feedback
                for _ in 0..number_of_prints {
                    println!("Running!");
                    task.publish_feedback(?????);
                    tokio::time::sleep(Duration::from_secs(1));
                }
            })()).await {
                // I'm assuming that getting an `Err` means the task was cancelled. Is this correct?
                task.begin_cancelling().cancelled_with(?????)
            } else {
                // I'm assuming that if we got an `Ok`, we were not cancelled. Is that correct?
                task.succeeded_with(?????)
            };

            terminated_goal
        })
        .unwrap();

    println!("Running `test_node`...");

    executor.spin(SpinOptions::default()).first_error().unwrap();
}

Note that I have two closures: one for create_action_server() and one for unless_cancel_requested() (the second one is called immediately to create a future). How do I publish feedback, accept a cancellation, and publish the result? Basically, what do I need to replace the ?????s with in my example? I saw that the TestAction_Result and TestAction_Feedback structs were generated in addition to the TestAction struct. Do I need to construct these manually, or is there another method to create them?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions