Ask Your Question
0

How to structure a node to publish a topic using classes? [closed]

asked 2014-08-05 00:30:33 -0600

Luis Ruiz gravatar image

updated 2016-03-18 07:30:36 -0600

I am writing a node but I have some doubts of how to structure it if I am using classes. Right now I have written two methods. The first one is:

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
class node_class
{
public:
    node_class();
private:
    ros::NodeHandle nh_;
    ros::Publisher pub_;
    std_msgs::String msg;
    ros::Rate loop_rate;
};
node_class::node_class():
    pub_(nh_.advertise<std_msgs::String>("chatter", 10)),
    loop_rate(1)
{
    msg.data = "hello world";
    while(ros::ok())
    {
        pub_.publish(msg);
        loop_rate.sleep();
    }
}
int main(int argc, char **argv)
{
    ros::init(argc, argv, "node_class");
    node_class this_node;
    while(ros::ok())
        ros::spinOnce();
    return 0;
}

In this one the loop is done inside the constructor, but I have my doubts about it. Also the ros::ok() is checked twice. And the second method is:

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
class node_class
{
public:
    node_class();
    void loop_function();
private:
    ros::NodeHandle nh_;
    ros::Publisher pub_;
    std_msgs::String msg;
    ros::Rate loop_rate;
};
node_class::node_class():
    pub_(nh_.advertise<std_msgs::String>("chatter", 10)),
    loop_rate(1)
{
    msg.data = "hello world";
}
void node_class::loop_function()
{
    pub_.publish(msg);
    loop_rate.sleep();
}
int main(int argc, char **argv)
{
    ros::init(argc, argv, "node_class");
    node_class this_node;
    while(ros::ok())
    {
        this_node.loop_function();
        ros::spinOnce();
    }
    return 0;
}

Here I am using a loop_function from the class to be executed in the main while loop. Both methods work but, are there other methods or best practices to do this?

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by Luis Ruiz
close date 2014-08-06 01:49:11.604201

1 Answer

Sort by ยป oldest newest most voted
2

answered 2014-08-05 02:49:52 -0600

BennyRe gravatar image

Definitely the second one!

In the first one your doing an infinite loop inside a constructor, which is in my eyes really bad.

Also the ros::ok() is checked twice.

No it isn't. The ros::ok() call in the main method is being called exactly one time, namely when you hit Ctrl + C and your infinite loop in the constructor exits.

For the future have a look at the ros::spin() method also.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2014-08-05 00:30:33 -0600

Seen: 1,214 times

Last updated: Mar 18 '16