Creating pub/sub to ROS2 node spinning in a thread
Hi everyone I'm trying to migrate this project I had from ROS to ROS2 and I'm having a problem creating pub/sub to my node spinning a thread, I have this function runRosnode() where I create the node then rosMain() will spin the node on a thread so it doesn't stop the code from executing, getROSNode() returns the node so I can eventually call it and create pub/sub in other cpp files. My problem is that I can't create any pub/sub outside of the rosMain() function where before (in ROS) this approach was working, I don't get any compilation errors but the pub/sub created outside of rosMain() don't show with
ros2 topic list
while the ones created inside rosMain() work as intended, anyone has any idea on why this is the case and how I can solve it ? Thanks in advance
rclcpp::Node::SharedPtr & ROSOMNeT::getROSNode() {
return rosNode;
}
void ROSOMNeT::runROSNode() {
cout << "Running ROS2 node" << endl;
rclcpp::init(0, nullptr);
rosNode = std::make_shared<rclcpp::Node>("ROS2OMNeT");
//these do not work
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher__ =
getROSNode()->create_publisher<std_msgs::msg::String>("topic2", 10);
auto subscription_ = getROSNode()->create_subscription<std_msgs::msg::String>(
"topic2", 10, std::bind(&ROSOMNeT::topic_callback, this, _1));
rosThread = new thread(&ROSOMNeT::rosMain, this);
/* old ROS code that used to work
cout << "Running ROS node" << endl;
init(M_string(), "ROSOMNeT");
rosNode = new NodeHandle();
rosThread = new thread(&ROSOMNeT::rosMain, this);*/
}
void ROSOMNeT::topic_callback(const std_msgs::msg::String::SharedPtr msg)
{
cout<<( "I heard: '%s'", msg->data.c_str());
}
void ROSOMNeT::rosMain() {
cout << "ROS Main spinning on ROS" << endl;
//these work
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_ =
getROSNode()->create_publisher<std_msgs::msg::String>("topic1", 10);
auto subscription_ = getROSNode()->create_subscription<std_msgs::msg::String>(
"topic", 10, std::bind(&ROSOMNeT::topic_callback, this, _1));
rclcpp::spin(getROSNode());
}
Maybe not a relevant question, but why do you not let
ROSOMNeT
inherit fromNode
, but instead create a ros1nodehandler
workaround?As I mentioned the goal is to able to create pub/sub in other files (so I can use their methods as callbacks) so this approach was perfect as I could just create a
ROSOMNeT
obj and callgetROSNode()
in the other files something like thisauto subscription_ = rosomnet.getROSNode()->create_subscription<std_msgs::msg::String>( "topic", 10, std::bind(&MyOtherClass::MyOtherClassMethod, this, _1));
and this used to work with ROS but now that I'm trying to switch to ROS2 it doesn't.now if I was to try and accomplish this by making my node through a class that inherits from
Node
how would I use my other class method as CallBacks for the subs and how would I create pubs in other classes (outside of the node one ?)