From 288b114841caf27816bb25846dc7dbc1f1e5ad23 Mon Sep 17 00:00:00 2001 From: Nuno Marques Date: Sun, 22 Nov 2026 01:04:15 -0800 Subject: [PATCH] feat(uxrce_dds_client): bridge out-of-tree uORB messages over uXRCE-DDS (#29782) * feat(uxrce_dds_client): bridge the topics of out-of-tree messages Out-of-tree uORB messages build into PX4 like any other, but the bridge reads only dds_topics.yaml, so bridging one means editing that file and carrying the change through every PX4 update. When $EXTERNAL_MODULES_LOCATION/msg/dds_topics.yaml exists, the build passes it to the generator after dds_topics.yaml, and the generator appends each file's lists to those before it. A topic declared twice in the same list stops the build, since it would be bridged twice. A single file, as Zenoh's build passes, yields its lists unchanged. Assisted-by: Claude-Code:claude-opus-5-5 * test(uxrce_dds_client): test the topic generator in the Python checks The generator runs only inside a firmware build, so a change that breaks joining topic files, or the check for repeated topics, would first show up as a broken build. The tests run it on its own: a second file appends its topics to each list, lists split across files give the same header as one file, files without topics add nothing, and a repeated topic stops it. The Python checks job installs empy for the generator, in the range PX4's requirements.txt gives. Assisted-by: Claude-Code:claude-opus-5-5 * feat(scripts): copy out-of-tree messages into px4_msgs ROS 2 needs every bridged message in px4_msgs, and copy_to_ros_ws.sh copies only PX4's own. An optional second argument, the external modules location, adds the messages of its msg directory, if it has any. A message with the name of a PX4 message would replace PX4's definition in px4_msgs, so the script refuses it before copying anything. A test in the Python checks runs the script on throwaway workspaces: PX4's messages alone, a location's messages added, a location without messages, and the refusals of a PX4 message name and of a location without a msg directory. Assisted-by: Claude-Code:claude-opus-5-5 * docs(uxrce_dds): document bridging out-of-tree messages The uXRCE-DDS page covers dds_topics.yaml but not the topics of out-of-tree messages. Describe their topics file and the copy into px4_msgs there, and point to it from the External Modules page. Assisted-by: Claude-Code:claude-opus-5-5 --- .github/workflows/python_checks.yml | 12 ++- Tools/copy_to_ros_ws.sh | 31 +++++- Tools/test_copy_to_ros_ws.py | 82 ++++++++++++++++ docs/en/advanced/out_of_tree_modules.md | 1 + docs/en/middleware/uxrce_dds.md | 17 ++++ src/modules/uxrce_dds_client/CMakeLists.txt | 14 ++- .../uxrce_dds_client/generate_dds_topics.py | 21 +++- .../test_generate_dds_topics.py | 95 +++++++++++++++++++ 8 files changed, 264 insertions(+), 9 deletions(-) create mode 100644 Tools/test_copy_to_ros_ws.py create mode 100644 src/modules/uxrce_dds_client/test_generate_dds_topics.py diff --git a/.github/workflows/python_checks.yml b/.github/workflows/python_checks.yml index 5091d9bebb2..7cdac377c4c 100644 --- a/.github/workflows/python_checks.yml +++ b/.github/workflows/python_checks.yml @@ -31,7 +31,7 @@ jobs: - name: Install tools run: | - pip install mypy types-requests types-PyYAML flake8 pyyaml + pip install mypy types-requests types-PyYAML flake8 pyyaml "empy>=3.3,<4" pip install -r Tools/setup/test-requirements.txt - name: Check MAVSDK test scripts with mypy @@ -63,6 +63,16 @@ jobs: flake8 Tools/ros2/*.py python3 -m unittest discover -s Tools/ros2 -p 'test_*.py' + - name: Check the uXRCE-DDS topic generator + run: | + flake8 src/modules/uxrce_dds_client/test_generate_dds_topics.py + python3 -m unittest discover -s src/modules/uxrce_dds_client -p 'test_*.py' -v + + - name: Test the ROS workspace copy script + run: | + flake8 Tools/test_copy_to_ros_ws.py + python3 -m unittest discover -s Tools -p 'test_copy_to_ros_ws.py' -v + - name: Test submodule check run: python3 -m unittest discover -s Tools -p 'test_check_submodules.py' -v diff --git a/Tools/copy_to_ros_ws.sh b/Tools/copy_to_ros_ws.sh index b27fb07e341..2eb45d9dbd5 100755 --- a/Tools/copy_to_ros_ws.sh +++ b/Tools/copy_to_ros_ws.sh @@ -6,9 +6,10 @@ DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) PX4_SRC_DIR="$DIR/.." WS_DIR="$1" +EXTERNAL_MODULES_LOCATION="$2" if [ ! -e "${WS_DIR}" ] then - echo "Usage: $0 " + echo "Usage: $0 []" exit 1 fi WS_DIR="$WS_DIR"/src @@ -18,6 +19,30 @@ then exit 1 fi +# Out-of-tree messages join px4_msgs too, so none may have the name of a PX4 message +EXTERNAL_MSGS=() +if [ -n "${EXTERNAL_MODULES_LOCATION}" ] +then + EXTERNAL_MSG_DIR="${EXTERNAL_MODULES_LOCATION}"/msg + if [ ! -d "${EXTERNAL_MSG_DIR}" ] + then + echo "'msg' directory not found inside the external modules location (${EXTERNAL_MSG_DIR})" + exit 1 + fi + for msg in "${EXTERNAL_MSG_DIR}"/*.msg + do + # with no messages in the directory, the pattern itself comes through + [ -e "${msg}" ] || continue + name=$(basename "${msg}") + if [ -e "${PX4_SRC_DIR}/msg/${name}" ] || [ -e "${PX4_SRC_DIR}/msg/versioned/${name}" ] + then + echo "${EXTERNAL_MSG_DIR}/${name} has the name of a PX4 message" + exit 1 + fi + EXTERNAL_MSGS+=("${msg}") + done +fi + cp -ar "${PX4_SRC_DIR}"/msg/translation_node "${WS_DIR}" cp -ar "${PX4_SRC_DIR}"/msg/px4_msgs_old "${WS_DIR}" PX4_MSGS_DIR="${WS_DIR}"/px4_msgs @@ -31,3 +56,7 @@ fi cp -ar "${PX4_SRC_DIR}"/msg/*.msg "${PX4_MSGS_DIR}"/msg cp -ar "${PX4_SRC_DIR}"/msg/versioned/*.msg "${PX4_MSGS_DIR}"/msg cp -ar "${PX4_SRC_DIR}"/srv/*.srv "${PX4_MSGS_DIR}"/srv +if [ ${#EXTERNAL_MSGS[@]} -gt 0 ] +then + cp -a "${EXTERNAL_MSGS[@]}" "${PX4_MSGS_DIR}"/msg +fi diff --git a/Tools/test_copy_to_ros_ws.py b/Tools/test_copy_to_ros_ws.py new file mode 100644 index 00000000000..751ff3fcb91 --- /dev/null +++ b/Tools/test_copy_to_ros_ws.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Tests of copy_to_ros_ws.sh with an external modules location.""" + +import os +import shutil +import subprocess +import tempfile +import unittest + +TOOLS = os.path.dirname(os.path.abspath(__file__)) +SCRIPT = os.path.join(TOOLS, "copy_to_ros_ws.sh") +MSG = os.path.join(TOOLS, "..", "msg") +VERSIONED = os.path.join(MSG, "versioned") + + +def messages(directory): + return sorted(n for n in os.listdir(directory) if n.endswith(".msg")) + + +class CopyToRosWsTest(unittest.TestCase): + + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp) + self.ws = os.path.join(self.tmp, "ws") + # an existing px4_msgs keeps the script from cloning it + self.px4_msgs = os.path.join(self.ws, "src", "px4_msgs") + for directory in ("msg", "srv"): + os.makedirs(os.path.join(self.px4_msgs, directory)) + self.px4 = set(messages(MSG)) | set(messages(VERSIONED)) + + def location(self, *files): + path = tempfile.mkdtemp(dir=self.tmp) + for name in files: + os.makedirs(os.path.join(path, "msg"), exist_ok=True) + with open(os.path.join(path, "msg", name), "w") as f: + f.write("uint64 timestamp\n") + return path + + def copy(self, *location): + return subprocess.run(["bash", SCRIPT, self.ws, *location], + capture_output=True, text=True) + + def copied(self): + return set(os.listdir(os.path.join(self.px4_msgs, "msg"))) + + def test_px4_messages_without_a_location(self): + result = self.copy() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.copied(), self.px4) + + def test_a_location_adds_its_messages(self): + result = self.copy(self.location("MyMessage.msg")) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.copied(), self.px4 | {"MyMessage.msg"}) + + def test_a_location_without_messages_adds_none(self): + result = self.copy(self.location("dds_topics.yaml")) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.copied(), self.px4) + + def test_a_px4_message_name_is_refused_before_copying(self): + for name in (messages(MSG)[0], messages(VERSIONED)[0]): + with self.subTest(name=name): + result = self.copy(self.location("MyMessage.msg", name)) + self.assertEqual(result.returncode, 1) + self.assertIn(f"{name} has the name of a PX4 message", + result.stdout) + self.assertEqual(os.listdir(os.path.join(self.ws, "src")), + ["px4_msgs"]) + self.assertEqual(self.copied(), set()) + + def test_a_location_without_a_msg_directory_is_refused(self): + result = self.copy(self.location()) + self.assertEqual(result.returncode, 1) + self.assertIn("'msg' directory not found", result.stdout) + self.assertEqual(os.listdir(os.path.join(self.ws, "src")), + ["px4_msgs"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/en/advanced/out_of_tree_modules.md b/docs/en/advanced/out_of_tree_modules.md index 7763e547841..6e3f41487a4 100644 --- a/docs/en/advanced/out_of_tree_modules.md +++ b/docs/en/advanced/out_of_tree_modules.md @@ -69,6 +69,7 @@ The uORB topic headers are generated in `/uORB/topics/`, and the mess generated in `/msg/topics_sources/`. The new uORB messages can be used like any other uORB message as described [here](../middleware/uorb.md#adding-a-new-topic). +To bridge them to ROS 2, see [uXRCE-DDS: Out-of-Tree Messages](../middleware/uxrce_dds.md#out-of-tree-messages). :::warning The out-of-tree uORB message definitions cannot have the same name as any of the normal uORB messages. diff --git a/docs/en/middleware/uxrce_dds.md b/docs/en/middleware/uxrce_dds.md index 06419c8167f..9bd6c6b5a35 100644 --- a/docs/en/middleware/uxrce_dds.md +++ b/docs/en/middleware/uxrce_dds.md @@ -667,6 +667,23 @@ The Zenoh bridge module does not yet support demux routing — topics listed und You can arbitrarily change the configuration. For example, you could use different default namespaces or use a custom package to store the message definitions. +### Out-of-Tree Messages + +[Out-of-tree uORB messages](../advanced/out_of_tree_modules.md#out-of-tree-uorb-message-definitions) can be bridged without changing `dds_topics.yaml`. +List them in `$EXTERNAL_MODULES_LOCATION/msg/dds_topics.yaml`, which has the same structure: + +```yaml +publications: + + - topic: /fmu/out/my_message + type: px4_msgs::msg::MyMessage +``` + +The build appends its `publications`, `subscriptions` and `subscriptions_multi` to those of `dds_topics.yaml`, and stops with an error if a topic appears twice in the same list. + +ROS 2 needs the definitions of these messages in `px4_msgs` too. +`Tools/copy_to_ros_ws.sh ` copies them into the workspace's `px4_msgs` along with PX4's own messages, and refuses a message with the name of a PX4 message. + ## DDS (ROS 2) Services PX4 uXRCE-DDS middleware supports [ROS 2 services](https://docs.ros.org/en/jazzy/Concepts/Basic/About-Services.html). diff --git a/src/modules/uxrce_dds_client/CMakeLists.txt b/src/modules/uxrce_dds_client/CMakeLists.txt index 210f1935b2c..a9b628c7980 100644 --- a/src/modules/uxrce_dds_client/CMakeLists.txt +++ b/src/modules/uxrce_dds_client/CMakeLists.txt @@ -135,14 +135,24 @@ else() target_include_directories(microxrceddsclient INTERFACE ${microxrceddsclient_build_dir}/include) + # PX4's topics, then those of out-of-tree messages listed in $EXTERNAL_MODULES_LOCATION/msg/dds_topics.yaml + set(dds_topics_files ${CMAKE_CURRENT_SOURCE_DIR}/dds_topics.yaml) + if(EXTERNAL_MODULES_LOCATION AND EXISTS ${EXTERNAL_MODULES_LOCATION}/msg/dds_topics.yaml) + list(APPEND dds_topics_files ${EXTERNAL_MODULES_LOCATION}/msg/dds_topics.yaml) + endif() + set(dds_topics_args) + foreach(dds_topics_file ${dds_topics_files}) + list(APPEND dds_topics_args --dds-topics-file ${dds_topics_file}) + endforeach() + add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/dds_topics.h COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/generate_dds_topics.py --client-outdir ${CMAKE_CURRENT_BINARY_DIR} - --dds-topics-file ${CMAKE_CURRENT_SOURCE_DIR}/dds_topics.yaml + ${dds_topics_args} --template_file ${CMAKE_CURRENT_SOURCE_DIR}/dds_topics.h.em DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/generate_dds_topics.py - ${CMAKE_CURRENT_SOURCE_DIR}/dds_topics.yaml + ${dds_topics_files} ${CMAKE_CURRENT_SOURCE_DIR}/dds_topics.h.em COMMENT "Generating XRCE-DDS topic bridge" ) diff --git a/src/modules/uxrce_dds_client/generate_dds_topics.py b/src/modules/uxrce_dds_client/generate_dds_topics.py index d40e785a95d..355fcfa2219 100644 --- a/src/modules/uxrce_dds_client/generate_dds_topics.py +++ b/src/modules/uxrce_dds_client/generate_dds_topics.py @@ -43,8 +43,8 @@ import em import yaml parser = argparse.ArgumentParser() -parser.add_argument("-y", "--dds-topics-file", dest='yaml_file', type=str, - help="Setup topics file path, by default using 'dds_topics.yaml'") +parser.add_argument("-y", "--dds-topics-file", dest='yaml_files', type=str, action='append', required=True, + help="Setup topics file path; repeat it to add the topics of more files") parser.add_argument("-t", "--template_file", dest='template_file', type=str, help="DDS topics template file") @@ -75,9 +75,13 @@ if not os.path.exists(folder_name): -# open yaml file to load dictionary of publications and subscriptions -with open(args.yaml_file, 'r') as file: - msg_map = yaml.safe_load(file) +# open the yaml files and join their lists of publications and subscriptions, in order +msg_map = {'publications': [], 'subscriptions': [], 'subscriptions_multi': []} +for yaml_file in args.yaml_files: + with open(yaml_file, 'r') as file: + topics = yaml.safe_load(file) or {} + for key in msg_map: + msg_map[key] += topics.get(key) or [] # Get DDS namespace from environment, default to empty string namespace = os.getenv('PX4_UXRCE_DDS_NS', '') @@ -167,6 +171,13 @@ merged_em_globals['subscriptions_multi'] = subs_multi merged_em_globals['type_includes'] = sorted(set(all_type_includes)) +# a topic declared twice in a list, in one file or in two, would be bridged twice +for key in ('publications', 'subscriptions', 'subscriptions_multi'): + names = [msg_type['topic'] for msg_type in merged_em_globals[key]] + repeated = sorted({name for name in names if names.count(name) > 1}) + if repeated: + raise ValueError(f"{key}: {', '.join(repeated)} declared more than once") + # run interpreter ofile = open(output_file, 'w') diff --git a/src/modules/uxrce_dds_client/test_generate_dds_topics.py b/src/modules/uxrce_dds_client/test_generate_dds_topics.py new file mode 100644 index 00000000000..a334c6aedf8 --- /dev/null +++ b/src/modules/uxrce_dds_client/test_generate_dds_topics.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Tests of generate_dds_topics.py with more than one topics file.""" + +import os +import subprocess +import sys +import tempfile +import unittest + +import yaml + +HERE = os.path.dirname(os.path.abspath(__file__)) +GENERATOR = os.path.join(HERE, "generate_dds_topics.py") +TEMPLATE = os.path.join(HERE, "dds_topics.h.em") +PX4_TOPICS = os.path.join(HERE, "dds_topics.yaml") +LISTS = ("publications", "subscriptions", "subscriptions_multi") +OUT_OF_TREE = { + "publications": [ + {"topic": "/fmu/out/my_message", "type": "px4_msgs::msg::MyMessage"}, + ], + "subscriptions": [ + {"topic": "/fmu/in/my_command", "type": "px4_msgs::msg::MyCommand"}, + ], +} + + +class GenerateDdsTopicsTest(unittest.TestCase): + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.directory = directory.name + with open(PX4_TOPICS) as f: + self.px4 = yaml.safe_load(f) + + def write(self, topics): + handle, path = tempfile.mkstemp(suffix=".yaml", dir=self.directory) + with os.fdopen(handle, "w") as f: + if isinstance(topics, str): + f.write(topics) + else: + yaml.safe_dump(topics, f, sort_keys=False) + return path + + def generate(self, *topics_files): + out = tempfile.mkdtemp(dir=self.directory) + command = [sys.executable, GENERATOR, "--client-outdir", out, + "--template_file", TEMPLATE] + for topics_file in topics_files: + command += ["--dds-topics-file", topics_file] + result = subprocess.run(command, capture_output=True, text=True) + header = os.path.join(out, "dds_topics.h") + if not os.path.exists(header): + return result, None + with open(header) as f: + return result, f.read() + + def test_a_second_file_appends_its_topics_to_each_list(self): + joined = {key: (self.px4.get(key) or []) + OUT_OF_TREE.get(key, []) + for key in LISTS} + _, expected = self.generate(self.write(joined)) + result, header = self.generate(PX4_TOPICS, self.write(OUT_OF_TREE)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('"/fmu/out/my_message"', header) + self.assertIn('"/fmu/in/my_command"', header) + self.assertEqual(header, expected) + + def test_lists_split_across_files_generate_the_same_header(self): + publications = {"publications": self.px4["publications"]} + subscriptions = {key: self.px4[key] for key in LISTS[1:]} + _, expected = self.generate(PX4_TOPICS) + result, header = self.generate(self.write(publications), + self.write(subscriptions)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(header, expected) + + def test_files_without_topics_add_nothing(self): + _, expected = self.generate(PX4_TOPICS) + result, header = self.generate(PX4_TOPICS, self.write(""), + self.write("publications:\n")) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(header, expected) + + def test_a_topic_declared_twice_stops_the_generator(self): + again = {"publications": self.px4["publications"][:1]} + topic = again["publications"][0]["topic"] + result, header = self.generate(PX4_TOPICS, self.write(again)) + self.assertNotEqual(result.returncode, 0) + self.assertIn(f"publications: {topic} declared more than once", + result.stderr) + self.assertIsNone(header) + + +if __name__ == "__main__": + unittest.main()