framework/utils/ros2_topic_to_json.py

72 lines
No EOL
2.6 KiB
Python

"""
ROS2_Topic_to_json
ROS 2 program for outputting system objects to json format
From https://github.com/ros2/ros2cli/blob/humble/ros2topic/ros2topic/verb/list.py
@shalenikol release 0.1
"""
"""
usage: python ros2_topic_to_json.py [-h] [--jsonpath JSONPATH]
options:
-h, --help show this help message and exit
--jsonpath JSONPATH Output file in json-format
"""
import argparse
import json
from ros2cli.node.strategy import NodeStrategy
from ros2topic.api import get_topic_names_and_types
OUTPUT_FILE = "topics.json"
# def show_topic_info(topic_info, is_publisher):
# message = ('Published' if is_publisher else 'Subscribed') + ' topics:\n'
# for (topic_name, topic_types, pub_count, sub_count) in topic_info:
# count = pub_count if is_publisher else sub_count
# if count:
# topic_types_formatted = ', '.join(topic_types)
# count_str = str(count) + ' ' + ('publisher' if is_publisher else 'subscriber') \
# + ('s' if count > 1 else '')
# message += f' * {topic_name} [{topic_types_formatted}] {count_str}\n'
# return message
def main(args, jsonpath):
topic_info = []
with NodeStrategy(args) as node:
topic_names_and_types = get_topic_names_and_types(
node=node,
include_hidden_topics=False)
for (topic_name, topic_types) in topic_names_and_types:
# if args.verbose:
# pub_count = node.count_publishers(topic_name)
# sub_count = node.count_subscribers(topic_name)
# topic_info.append((topic_name, topic_types, pub_count, sub_count))
# else:
topic_info.append((topic_name, topic_types))
# if args.count_topics:
print(f"---> number of topics: {len(topic_names_and_types)}")
j_data = {"topics": topic_info}
with open(jsonpath, "w") as fh:
json.dump(j_data, fh, indent=2)
# elif topic_names_and_types:
# if args.verbose:
# print(show_topic_info(topic_info, is_publisher=True))
# print(show_topic_info(topic_info, is_publisher=False))
# else:
for (topic_name, topic_types) in topic_info:
msg = "{topic_name}"
# topic_types_formatted = ', '.join(topic_types)
# if args.show_types:
# msg += ' [{topic_types_formatted}]'
print(msg.format_map(locals()))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--jsonpath", default=OUTPUT_FILE, help="Output file in json-format")
m_args = parser.parse_args()
args = {}
main(args, m_args.jsonpath)