ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How to subscribe the topic only once

asked 2017-09-06 04:15:23 -0600

hudaming gravatar image

updated 2017-09-06 08:17:53 -0600

lucasw gravatar image

I have a problem about how to sucscribe the topic only once,In some time, I only hope to get the first data from the topic, rather than change the publisher. So how should I do? This is my code:

#include  <ros/ros.h>
#include <sensor_msgs/NavSatFix.h>
#include <geometry_msgs/PointStamped.h>
static geometry_msgs::PointStamped point;

void imageCallback(const sensor_msgs::NavSatFix::ConstPtr &msg)

int main(int argc, char **argv)
  ros::init(argc, argv, "test");
  ros::NodeHandle nh;
  ros::Subscriber positions_sub = nh.subscribe("/POSITIONS", 3, &imageCallback);

In this code, I can get many points, but I only hope to get the first point. What should I change in tthe code ? THANKS!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2017-09-06 05:31:18 -0600

gvdhoorn gravatar image

updated 2019-01-24 11:42:05 -0600

While @bvbdort's answer will probably work, there is a convenience method that essentially does all that for you in a single line: ros::topic:waitForMessage(..).

It also supports specifying timeouts, which NodeHandle to use and some other niceties.


#include <ros/ros.h>
#include <sensor_msgs/NavSatFix.h>
#include <geometry_msgs/PointStamped.h>

int main(int argc, char *argv[])
  ros::init(argc, argv, "test");
  ros::NodeHandle nh;

  sensor_msgs::NavSatFixConstPtr navsatfix_msg = ros::topic::waitForMessage("/POSITIONS");

  geometry_msgs::PointStamped point;
  point.point.x = navsatfix_msg->latitude;
  point.point.y = navsatfix_msg->longitude;
  point.point.z = navsatfix_msg->altitude;

  // do something with 'point'
edit flag offensive delete link more


Sorry, I can not get the solution. Can you give me an example? My hope is to loop the imageCallback only once. Thanks!

hudaming gravatar image hudaming  ( 2017-09-06 08:25:24 -0600 )edit

See my edit. This is somewhat pseudo-code though, I haven't (even) compile-tested it.

gvdhoorn gravatar image gvdhoorn  ( 2017-09-06 08:41:54 -0600 )edit

@gvdhoorn Your code didn't work for me, because the return value of waitForMessage is a boost::shared_ptr. So in this case I'd need to change that to boost::shared_ptr<sensor_msgs::NavSatFix> msg = ros::topic::waitForMessage<sensor_msgs::NavSatFix>("/POSITIONS");. You might want to fix this.

max11gen gravatar image max11gen  ( 2019-01-24 10:56:03 -0600 )edit

Thanks, you were correct.

I've opted to use NavSatFixConstPtr though. It's more "ROS-onic".

gvdhoorn gravatar image gvdhoorn  ( 2019-01-24 11:42:49 -0600 )edit

Question Tools

1 follower


Asked: 2017-09-06 04:15:23 -0600

Seen: 4,456 times

Last updated: Jan 24 '19