ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How to check if a message has a header? (c++)

asked 2020-03-21 20:46:07 -0500

scottnothing gravatar image

Is there any way program logic around whether a particular message contains a header (std_msgs/Header)? For example:

template <class MsgType>
ros::Time get_message_time(const boost::shared_ptr<MsgType>& msg)
{
    if (hasHeader(msg))
    {
        return msg->header.stamp;
    } else
    {
        return ros::Time::now();
    }
}

This code will not compile with messages that do not contain a header. Is there another way?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2020-03-21 22:09:53 -0500

scottnothing gravatar image

I figured out how to use message_traits. For the above code:

auto stamp = ros::message_traits::timeStamp(*msg);
if (stamp)
{
    return *stamp;
} else
{
    return ros::Time::now();
}

The message traits function will return a pointer which will be nullptr if it could not extract a timestamp (no header). Simply then test if the pointer is valid, then access it.

Similar traits exists for Header and FrameId, see http://docs.ros.org/indigo/api/roscpp...

edit flag offensive delete link more

Comments

Wouldn't ros::message_traits::HasHeader<m> be a more direct way of checking whether a message has a header?

gvdhoorn gravatar image gvdhoorn  ( 2020-03-22 02:56:00 -0500 )edit

Yes, I think the title question is due to my coming from a Python perspective where I would use hasattr(...) to determine if there was a header before accessing it. Due to c++ and type safety, this cant work. The real question, I guess, is how to get timestamp (or frame_id) from a header if one exists, and have this work for all possible message types.

scottnothing gravatar image scottnothing  ( 2020-03-22 14:36:33 -0500 )edit

There seem to be two questions here:

  1. how to determine whether a message has a header
  2. if there is a header, how to retrieve the timestamp

For the first

For the second:

  • convention dictates that messages with headers store them in a field of type std_msgs/Header with the name header (this is also the location most/all code in roscpp will check
  • if convention is not followed, the libraries I linked to earlier could be used to find it, but it could be that a field with type std_msgs/Header is used without it actually being a header
gvdhoorn gravatar image gvdhoorn  ( 2020-03-23 04:56:12 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2020-03-21 20:46:07 -0500

Seen: 1,574 times

Last updated: Mar 21 '20