0

I have a ROS Node where i subscribe to a Topic and then publish to another topic on the following way :

#include ...

//Ros Nodehandle + Publisher

//Callback Function definition

int main (int argc, char** argv){
   //Initialisation

   // Pub
   pub = nh->advertise<Messagetype>("Topic2", 1);
 
   //Sub
   ros::Subscriber sub = nh->subscribe("Topic1", 1, sub_cb);

   ros::spin();

   return 0;
}

void sub_cb(){
    //Write the msg i want to publish

    pub.publish(msg);

}

I wanted to publish the message for 15 seconds for example. I tried a solution with Ros::Time and Ros::Duration . But the fact that i have a publisher in my callback function didn't allow me to do that.

Is there a way to do it even is my publish event is in my callback function ? If not, any solution would work, the main thing that my subscriber and my publisher are on the same node.

theone
  • 1
  • 1
  • why not just put in a time-check before the publish and only publish if time is less than 15s since you started the clock? – Christian Fritz Sep 09 '20 at 15:43
  • If i start the clock in the sub_cb() function it shows an error. I think i can do it only in the main. – theone Sep 09 '20 at 15:52
  • is that a problem? – Christian Fritz Sep 09 '20 at 15:57
  • I think I don't get it right with the fact of publishing. I always thought publishing is through "pub.publish(msg);" . So if I want to influence when and how to publish i should make a control statement for "pub.publish(msg);". How to control it from main ? From the defition of the publisher ? – theone Sep 09 '20 at 16:04
  • Create a timer in the global scope; set it in main; check it in `sub_cb` before calling `publish`. – Christian Fritz Sep 09 '20 at 16:22

1 Answers1

1

Like I said in the comments, I think this is just a logic question, nothing really specific to ROS. Here is one of several possible solutions:

#include "ros/ros.h"
#include "std_msgs/String.h"

ros::Publisher pub;
ros::Time begin;

void sub_cb(const std_msgs::StringConstPtr& str) {
  std_msgs::String msg;
  msg.data = "hello world";
  ros::Time now = ros::Time::now();
  if (now.sec - begin.sec < 15) { // stop publishing after 15 seconds
    std::cout << "." << std::endl;
    pub.publish(msg);
  } else {
    std::cout << "stopped" << std::endl;  // just for debugging
  }
}

int main (int argc, char** argv){
  ros::init(argc, argv, "test");
  ros::NodeHandle nh;
  pub = nh.advertise<std_msgs::String>("Topic2", 1);
  ros::Subscriber sub = nh.subscribe("Topic1", 1, sub_cb);
  begin = ros::Time::now();
  ros::spin();
  return 0;
}
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71