ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Issue with subscriber callback as publihser

asked 2018-03-13 17:53:42 -0600

hagm gravatar image

updated 2018-03-13 19:08:46 -0600

Using the code prototype shown here

I wrote the following code:

#include <ros/ros.h>
#include <std_msgs/Int16.h>

class SubscribeAndPublish
{
public:
    SubscribeAndPublish()
    {
        pub = nh.advertise<std_msgs::Int16>("same_topic",1);
        sub = nh.subscribe<std_msgs::Int16>("same_topic",1,&SubscribeAndPublish::callback,this);
    }
    void callback(const std_msgs::Int16::ConstPtr& msg) 
    {
        ROS_INFO("I heard this data: [%d]", msg->data);
        std_msgs::Int16 msg_p;
        msg_p.data = msg->data;
        ROS_INFO_STREAM(" I got some data");
        pub.publish(msg_p);
    }
    private:
        ros::NodeHandle nh;
        ros::Publisher pub;
        ros::Subscriber sub;

};

int main(int argc, char **argv){
    ros::init(argc,argv,"node");
    SubscribeAndPublish ps;
    ros::spin();
    return 0;
}

When I executes the code, it is waiting (for input) and I gave some integers as follows

12
123324
 43534
23452345
342
153
5234

The program is not printing anything and still waits for input, but when I kill the node, (only) numbers are printing on command lines.

Why the program is not working as expected? where I went wrong?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2018-03-13 19:20:38 -0600

lucasw gravatar image

updated 2018-03-13 19:22:46 -0600

Your callback is publishing on the same topic it is listening on, so the first time it receives anything it will publish and trigger it self forever:

[[/node] :[17] [ I got some data]
[[/node] :[14] [I heard this data: [0]]
[[/node] :[17] [ I got some data]
[[/node] :[14] [I heard this data: [0]]
[[/node] :[17] [ I got 
...

It prints out fine on my system, but maybe yours can't keep up with it?

rostopic hz /same_topic
subscribed to [/same_topic]
average rate: 18782.57

(!)

The queue size is just one so only randomly can a competing publisher inject a message into the infinite loop, it has to beat the self published message into the queue.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2018-03-13 17:53:42 -0600

Seen: 153 times

Last updated: Mar 13 '18