I have a program with a main.cpp and a message.cpp files.
The second has a function that is called every time an event happens and I have to send a ros message.
My first try was to declare the publisher and send the message in message.cpp:
ros::NodeHandle nh("~");
ros::Publisher pub = nh.advertise<myProject_ros::PathMessage>("/myProject_ros/message", 1000);
// creating my message
pub.publish(message);
But doing it like that, I had to insert a delay between the publisher and the publish, otherwise the listener had no time to connect.
In order to avoid introducing delays, I started creating the publisher in my main file:
ros::NodeHandle nh("~");
ros::Publisher pub = nh.advertise<myProject_ros::PathMessage>("/myProject_ros/message", 1000);
And then I wanted to publish in message.cpp:
pub.publish(message);
But then
error: ‘pub’ was not declared in this scope
So now I am creating the publisher both in the main so listener is ready and in message.cpp again to avoid pub not declared. It is working fine, I don't need delay now, but it looks like a "dirty" solution.
What is the proper way to do this? I am new to ROS and C++.
Originally posted by danividanivi on ROS Answers with karma: 3 on 2017-11-07
Post score: 0
Original comments
Comment by jayess on 2017-11-07:
Welcome! It would be much easier to understand your problem if you posted your code instead of describing it and posting snippets.
Comment by l4ncelot on 2017-11-07:
So you basically want to wait with publisher on your listener? You can do that with getNumSubscribers()
and wait until this number is greater than 0.
Comment by danividanivi on 2017-11-07:
Thank you! The full code is very long and copyright protected, I just have to add this feature of sending ROS messages and I did, but I don't think declaring pub twice is the best way to do it.
Comment by danividanivi on 2017-11-07:
I thought about waiting for getNumSubscribers>0 but sometimes code will run without any listener, so I cannot do that.
Comment by jayess on 2017-11-07:
@danividanivi: Can you post a simple (non-copyrighted), complete example of what you're trying to accomplish?