0
$\begingroup$

Rosanswers logo

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?

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

Look up "variable scope in C++" to understand how variables like ros::Publisher pub can be declared and used in C++ programs.

The preferred method is to create a class like class MyNode, and declare ros::Publisher pub; as a private variable in the class. But if you just want to quickly hack up existing C++ code you can just declare ros::Publisher pub; as a global variable somewhere near the top of the cpp file, and use it later.


Originally posted by clyde with karma: 1247 on 2017-11-07

This answer was ACCEPTED on the original site

Post score: 0

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.