Search code examples
c++ros

How to get function return values into ROS topic msg to be published


I'm a beginner when it comes to working with ROS.
Currently working in Melodic, outside of the catkin workspace. ie: not using catkin

My goal is to create a topic that contains an x and y value, then to update those values from the return value of my path prediction function, which returns a std::vector<Eigen::Vector2f> containing the x and y values.

this is what my code looks like:

ros::NodeHangle nh;
ros::Publisher topic_pub = nh.advertise<geometry_msgs::Point>("mytopic/path", 1000);
int counter=0;
ros::Rate rate(10);

while (ros::ok()) {
   geometry_msgs::Point msg;
   msg.data = engine.getPathFunction();
   topic_pub.publish(msg);
   rate.sleep();
   }

The line where I set msg.data = engine.getPathFunction(); , returns an error of course.
The return type of getPathFunction() is std::vectorEigen::Vector2f ... with x and y values for the path.

What's the best way to handle this conversion and get those x and y values into msg?
Is this something ROS can handle? If not, is there another library useful for conversions? Should I just write my own function? If so, what should that function look like in this example?


Solution

  • The best, and only, way to handle this conversion is to do it manually. A Point message has fields for (x,y,z) so you'll need to simply assign those values yourself. Another thing to note is that a Point msg doesn't have a .data field like std_msgs do.

    geometry_msgs::Point msg;
    std::vector<Eigen::Vector2f> tmp_vec = engine.getPathFunction();
    msg.x = tmp_vec[0]; //Assumes x here
    msg.y = tmp_vec[1]; //Assumes y here
    topic_pub.publish(msg);