Robotics StackExchange | Archived questions

Callback not updating class member variable

I have encountered a strange problem. I have a standard class

class A{
public:
 A(ros::NodeHandle& nh){
        sub = nh.subscribe("cmd", 10, &A::cmd_callback, this);
         cmd_received = "none";
 } 
 void cmd_callback(const std_msgs::String::ConstPtr& msg){
        cmd_received = msg->data;
        std::cout<< "cmd received in callback: " << cmd_received << std::endl;
}
 void update(){
   ROS_INFO_STREAM_THROTTLE(2.0, "cmd received: " << cmd_received);
  }
private:
   std::string cmd_received;
   ros::Subscriber sub
};

Now when I send a string message from my python publisher it seems to be correctly received. The print statement in the callback outputs the correct value. However when calling the update function in the main loop, the value of cmd_received is the initial one ("none").

This is seems to be a very subtle bug, normally this kind of structure works great.

Any suggestions are appreciated.

Asked by gpldecha on 2018-11-15 04:49:01 UTC

Comments

We can't really debug this for you without seeing all of your code. Could you post the rest of it.

Asked by PeteBlackerThe3rd on 2018-11-15 05:11:52 UTC

It is part of a larger program which I cannot put here. I detailing the symptoms to see if anyone has encountered something similar. If not, I will find a work around.

Asked by gpldecha on 2018-11-15 05:19:22 UTC

I've tried running this and it works fine on my machine running 16.04 and kinetic. Here's the test code I'm using to test. Can you run it on your machine to confirm that you still see the issue?

Asked by Gary Servin on 2018-11-15 08:54:35 UTC

It's possible you have more than one instance of this class which is causing this bug.

Asked by PeteBlackerThe3rd on 2018-11-15 10:28:36 UTC

Answers