Robotics StackExchange | Archived questions

Passed array of integers are not displayed in the callback function

I have created a node which reads array of integers from a file and publishes over Topic_1 at once

...
 ros::Publisher publisher = nh.advertise<std_msgs::Int32MultiArray>("Topic_1",1000,true);


  std_msgs::Int32MultiArray vec;


  ROS_INFO("Array elements from file [array1.txt] are published to Topic_1:\n");
  ifstream infile("array1.txt");

  while(infile >> temp)
      vec.data.push_back(temp);

  publisher.publish(vec);
  ros::spin();
...

and here is the subscriber for Topic_1

void callback_1(const std_msgs::Int32MultiArray::ConstPtr& vec1)
{ 
  ROS_INFO("Vector recieved over Topic_1\n");
  vector<int>::const_iterator itr = vec1->data.begin();

  for(;itr != vec1->data.end();++itr)
    {
      ROS_INFO("%d ",*itr);
    }
}
...
ros::Subscriber sub_1 = nh.subscribe("Topic_1",1000,callback_1);
...

There are no errors when I compile these nodes. But when I launch these nodes using roslaunch, 'for' loop in callback_1 is not at all executed.

 ROS_INFO("Vector recieved over Topic_1\n"); is executed

What could probably be going wrong?

Asked by anonymous25787 on 2016-03-03 14:09:15 UTC

Comments

Are you certain that infile contains data, and that the array is actually populated before it is published?

Asked by ahendrix on 2016-03-03 14:44:44 UTC

Answers

Is it easier to try something like if you can use a C++11 or C++0x standard compiler:

for(auto const& dt: vec1->data)
{
  ROS_INFO("%d ",dt);
}

Asked by jeremya on 2016-03-03 16:54:15 UTC

Comments

Yes, infile does contain data. I figured out the problem, When I start all the nodes using roslaunch, infile is not invoked but when I start the nodes using rosrun twice(for each node) everything is working perfectly fine (Even the entire vector is published in the subscriber). Why is this so?

Asked by anonymous25787 on 2016-03-03 22:16:30 UTC

Comments

When running nodes in roslaunch, roslaunch changes the working directory to ~/.ros before starting your node. Since your file is referenced by relative path, your node is no longer able to find it.

Asked by ahendrix on 2016-03-04 13:29:22 UTC

your node should either use a library like rospkg to locate files relative to the package that they're expected in, or you can use $(find) or similar in roslaunch to get the path to your file and pass it as a parameter or command-line argument.

Asked by ahendrix on 2016-03-04 13:30:53 UTC