Problem with threads and callback
Hi, I would like to create a program that's a subscriber and listener at the same time.
Here my diagram that I made just for this :
My callback is a listener that is initialized with ros::spin() in the beginning of the program (but i'm not sure that's the good one).
When it receives the good message, it will change the value of a boolean. With that modified value it will automaticly stop or continue the publisher.
I have 2 choices :
- The publisher is in a while which is initialized in the beginning of the program (that is to say : i remove ros::spin() in main to write ros::spinOnce() in the while). With a "If", it will stop the publish without exit the while.
- The publisher is in a while inside the callback.
In these two cases, I have one problem : it will never stop the loop (if it's in constructor, it will create an infinite loop, if it's in callback, i don't have any problem with infinite loop if I press CTRL + C). I change the boolean value in the callback, just after received message.
CASE 1 :
void Selectcamera::selectCallback(const std_msgs::String::ConstPtr &msg)
{
if (msg->data == "STOP")
isOk = false;
else
isOk = true;
while (isOk == true) {
cap >> frame;
cvimage = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame).toImageMsg();
pub.publish(cvimage);
cv::waitKey(1);
}
}
void Selectcamera::Selectcamera()
{
ros::init(argc, argv, "selectcamera");
ros::NodeHandle selectcamera;
image_transport::ImageTransport it(camera);
pub = it.advertise("camera", 1);
listcam_subscriber = selectcamera.subscribe("device", 1, &Selectcamera::selectCallback, this);
ros::spin();
}
CASE 2 :
void Selectcamera::selectCallback(const std_msgs::String::ConstPtr &msg)
{
if (msg->data == "STOP")
isOk = false;
else
isOk = true;
}
void Selectcamera::Selectcamera()
{
ros::init(argc, argv, "selectcamera");
ros::NodeHandle selectcamera;
image_transport::ImageTransport it(camera);
pub = it.advertise("camera", 1);
listcam_subscriber = selectcamera.subscribe("device", 1, &Selectcamera::selectCallback, this);
while (ros::ok()) {
if (isOk == true) {
cap >> frame;
cvimage = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame).toImageMsg();
pub.publish(cvimage);
}
cv::waitKey(1);
ros::spinOnce();
}
}
What is the best solution and how can I make it ?
Thanks,