Reputation: 1
I use a subscriber to receive message from mavros and hope to get values from subscriber callback that used to modify private class variables
class MavrosListener
{
private:
geometry_msgs::Vector3 position;
public:
void Listen_From_MAVROS_Callback(const mavros_msgs::DRONESENSOR::ConstPtr& dronesensor);
void Print_Variables();
};
//Callback definition
void MavrosListener::Listen_From_MAVROS_Callback(const mavros_msgs::DRONESENSOR::ConstPtr& dronesensor)
{
position.x = (dronesensor -> position)[0];
}
void MavrosListener::Print_Variables() {
std::cout << "x position: " << position.x << std::endl;
}
//manipulator
int main(int argc, char **argv)
{
ros::init(argc, argv, "GeoCtrlListener");
ros::NodeHandle n;
MavrosListener listener;
ros::Subscriber Sub_From_Mavros =
n.subscribe("/mavros/odroid/odroid_input", 1, &MavrosListener::Listen_From_MAVROS_Callback, &listener);
listener.Print_Variables();
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 attributes 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 modified or not. I need to store the data from callback function and makes some manipulation and then publish back to another topic.
Any suggestions? Thank you so much.
Upvotes: 0
Views: 123
Reputation: 4843
You're creating a subscriber and then immediately printing the variable it's supposed to modify. This leaves virtually no time for the subscriber to actually be called and modify the variable. Instead you should give enough time for the subscriber to be called before printing the variable.
As well, in roscpp
the spin()
method is what actually breaks and allows time for callbacks to execute. You either need to use ros::spinOnce()
in a loop or ros::spin()
as a blocker for your main thread.
Upvotes: 0