Robotics StackExchange | Archived questions

Get all key/value pairs from custom ROS2 message

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

Asked by andrew_103 on 2021-02-01 22:29:11 UTC

Comments

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

Asked by crnewton on 2021-02-02 08:09:24 UTC

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).

Asked by gvdhoorn on 2021-02-02 11:12:19 UTC

@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

Asked by andrew_103 on 2021-02-02 12:54:26 UTC

@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

Asked by andrew_103 on 2021-02-02 13:00:09 UTC

Answers

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))

Asked by moooeeeep on 2021-09-29 08:06:21 UTC

Comments