Publish on topic for a certain period of time

1.2k views Asked by At

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.

1

There are 1 answers

1
Christian Fritz On

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;
}