Ask Your Question
0

Get all key/value pairs from custom ROS2 message

asked 2021-02-01 21:29:11 -0600

andrew_103 gravatar image

I've created a custom message that's setup similar to the following

int64 a
int64 b
int64 c

Is there a way to grab all the key/value pairs or just the values in order such that I can iterate over them? I'm imagining something like grabbing key/value pairs from dicts in Python:

for k, v in d.items():
    # perform some operation on k/v pair

I'm using ROS2 Dashing on Ubuntu 18.04

edit retag flag offensive close merge delete

Comments

If you want to iterate over individual values, why not present them as an iterable type (MultiArray)?

crnewton gravatar image crnewton  ( 2021-02-02 07:09:24 -0600 )edit

you don't really indicate which language you're interested in (the Python bit seems to be to illustrate the kind of functionality you're after), but in C++, you could perhaps take a look at facontidavide/ros2_introspection.

Without more context as to why you're looking to do this it seems like a strange question, as consumers of ROS messages (whether ROS 1 or ROS 2) typically know beforehand what they're receiving (as topics are typed).

gvdhoorn gravatar image gvdhoorn  ( 2021-02-02 10:12:19 -0600 )edit

@crnewton I thought about using an array and that would definitely work. The only reason for trying to find a different way with the format I put above is for readability and to have explicit names for the values

andrew_103 gravatar image andrew_103  ( 2021-02-02 11:54:26 -0600 )edit

@gvdhoorn my apologies for not making it clear. I'm using Python for implementation. The context is that this message sends values to a serial interface node which just redirects the message data to the serial port

andrew_103 gravatar image andrew_103  ( 2021-02-02 12:00:09 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-09-29 08:06:21 -0600

moooeeeep gravatar image

There is no API for this, but as this is Python you can probably get away with a hack like this (untested code):

from diagnostic_msgs.msg import KeyValue

msg = KeyValue(key="Hello", value="world")

data_attributes = [
    attr for attr in dir(msg)
    if not attr.startswith("_") and "serialize" not in attr]

for attr in data_attributes:
    print(attr, getattr(msg, attr))
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2021-02-01 21:29:11 -0600

Seen: 153 times

Last updated: Sep 29 '21