Giter Site home page Giter Site logo

Support for Bevy about ros2_rust HOT 7 OPEN

TanJunKiat avatar TanJunKiat commented on July 20, 2024
Support for Bevy

from ros2_rust.

Comments (7)

Yadunund avatar Yadunund commented on July 20, 2024

Hi there!

I've been using ros2_rust along with bevy (although v0.11) without much problems.

Here's how I integrate ROS 2 interfaces within my bevy application:

  1. I have a dedicated startup plugin that initializes a bevy Resource which is a struct that bundles an rclrs::Context and an Arc<rclrs::Node>. A Default trait for this resource is defined which instantiates the context and node. The same plugin also adds a system which retrieves the above resource, checks if the context is okay and if so, calls rclrs::spin_once() with a clone of the node.
  2. In plugins where I need to define, pub/sub/client/services, I define a bevy Component struct with the corresponding rclrs entity. Then, there are systems that query for the Resource above, initialize the component using the node from the resource, and finally insert the component into the entities.

Hope that helps!

from ros2_rust.

TanJunKiat avatar TanJunKiat commented on July 20, 2024
use bevy::prelude::*;
use std::sync::{Arc, Mutex};
use std_msgs::msg::String as StringMsg;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugins(NodePlugin)
        .add_systems(Startup, setup)
        .add_systems(Update,print_string)
        .run();
}

fn setup() {
    eprintln!("Bevy initialized.");
}

fn print_string(
    string_node: ResMut<NodeSetting>,
) {
    let s = string_node.data.clone().lock().unwrap().clone().unwrap();
    eprintln!("{}",&s.data);
    eprintln!("Received string.");
}

pub struct NodePlugin;

#[derive(Resource)]
struct NodeSetting {
    node: Arc<rclrs::Node>,
    _subscription: Arc<rclrs::Subscription<StringMsg>>,
    data: Arc<Mutex<Option<StringMsg>>>,
}

impl Plugin for NodePlugin {
    fn build (&self, app: &mut App){
        let context = rclrs::Context::new(std::env::args()).unwrap();
        let node = rclrs::Node::new(&context, "republisher").unwrap();
        let data = Arc::new(Mutex::new(None));
        let data_cb = Arc::clone(&data);
        let string_node = NodeSetting {
            node: node.clone(),
            data: data.clone(),
            _subscription: node.create_subscription(
                "in_topic",
                rclrs::QOS_PROFILE_DEFAULT,
                move |msg: StringMsg| {
                    *data_cb.lock().unwrap() = Some(msg);  // (4)
                },
            ).unwrap(),
        };
        
        app.insert_resource(string_node)
        .add_systems(Update, spin_node)
        .insert_resource(Time::<Fixed>::from_hz(1.0));
    }
}

fn spin_node(string_node: ResMut<NodeSetting>){
    eprintln!("spinning node ");
    rclrs::spin_once(string_node.node.clone(),None).unwrap();
    eprintln!("exit node ");
}

from ros2_rust.

TanJunKiat avatar TanJunKiat commented on July 20, 2024

@Yadunund thanks for the support.

I tried to create a simple test code to try out what you suggested.

Not sure did I understood the recommendation correctly but my Bevy still gets stuck after the node was spun once.

from ros2_rust.

mxgrey avatar mxgrey commented on July 20, 2024

Is it stuck inside the spin_once or elsewhere? I'd recommend putting a sensible timeout in the spin_once.

from ros2_rust.

mxgrey avatar mxgrey commented on July 20, 2024

Instead of transferring the subscription data using an Arc<Mutex<Option<T>>> I would recommend creating a mpsc channel. Give the sender to your subscription callback and store the receiver in your resource.

Your subscription callback would simply pass the messages into the sender. Your print_string system would drain the receiver using try_recv.

from ros2_rust.

TanJunKiat avatar TanJunKiat commented on July 20, 2024
use bevy::prelude::*;
use std::{sync::{Arc, Mutex}, time::Duration};
use std_msgs::msg::String as StringMsg;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugins(NodePlugin)
        .add_systems(Startup, setup)
        .add_systems(Update,print_string)
        .run();
}

fn setup() {
    eprintln!("Bevy initialized.");
}

fn print_string(
    string_node: ResMut<NodeSetting>,
) {
    let guard = string_node.data.lock().unwrap();
    if guard.as_ref() != None{   
        let info = guard.as_ref().unwrap();
        eprintln!("Bevy got message: {}",&info.data);
    }
}

pub struct NodePlugin;

#[derive(Resource)]
struct NodeSetting {
    node: Arc<rclrs::Node>,
    _subscription: Arc<rclrs::Subscription<StringMsg>>,
    data: Arc<Mutex<Option<StringMsg>>>,
}

impl Plugin for NodePlugin {
    fn build (&self, app: &mut App){
        let context = rclrs::Context::new(std::env::args()).unwrap();
        let node = rclrs::Node::new(&context, "republisher").unwrap();
        let data = Arc::new(Mutex::new(None));
        let data_cb = Arc::clone(&data);
        let string_node = NodeSetting {
            node: node.clone(),
            data: data.clone(),
            _subscription: node.create_subscription(
                "in_topic",
                rclrs::QOS_PROFILE_DEFAULT,
                move |msg: StringMsg| {
                    eprintln!("Node received message: {}",msg.data);
                    *data_cb.lock().unwrap() = Some(msg);  // (4)
                },
            ).unwrap(),
        };
        
        app.insert_resource(string_node)
        .add_systems(Update, spin_node)
        .insert_resource(Time::<Fixed>::from_hz(1.0));
    }
}

fn spin_node(string_node: ResMut<NodeSetting>){
    eprintln!("Entering node ");
    let _action = rclrs::spin_once(string_node.node.clone(),Some(Duration::new(1, 0)));
    eprintln!("Exiting node ");
}

from ros2_rust.

TanJunKiat avatar TanJunKiat commented on July 20, 2024

@mxgrey @Yadunund Awesome guys.

Thank you so much for the help.

I managed to get the message on the bevy resource struct and bevy can print the string as it receives it.

from ros2_rust.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.