0
$\begingroup$

Rosanswers logo

I already read this link: https://answers.ros.org/question/258666/how-to-display-the-function-of-latch/

But I still don't get it, I didn't find any difference whether latch=true or false, the answer is add ros::spin in code, but I thought that's used for subscriber.

this is my main()

ros::init(argc,argv, "Pub");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<std_msgs::Int8>("topic", 50, true);
ros::Rate rate(1);

std_msgs::Int8 msg;
msg.data = 0;
srand(time(NULL));
while(ros::ok())
{
  pub.publish(msg);

  ROS_INFO("msg:%d",msg.data);
  rate.sleep();
  msg.data++;
}
return 0;

Originally posted by rjosodtssp on ROS Answers with karma: 28 on 2020-09-02

Post score: 1

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

From the wiki :

latch [optional]

Enables "latching" on a connection. When a connection is latched, the last message published is saved and automatically sent to any future subscribers that connect. This is useful for slow-changing to static data like a map. Note that if there are multiple publishers on the same topic, instantiated in the same node, then only the last published message from that node will be sent, as opposed to the last published message from each publisher on that single topic.

That means that if you publish a message with latch=true then every subscriber will get the message once even if you don't publish it anymore. Your code is publishing in a while loop so indeed it won't make a difference wether latch=true or false because you always send a new message. To show the difference you need to publish data only once (or several time but stop at some point) and then subscribe to the topic when it's not published anymore (with rostopic echo for example). A code that would show the difference could be :

ros::init(argc,argv, "Pub");
ros::NodeHandle nh;
ros::Publisher pub_latch_true = nh.advertise<std_msgs::Int8>("topic_latch_true", 50, true);
ros::Publisher pub_latch_false = nh.advertise<std_msgs::Int8>("topic_latch_false", 50, false);
ros::Rate rate(1);

std_msgs::Int8 msg;
msg.data = 2;
pub_latch_true.publish(msg);
pub_latch_false.publish(msg);
while(ros::ok())
{
  ros::spinOnce();
  rate.sleep();
}
return 0;

Run this node (the while loop is only to keep the node alive) and then do rostopic echo /topic_latch_true and rostopic echo /topic_latch_false, you won't have any output for topic_latch_false and you will have only one message with topic_latch_true (the last published message).


Originally posted by Delb with karma: 3907 on 2020-09-03

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by rjosodtssp on 2020-09-03:
thank you, very helpful

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.