Why does waitForMessage not work for a single non-latching message?
I need a way to get the first message that was published after this line of code. I am thinking waitForMessage
seems like a logical choice. However, it does not seem to be behaving as I expected.
Given the following simple program that waits for messages from a topic a couple of times.
#include "ros/ros.h"
#include "std_msgs/Int32.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle nh;
std_msgs::Int32::ConstPtr ret;
ret = ros::topic::waitForMessage<std_msgs::Int32>("/topic");
ROS_INFO("%d", ret->data);
ret = ros::topic::waitForMessage<std_msgs::Int32>("/topic");
ROS_INFO("%d", ret->data);
ret = ros::topic::waitForMessage<std_msgs::Int32>("/topic");
ROS_INFO("%d", ret->data);
ros::spin();
return 0;
}
I publish with the following non-latching publish
#!/usr/bin/env python
import rospy
import std_msgs
if __name__ == "__main__":
rospy.init_node('publisher')
pub = rospy.Publisher('/topic', std_msgs.msg.Int32, queue_size=1, latch=False)
pub.publish(0)
rospy.spin()
rostopic echo /topic
shows that the message is published correctly. However, the listener program is still stuck at waitForMessage
even though the listener program was started before the publishing node. Why is that the case?
Further testing with
#!/usr/bin/env python
import rospy
import std_msgs
if __name__ == "__main__":
i = 0
while not rospy.is_shutdown():
pub = rospy.Publisher('/topic', std_msgs.msg.Int32, queue_size=1)
rospy.init_node('publisher')
pub.publish(i)
i += 1
rospy.sleep(10)
shows that it's always only the first message that is ignored. The subsequent messages are correctly caught by waitForMessage
Seeing your question (and #q368589), perhaps it would be good if you could clarify why you "need a way to get the first message that was published after this line of code". What is it you're trying to achieve?
Publish-subscribe being a completely asynchronous pattern of communication, implementing anything which requires strict ordering of events in different entities is typically a bit more complex than normal. So things may need a different approach.
Thanks for the patience and detailed responses, I am currently running tests in simulation where I rearrange some 200+ objects in gazebo and check if the sensor detects them. This is repeated many times for many different configurations. Since I am simulating multiple lidars, getting each sensor measurement takes an incredibly long time. As such, to speed up my testing, I only get the first sensor reading immediately after rearrangement (which I was thinking to accomplish with
waitForMessage
). I am currently tracking down an issue where the sensor measurements don't seem to be updated afte rearrangement (question on gazebosim here) which led me to the questions onwaitForMessage
.