Robotics StackExchange | Archived questions

Use subscriber callback to modify class attributes

Hi, I am new to ROS, and I am encountering a weird issue currently. Any help would be greatly appreciate. I use a subscriber to receive message from mavros and hope to get values from subscriber callback that used to modify private class variables. Here is my code:

class Listener{
    private:
       geometry_msgs::Vector3 position;
    public:
       void Listen_From_MAVROS_Callback(const mavros_msgs::DRONESENSOR::ConstPtr& dronesensor);
       void Print_Variables();
}
void Listener::Listen_From_MAVROS_Callback(const mavros_msgs::DRONESENSOR::ConstPtr& dronesensor)
{
      position.x = (dronesensor -> position)[0];
 }
void Listener::Print_Variables() {
     std::cout << "x position: " << position.x << std::endl;
}
int main(int argc, char **argv){
    ros::init(argc, argv, "GeoCtrlListener");
   ros::NodeHandle n;
   Listener listener;
   ros::Subscriber Sub_From_Mavros = n.subscribe("/mavros/odroid/odroid_input", 1, 
   &Listener::Listen_From_MAVROS_Callback, &listener);
  listener.Print_Variables();
   ros::spin();
  std::cout << "connection end" << std::endl;
 listener.Print_Variables();
return 0
}

For the code above when I run it, the print statement before spin() all returns 0, meaning no attibutes is modified. However, when I press ctrl c and end the connection, the console returns the correct value. I am so confused whether my object listener is correctly mofidied or not. I need to store the data from callback function and makes some manipulation and then publish back to another topic. Ayn suggestions? Thank you so much

Asked by Junjie_Gao on 2023-07-30 18:10:56 UTC

Comments

Answers

Hi!

The code you posted should print 0 one time (right before calling ros::spin()). The main is then "stuck" (find a better description of how spin works in the docs) at the spin line, your callback is executed on message arrival and the value is correctly stored in the class attribute. This is confirmed by the fact that the last print returns the value you are expecting.

What behavior did you expect instead?

Asked by bluegiraffe-sc on 2023-07-31 09:13:42 UTC

Comments

Hi, so this is the problem with print statement right? If so, should I put subscriber in the class constructor instead? Is there any way I could check the class attributes with continuous changes on message arrival? Since I also try to put to publisher in the spin loop and when I echo it, the values are still all zeros.

Asked by Junjie_Gao on 2023-07-31 13:21:14 UTC

Can you edit the question adding this alternative solution?

Asked by bluegiraffe-sc on 2023-08-01 02:48:31 UTC