Subscriber callback function isn't invoked
Two publishers publish array of integers to two different topics (Topic_1 and Topic_2) and a third node subscribes to these two topics.
ros::Publisher publisher = nh.advertise<std_msgs::Int32MultiArray>("Topic_1",1000);
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();
return 0;
}
Here is the code for second publisher
...
...
ros::Publisher publisher = nh.advertise<std_msgs::Int32MultiArray>("Topic_2",1000);
std_msgs::Int32MultiArray vec2;
ROS_INFO("Array elements from file [array2.txt] are published to Topic_2:\n");
ifstream infile("array2.txt");
while(infile >> temp)
vec2.data.push_back(temp);
publisher.publish(vec2);
ros::spin();
return 0;
}
Here is the one for subscriber:
#include "ros/ros.h"
#include<bits/stdc++.h>
#include<std_msgs/Int32MultiArray.h>
void sort();
void callback_1(const std_msgs::Int32MultiArray::ConstPtr& vec1)
{
ROS_INFO("Vector recieved! over Topic_1\n");
}
void callback_2(const std_msgs::Int32MultiArray::ConstPtr& vec2)
{
ROS_INFO("Vector recieved! over Topic_2\n");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");
ROS_INFO("Reading the vectors from both the topics");
ros::NodeHandle nh;
ros::Subscriber sub_1 = nh.subscribe("Topic_1",1000,callback_1);
ros::Subscriber sub_2 = nh.subscribe("Topic_2",1000,callback_2);
ros::spin();
return 0;
}
But ROS_INFO("Vector recieved! over Topic_1\n");
statements are not at all executed.
I even wrote a launch file to start these three nodes but the above statement is not executed.
But when I run rosnode list
, all the three nodes are listed and even both the topics are displayed when I run rostopic list
What could probably be going wrong?
Have you tried replacing spin() with a while loop and ros::spinOnce() ? Subscription will not require a while loop, just spinOnce will suffice.