urml-av-runtime 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ # --- Python ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ dist/
9
+ develop-eggs/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Virtual envs
25
+ .venv/
26
+ venv/
27
+ env/
28
+ ENV/
29
+ .python-version
30
+
31
+ # Test / coverage / mypy / pyright
32
+ .coverage
33
+ .coverage.*
34
+ .cache
35
+ .pytest_cache/
36
+ .mypy_cache/
37
+ .dmypy.json
38
+ .pyre/
39
+ .pyright/
40
+ htmlcov/
41
+ nosetests.xml
42
+ coverage.xml
43
+ *.cover
44
+ .hypothesis/
45
+ .tox/
46
+
47
+ # --- Node / web tooling (kept out of core repo; here for safety) ---
48
+ node_modules/
49
+ .pnp.*
50
+ .yarn/cache/
51
+ .yarn/unplugged/
52
+ .yarn/build-state.yml
53
+ .yarn/install-state.gz
54
+ npm-debug.log*
55
+ yarn-debug.log*
56
+ yarn-error.log*
57
+
58
+ # --- C++ / Rust build artifacts (in case reference runtimes land here in early Phase 1) ---
59
+ target/
60
+ *.o
61
+ *.obj
62
+ *.a
63
+ *.lib
64
+ *.dll
65
+ *.dylib
66
+ *.exe
67
+ *.pdb
68
+ cmake-build-*/
69
+ CMakeCache.txt
70
+ CMakeFiles/
71
+ CMakeScripts/
72
+ Testing/
73
+ cmake_install.cmake
74
+ install_manifest.txt
75
+ compile_commands.json
76
+
77
+ # --- ROS 2 build dirs ---
78
+ build/
79
+ install/
80
+ log/
81
+
82
+ # --- Editor and OS junk ---
83
+ .vscode/
84
+ .idea/
85
+ *.swp
86
+ *.swo
87
+ *~
88
+ .DS_Store
89
+ Thumbs.db
90
+ desktop.ini
91
+
92
+ # --- Local-only artifacts ---
93
+ .env
94
+ .env.*
95
+ *.log
96
+ *.tmp
97
+ .local/
98
+ .scratch/
99
+
100
+ # --- Outreach campaign artifacts (operational, not part of the open standard) ---
101
+ # Target lists, message drafts, tracking data, and the launch-approval record
102
+ # stay local. They are private to the maintainer; committing them would
103
+ # telegraph the campaign before launch and could embarrass listed projects.
104
+ outreach/
105
+
106
+ # Outreach dashboard SQLite mirror (RFC-0275). Derived from
107
+ # examples/lighthouses/outreach*.yaml via tools/scripts/refresh_outreach_db.py.
108
+ # Regenerated on demand by `make outreach-refresh`.
109
+ tools/outreach.db
110
+ tools/.outreach.db
111
+
112
+ # Local Claude Code settings (per-machine; permission rules, etc.). Not committed.
113
+ .claude/settings.json
114
+ .claude/settings.local.json
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: urml-av-runtime
3
+ Version: 0.5.0
4
+ Summary: Autonomous-vehicle reference runtime for URML — Autoware AD API via rclpy.
5
+ Project-URL: Homepage, https://github.com/urml-dev/URML
6
+ Project-URL: Repository, https://github.com/urml-dev/URML
7
+ Project-URL: Issues, https://github.com/urml-dev/URML/issues
8
+ Author: URML Maintainers
9
+ License: BUSL-1.1
10
+ Keywords: adapi,autonomous-vehicle,autoware,robotics,ros2,runtime,trajectory,urml
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: Other/Proprietary License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: pydantic<3,>=2.6
21
+ Requires-Dist: pyyaml<7,>=6.0
22
+ Requires-Dist: urml-ros2-runtime>=0.5.0
23
+ Requires-Dist: urml-validator>=0.5.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: mypy>=1.10; extra == 'dev'
26
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
27
+ Requires-Dist: pytest>=8; extra == 'dev'
28
+ Requires-Dist: ruff>=0.5; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ <p align="center">
32
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
33
+ </p>
34
+
35
+ # urml-av-runtime
36
+
37
+ **Autonomous-vehicle reference runtime for URML** — `AutowareAdapter`, over the Autoware Universe AD API.
38
+
39
+ The first substrate to implement URML's `TrajectoryAdapter` Protocol (RFC-0020). Until now only `MockROSAdapter` did; this backs the AV verbs against a real [Autoware](https://autoware.org/) stack through the documented [AD API](https://autowarefoundation.github.io/autoware-documentation/main/design/autoware-interfaces/ad-api/) (`autoware_adapi_v1_msgs`).
40
+
41
+ ## Method coverage
42
+
43
+ | URML primitive | Autoware AD API | behaviour |
44
+ |---|---|---|
45
+ | `plan_path` (compute) | `/api/routing/set_route_points` (`SetRoutePoints`) | sets a route to the goal pose; Autoware plans the dense trajectory from the vehicle's localized pose. URML binds a route handle, not raw waypoints |
46
+ | `follow_trajectory` (actuate) | `/api/operation_mode/change_to_autonomous` (`ChangeOperationMode`) + a `VelocityLimit` publish | engages autonomous driving under an optional speed cap. The only AV verb that actuates |
47
+ | `wait` / `report` | none | passive hold / local report sink, so a full AV program runs |
48
+
49
+ Everything else in the substrate surface is not implemented: an AV program is `plan_path` then `follow_trajectory` (see [`examples/av/robotaxi-trip.urml.yaml`](../../examples/av/robotaxi-trip.urml.yaml)).
50
+
51
+ ## Honest boundaries
52
+
53
+ - `start` is ignored: Autoware routes from the vehicle's current localized pose.
54
+ - `along` (an HD-map corridor id) is checked by the validator upstream; the AD API routing request takes no such field, so it is not forwarded.
55
+ - `max_accel` and `on_off_route` are vehicle- and planning-configured in Autoware; the adapter records the intent, it does not set them per call.
56
+ - Every AD API service / topic / message-type name is overridable in `AutowareConfig`, so the adapter tracks a specific Autoware release without a code change.
57
+
58
+ ## Install / use
59
+
60
+ `rclpy` and the Autoware message packages ship with a ROS 2 + Autoware install, not from PyPI, so there is no installable extra. They are imported lazily, so this module loads on every host (Windows included) and the hermetic suite runs without ROS 2.
61
+
62
+ ```bash
63
+ pip install -e reference/av-runtime # hermetic dev; adapter needs Linux + Autoware to actuate
64
+ ```
65
+
66
+ ```python
67
+ from urml_av_runtime import AutowareAdapter, AutowareConfig, MapPose
68
+
69
+ cfg = AutowareConfig(location_to_pose={
70
+ "depot": MapPose(x=0.0, y=0.0),
71
+ "dropoff": MapPose(x=30.0, y=12.0, yaw=1.57),
72
+ })
73
+ # rclpy.init() is the caller's responsibility, as with RclpyAdapter.
74
+ with AutowareAdapter(cfg) as av:
75
+ plan = av.plan_trajectory(start=None, goal="dropoff", along="city_map")
76
+ av.follow_trajectory_goal(trajectory=plan.payload, max_velocity_mps=12.0)
77
+ ```
78
+
79
+ ## Status
80
+
81
+ **v0.1 (this release):**
82
+ - `AutowareAdapter` + `AutowareConfig` + `load_av_config`. Hermetic suite green via fake-`rclpy` / fake-message injection (`pytest reference/av-runtime/tests -q`).
83
+ - The `av` profile is research-grade, not production safety-certified (RFC-0020). Real-vehicle validation on a Linux + Autoware host is a gated follow-up, never claimed from the hermetic suite.
84
+
85
+ ## Core Commitment
86
+
87
+ Business Source License 1.1: free for non-production use, commercial license for production (see [`LICENSING.md`](../../LICENSING.md)). No vendor coupling, no cloud dependency. `rclpy` and the Autoware messages are imported lazily, never at module load.
@@ -0,0 +1,57 @@
1
+ <p align="center">
2
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
3
+ </p>
4
+
5
+ # urml-av-runtime
6
+
7
+ **Autonomous-vehicle reference runtime for URML** — `AutowareAdapter`, over the Autoware Universe AD API.
8
+
9
+ The first substrate to implement URML's `TrajectoryAdapter` Protocol (RFC-0020). Until now only `MockROSAdapter` did; this backs the AV verbs against a real [Autoware](https://autoware.org/) stack through the documented [AD API](https://autowarefoundation.github.io/autoware-documentation/main/design/autoware-interfaces/ad-api/) (`autoware_adapi_v1_msgs`).
10
+
11
+ ## Method coverage
12
+
13
+ | URML primitive | Autoware AD API | behaviour |
14
+ |---|---|---|
15
+ | `plan_path` (compute) | `/api/routing/set_route_points` (`SetRoutePoints`) | sets a route to the goal pose; Autoware plans the dense trajectory from the vehicle's localized pose. URML binds a route handle, not raw waypoints |
16
+ | `follow_trajectory` (actuate) | `/api/operation_mode/change_to_autonomous` (`ChangeOperationMode`) + a `VelocityLimit` publish | engages autonomous driving under an optional speed cap. The only AV verb that actuates |
17
+ | `wait` / `report` | none | passive hold / local report sink, so a full AV program runs |
18
+
19
+ Everything else in the substrate surface is not implemented: an AV program is `plan_path` then `follow_trajectory` (see [`examples/av/robotaxi-trip.urml.yaml`](../../examples/av/robotaxi-trip.urml.yaml)).
20
+
21
+ ## Honest boundaries
22
+
23
+ - `start` is ignored: Autoware routes from the vehicle's current localized pose.
24
+ - `along` (an HD-map corridor id) is checked by the validator upstream; the AD API routing request takes no such field, so it is not forwarded.
25
+ - `max_accel` and `on_off_route` are vehicle- and planning-configured in Autoware; the adapter records the intent, it does not set them per call.
26
+ - Every AD API service / topic / message-type name is overridable in `AutowareConfig`, so the adapter tracks a specific Autoware release without a code change.
27
+
28
+ ## Install / use
29
+
30
+ `rclpy` and the Autoware message packages ship with a ROS 2 + Autoware install, not from PyPI, so there is no installable extra. They are imported lazily, so this module loads on every host (Windows included) and the hermetic suite runs without ROS 2.
31
+
32
+ ```bash
33
+ pip install -e reference/av-runtime # hermetic dev; adapter needs Linux + Autoware to actuate
34
+ ```
35
+
36
+ ```python
37
+ from urml_av_runtime import AutowareAdapter, AutowareConfig, MapPose
38
+
39
+ cfg = AutowareConfig(location_to_pose={
40
+ "depot": MapPose(x=0.0, y=0.0),
41
+ "dropoff": MapPose(x=30.0, y=12.0, yaw=1.57),
42
+ })
43
+ # rclpy.init() is the caller's responsibility, as with RclpyAdapter.
44
+ with AutowareAdapter(cfg) as av:
45
+ plan = av.plan_trajectory(start=None, goal="dropoff", along="city_map")
46
+ av.follow_trajectory_goal(trajectory=plan.payload, max_velocity_mps=12.0)
47
+ ```
48
+
49
+ ## Status
50
+
51
+ **v0.1 (this release):**
52
+ - `AutowareAdapter` + `AutowareConfig` + `load_av_config`. Hermetic suite green via fake-`rclpy` / fake-message injection (`pytest reference/av-runtime/tests -q`).
53
+ - The `av` profile is research-grade, not production safety-certified (RFC-0020). Real-vehicle validation on a Linux + Autoware host is a gated follow-up, never claimed from the hermetic suite.
54
+
55
+ ## Core Commitment
56
+
57
+ Business Source License 1.1: free for non-production use, commercial license for production (see [`LICENSING.md`](../../LICENSING.md)). No vendor coupling, no cloud dependency. `rclpy` and the Autoware messages are imported lazily, never at module load.
@@ -0,0 +1,75 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "urml-av-runtime"
7
+ version = "0.5.0"
8
+ description = "Autonomous-vehicle reference runtime for URML — Autoware AD API via rclpy."
9
+ readme = "README.md"
10
+ license = { text = "BUSL-1.1" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "URML Maintainers" }]
13
+ keywords = ["robotics", "autonomous-vehicle", "autoware", "adapi", "ros2", "trajectory", "urml", "runtime"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: Other/Proprietary License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Scientific/Engineering",
23
+ ]
24
+ dependencies = [
25
+ "pydantic>=2.6,<3",
26
+ "PyYAML>=6.0,<7",
27
+ "urml-validator>=0.5.0",
28
+ "urml-ros2-runtime>=0.5.0",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ # rclpy and the Autoware message packages (autoware_adapi_v1_msgs,
33
+ # tier4_planning_msgs, geometry_msgs) ship with a ROS 2 + Autoware
34
+ # install, not from PyPI, so there is no installable extra for them. They
35
+ # are imported lazily by the adapter, so this module loads on every host
36
+ # (Windows included) and the hermetic suite runs without ROS 2. Run the
37
+ # adapter against a real Autoware stack on Linux.
38
+ dev = [
39
+ "pytest>=8",
40
+ "pytest-cov>=5",
41
+ "ruff>=0.5",
42
+ "mypy>=1.10",
43
+ ]
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/urml-dev/URML"
47
+ Repository = "https://github.com/urml-dev/URML"
48
+ Issues = "https://github.com/urml-dev/URML/issues"
49
+
50
+ [tool.hatch.build.targets.wheel]
51
+ packages = ["src/urml_av_runtime"]
52
+
53
+ [tool.ruff]
54
+ line-length = 120
55
+ target-version = "py311"
56
+ src = ["src", "tests"]
57
+
58
+ [tool.ruff.lint]
59
+ select = ["E", "F", "W", "I", "B", "UP", "N", "ANN", "RUF"]
60
+ ignore = ["ANN401"]
61
+
62
+ [tool.ruff.lint.per-file-ignores]
63
+ "tests/*" = ["ANN"]
64
+
65
+ [tool.mypy]
66
+ strict = true
67
+ python_version = "3.11"
68
+ plugins = ["pydantic.mypy"]
69
+ mypy_path = "src"
70
+ packages = ["urml_av_runtime"]
71
+
72
+ [tool.pytest.ini_options]
73
+ minversion = "8.0"
74
+ testpaths = ["tests"]
75
+ addopts = ["-q", "--strict-markers"]
@@ -0,0 +1,26 @@
1
+ """urml_av_runtime — autonomous-vehicle reference runtime for URML.
2
+
3
+ AutowareAdapter (+ AutowareConfig, load_av_config)
4
+ The Autoware Universe AD API (``autoware_adapi_v1_msgs``) backing for
5
+ URML's AV trajectory verbs (RFC-0020): ``plan_path`` sets a route via
6
+ ``/api/routing/set_route_points``; ``follow_trajectory`` engages
7
+ autonomous driving via ``/api/operation_mode/change_to_autonomous``,
8
+ under an optional published speed cap. It is the first substrate to
9
+ implement the ``TrajectoryAdapter`` Protocol (only ``MockROSAdapter``
10
+ did before). rclpy and the Autoware messages are imported lazily, so
11
+ this module loads on every host, including Windows.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from urml_av_runtime._version import __version__
17
+ from urml_av_runtime.adapter import AutowareAdapter
18
+ from urml_av_runtime.config import AutowareConfig, MapPose, load_av_config
19
+
20
+ __all__ = [
21
+ "AutowareAdapter",
22
+ "AutowareConfig",
23
+ "MapPose",
24
+ "__version__",
25
+ "load_av_config",
26
+ ]
@@ -0,0 +1,3 @@
1
+ """Package version. Bumped per release."""
2
+
3
+ __version__ = "0.5.0"
@@ -0,0 +1,308 @@
1
+ """AutowareAdapter — real ROS 2 backing for URML's AV trajectory verbs.
2
+
3
+ Implements the ``TrajectoryAdapter`` Protocol (RFC-0020) against the
4
+ Autoware Universe **AD API** (``autoware_adapi_v1_msgs``). It is the first
5
+ substrate to implement that protocol; until now only ``MockROSAdapter`` did.
6
+
7
+ ## What it maps
8
+
9
+ - ``plan_path`` -> ``plan_trajectory``: set a route to the goal pose through
10
+ the AD API routing service (``/api/routing/set_route_points``). Autoware
11
+ plans the dense trajectory internally from the vehicle's localized pose;
12
+ URML binds a route handle, not raw waypoints (the payload is opaque per the
13
+ protocol contract).
14
+ - ``follow_trajectory`` -> ``follow_trajectory_goal``: optionally publish a
15
+ speed cap (``VelocityLimit`` to the scenario-planning ``max_velocity``
16
+ topic), then engage autonomous driving via the operation-mode service
17
+ (``/api/operation_mode/change_to_autonomous``). Engaging autonomous is what
18
+ makes Autoware follow the planned route.
19
+
20
+ ## Honest boundaries
21
+
22
+ - ``start`` is ignored: Autoware routes from the vehicle's current localized
23
+ pose, not an arbitrary start.
24
+ - ``along`` (an HD-map corridor id) is checked by the validator upstream; it
25
+ is not a field the AD API routing request takes, so it is not forwarded.
26
+ - ``max_accel_mps2`` and ``on_off_route`` are vehicle- and
27
+ planning-configured in Autoware; the adapter records the intent but does not
28
+ set them per call. This is stated, not silently dropped.
29
+ - Every AD API service / topic / message-type name is configurable
30
+ (:class:`AutowareConfig`) so the adapter tracks a specific Autoware release
31
+ without a code change.
32
+
33
+ ## Lazy rclpy
34
+
35
+ ``rclpy`` and the Autoware message packages are imported lazily, so this
36
+ module imports on every host (including Windows) and the hermetic tests run
37
+ without a ROS 2 install. ``rclpy.init()`` is the caller's responsibility, as
38
+ in ``RclpyAdapter``. Real-vehicle behavior is verified separately under a
39
+ gated integration workflow, never in the hermetic suite.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import importlib
45
+ import math
46
+ from contextlib import suppress
47
+ from typing import Any
48
+
49
+ from urml_ros2_runtime.substrate.base import (
50
+ NavigationResult,
51
+ SubstrateResult,
52
+ TrajectoryPlanResult,
53
+ )
54
+
55
+ from urml_av_runtime._version import __version__
56
+ from urml_av_runtime.config import AutowareConfig, MapPose, load_av_config
57
+
58
+ __all__ = ["AutowareAdapter", "AutowareConfig", "MapPose", "__version__", "load_av_config"]
59
+
60
+
61
+ def _require_rclpy() -> Any:
62
+ """Lazy-import rclpy and surface a clear error if it isn't installed."""
63
+ try:
64
+ import rclpy # type: ignore[import-not-found,unused-ignore]
65
+ except ImportError as exc:
66
+ raise RuntimeError(
67
+ "rclpy is not installed. AutowareAdapter requires a ROS 2 + Autoware "
68
+ "environment.\n"
69
+ " On Linux: install ROS 2 and Autoware, source the setup files, then "
70
+ "launch Python.\n"
71
+ " On Windows: this adapter is not supported; use WSL2, or fall back to "
72
+ "MockROSAdapter for development."
73
+ ) from exc
74
+ return rclpy
75
+
76
+
77
+ def _import_type(spec: str) -> Any:
78
+ """Import a ``module:attr`` type spec (e.g. ``geometry_msgs.msg:Pose``)."""
79
+ module_name, _, attr = spec.partition(":")
80
+ if not attr:
81
+ raise ValueError(f"type spec {spec!r} must be 'module:attr'")
82
+ module = importlib.import_module(module_name)
83
+ return getattr(module, attr)
84
+
85
+
86
+ class AutowareAdapter:
87
+ """Autoware AD API backing for URML's ``plan_path`` / ``follow_trajectory``."""
88
+
89
+ def __init__(self, config: AutowareConfig | None = None) -> None:
90
+ self._rclpy = _require_rclpy()
91
+ self._config = config or AutowareConfig()
92
+ self._node = self._rclpy.create_node(
93
+ self._config.node_name,
94
+ namespace=self._config.ros2_namespace,
95
+ )
96
+ # Lazy client / publisher slots — None until first use.
97
+ self._clients: dict[str, Any] = {}
98
+ self._velocity_pub: Any = None
99
+ self._reports: list[dict[str, Any]] = []
100
+ self._closed = False
101
+
102
+ # ------------------------------------------------------------------
103
+ # Lifecycle
104
+ # ------------------------------------------------------------------
105
+
106
+ def close(self) -> None:
107
+ if self._closed:
108
+ return
109
+ with suppress(Exception):
110
+ self._node.destroy_node()
111
+ self._closed = True
112
+
113
+ def __enter__(self) -> AutowareAdapter:
114
+ return self
115
+
116
+ def __exit__(self, *_: object) -> None:
117
+ self.close()
118
+
119
+ # ------------------------------------------------------------------
120
+ # Service / topic plumbing
121
+ # ------------------------------------------------------------------
122
+
123
+ def _client(self, service_name: str, srv_type_spec: str) -> Any:
124
+ client = self._clients.get(service_name)
125
+ if client is None:
126
+ srv_type = _import_type(srv_type_spec)
127
+ client = self._node.create_client(srv_type, service_name)
128
+ self._clients[service_name] = client
129
+ return client
130
+
131
+ def _call_service(
132
+ self, service_name: str, srv_type_spec: str, request: Any
133
+ ) -> tuple[Any | None, str | None]:
134
+ """Call a service and wait. Returns (response, reason). reason is set on failure."""
135
+ client = self._client(service_name, srv_type_spec)
136
+ timeout = self._config.service_timeout_seconds
137
+ if not client.wait_for_service(timeout_sec=timeout):
138
+ return None, f"service_unavailable: {service_name}"
139
+ future = client.call_async(request)
140
+ self._rclpy.spin_until_future_complete(self._node, future, timeout_sec=timeout)
141
+ response = future.result()
142
+ if response is None:
143
+ return None, f"no_response: {service_name}"
144
+ return response, None
145
+
146
+ @staticmethod
147
+ def _status_ok(response: Any) -> bool:
148
+ """AD API responses carry a ResponseStatus with a `success` flag."""
149
+ status = getattr(response, "status", None)
150
+ if status is None:
151
+ # Some services return a bare success field.
152
+ return bool(getattr(response, "success", False))
153
+ return bool(getattr(status, "success", False))
154
+
155
+ @staticmethod
156
+ def _status_message(response: Any) -> str:
157
+ status = getattr(response, "status", None)
158
+ if status is not None:
159
+ return str(getattr(status, "message", "") or "")
160
+ return str(getattr(response, "message", "") or "")
161
+
162
+ def _resolve_goal_pose(self, goal: dict[str, float] | str) -> MapPose | None:
163
+ if isinstance(goal, str):
164
+ return self._config.resolve_pose(goal)
165
+ # A pose dict {x, y, z?, yaw?} from the program.
166
+ return MapPose.model_validate(goal)
167
+
168
+ def _build_pose(self, pose: MapPose) -> Any:
169
+ pose_type = _import_type("geometry_msgs.msg:Pose")
170
+ msg = pose_type()
171
+ msg.position.x = float(pose.x)
172
+ msg.position.y = float(pose.y)
173
+ msg.position.z = float(pose.z)
174
+ # Heading (yaw) as a quaternion about z.
175
+ msg.orientation.z = math.sin(pose.yaw / 2.0)
176
+ msg.orientation.w = math.cos(pose.yaw / 2.0)
177
+ return msg
178
+
179
+ # ------------------------------------------------------------------
180
+ # TrajectoryAdapter (RFC-0020)
181
+ # ------------------------------------------------------------------
182
+
183
+ def plan_trajectory(
184
+ self,
185
+ *,
186
+ start: dict[str, float] | str | None,
187
+ goal: dict[str, float] | str,
188
+ along: str | None = None,
189
+ ) -> TrajectoryPlanResult:
190
+ goal_pose = self._resolve_goal_pose(goal)
191
+ if goal_pose is None:
192
+ return TrajectoryPlanResult(
193
+ success=False,
194
+ reason=(
195
+ f"goal_not_resolvable: {goal!r} is declared in the manifest but not "
196
+ "mapped to a pose in av_adapter.yaml `location_to_pose`."
197
+ ),
198
+ )
199
+
200
+ if self._config.clear_route_before_plan:
201
+ clear_type = _import_type(self._config.clear_route_srv_type)
202
+ _resp, reason = self._call_service(
203
+ self._config.clear_route_service, self._config.clear_route_srv_type, clear_type.Request()
204
+ )
205
+ # A clear failure is not fatal (there may be no route yet); the
206
+ # set below is the authority. Only a service-unavailable is worth
207
+ # noting, and set_route will surface it too, so continue.
208
+
209
+ set_type = _import_type(self._config.set_route_srv_type)
210
+ request = set_type.Request()
211
+ # header: stamp + frame. Fields present on the AD API request.
212
+ if hasattr(request, "header"):
213
+ request.header.frame_id = self._config.map_frame
214
+ with suppress(Exception):
215
+ request.header.stamp = self._node.get_clock().now().to_msg()
216
+ request.goal = self._build_pose(goal_pose)
217
+ if hasattr(request, "waypoints"):
218
+ request.waypoints = []
219
+
220
+ response, reason = self._call_service(
221
+ self._config.set_route_service, self._config.set_route_srv_type, request
222
+ )
223
+ if response is None:
224
+ return TrajectoryPlanResult(success=False, reason=reason)
225
+ if not self._status_ok(response):
226
+ return TrajectoryPlanResult(
227
+ success=False,
228
+ reason=f"route_rejected: {self._status_message(response) or 'AD API declined the route'}",
229
+ )
230
+ return TrajectoryPlanResult(
231
+ success=True,
232
+ payload={
233
+ "goal": {"x": goal_pose.x, "y": goal_pose.y, "z": goal_pose.z, "yaw": goal_pose.yaw},
234
+ "frame": self._config.map_frame,
235
+ "along": along,
236
+ "waypoints": [],
237
+ "route_set": True,
238
+ },
239
+ )
240
+
241
+ def follow_trajectory_goal(
242
+ self,
243
+ *,
244
+ trajectory: dict[str, Any] | None,
245
+ max_velocity_mps: float | None = None,
246
+ max_accel_mps2: float | None = None,
247
+ on_off_route: str = "abort",
248
+ ) -> NavigationResult:
249
+ if trajectory is None or not trajectory.get("route_set"):
250
+ return NavigationResult(
251
+ success=False,
252
+ reason=(
253
+ "no_route: follow_trajectory needs a route bound by plan_path "
254
+ "(the trajectory payload has no `route_set`)."
255
+ ),
256
+ )
257
+ if max_velocity_mps is not None:
258
+ self._publish_velocity_limit(max_velocity_mps)
259
+
260
+ change_type = _import_type(self._config.change_mode_srv_type)
261
+ response, reason = self._call_service(
262
+ self._config.change_to_autonomous_service,
263
+ self._config.change_mode_srv_type,
264
+ change_type.Request(),
265
+ )
266
+ if response is None:
267
+ return NavigationResult(success=False, reason=reason)
268
+ if not self._status_ok(response):
269
+ return NavigationResult(
270
+ success=False,
271
+ reason=(
272
+ f"engage_rejected: {self._status_message(response) or 'AD API declined autonomous mode'}"
273
+ ),
274
+ )
275
+ return NavigationResult(success=True, frame=self._config.map_frame)
276
+
277
+ def _publish_velocity_limit(self, max_velocity_mps: float) -> None:
278
+ if self._velocity_pub is None:
279
+ msg_type = _import_type(self._config.velocity_limit_msg_type)
280
+ self._velocity_pub = self._node.create_publisher(
281
+ msg_type, self._config.velocity_limit_topic, 1
282
+ )
283
+ msg_type = _import_type(self._config.velocity_limit_msg_type)
284
+ msg = msg_type()
285
+ if hasattr(msg, "stamp"):
286
+ with suppress(Exception):
287
+ msg.stamp = self._node.get_clock().now().to_msg()
288
+ msg.max_velocity = float(max_velocity_mps)
289
+ self._velocity_pub.publish(msg)
290
+
291
+ # ------------------------------------------------------------------
292
+ # Non-actuating base primitives an AV program may use
293
+ # ------------------------------------------------------------------
294
+
295
+ def wait_passively(self, *, duration_seconds: float) -> SubstrateResult:
296
+ return SubstrateResult(success=True)
297
+
298
+ def emit_report(
299
+ self,
300
+ *,
301
+ to: str,
302
+ facts: dict[str, Any],
303
+ attachments: list[str] | None = None,
304
+ status: str = "success",
305
+ severity: str = "info",
306
+ ) -> SubstrateResult:
307
+ self._reports.append({"to": to, "status": status, "severity": severity, "facts": facts})
308
+ return SubstrateResult(success=True)
@@ -0,0 +1,80 @@
1
+ """Deployment-side configuration for the Autoware AV adapter.
2
+
3
+ Which WGS84/map pose a manifest-declared location (``depot``, ``dropoff``)
4
+ resolves to, and which Autoware AD API service / topic names to drive, is
5
+ deployment-specific, so it lives here rather than in the URML
6
+ program/manifest/envelope (the ros2 / px4 / ardupilot ``location_to_*``
7
+ precedent).
8
+
9
+ The defaults track the documented Autoware Universe AD API
10
+ (``autoware_adapi_v1_msgs``): routing via ``/api/routing/set_route_points``,
11
+ actuation via ``/api/operation_mode/change_to_autonomous``, and a speed cap
12
+ published to the scenario-planning ``max_velocity`` topic. Every name is
13
+ overridable so the adapter tracks a specific Autoware release without a code
14
+ change.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from pathlib import Path
20
+
21
+ import yaml
22
+ from pydantic import BaseModel, ConfigDict, Field
23
+
24
+
25
+ class MapPose(BaseModel):
26
+ """A goal pose in the map frame. ``yaw`` is the heading in radians."""
27
+
28
+ model_config = ConfigDict(extra="forbid")
29
+
30
+ x: float
31
+ y: float
32
+ z: float = 0.0
33
+ yaw: float = 0.0
34
+
35
+
36
+ class AutowareConfig(BaseModel):
37
+ """Connection + AD API binding config for :class:`AutowareAdapter`."""
38
+
39
+ model_config = ConfigDict(extra="forbid")
40
+
41
+ ros2_namespace: str = Field(default="", description="ROS 2 namespace for the adapter node.")
42
+ node_name: str = Field(default="urml_av_adapter", description="Node name the adapter creates.")
43
+ map_frame: str = Field(default="map", description="Frame id stamped on the route goal.")
44
+
45
+ location_to_pose: dict[str, MapPose] = Field(
46
+ default_factory=dict,
47
+ description="Map manifest-declared location names (depot, dropoff, ...) to map-frame poses.",
48
+ )
49
+
50
+ # AD API surface (autoware_adapi_v1_msgs). Overridable per Autoware release.
51
+ set_route_service: str = "/api/routing/set_route_points"
52
+ clear_route_service: str = "/api/routing/clear_route"
53
+ change_to_autonomous_service: str = "/api/operation_mode/change_to_autonomous"
54
+ set_route_srv_type: str = "autoware_adapi_v1_msgs.srv:SetRoutePoints"
55
+ clear_route_srv_type: str = "autoware_adapi_v1_msgs.srv:ClearRoute"
56
+ change_mode_srv_type: str = "autoware_adapi_v1_msgs.srv:ChangeOperationMode"
57
+
58
+ # Speed cap: a latched VelocityLimit publish, since the AD API has no
59
+ # per-call velocity-limit service across releases.
60
+ velocity_limit_topic: str = "/planning/scenario_planning/max_velocity"
61
+ velocity_limit_msg_type: str = "tier4_planning_msgs.msg:VelocityLimit"
62
+
63
+ clear_route_before_plan: bool = Field(
64
+ default=True,
65
+ description="Clear any existing route before setting a new one (idempotent planning).",
66
+ )
67
+ service_timeout_seconds: float = Field(default=10.0, gt=0)
68
+
69
+ def resolve_pose(self, name: str) -> MapPose | None:
70
+ return self.location_to_pose.get(name)
71
+
72
+
73
+ def load_av_config(path: str | Path) -> AutowareConfig:
74
+ """Parse an ``av_adapter.yaml`` file into an :class:`AutowareConfig`."""
75
+ p = Path(path)
76
+ with p.open(encoding="utf-8") as fh:
77
+ data = yaml.safe_load(fh) or {}
78
+ if not isinstance(data, dict):
79
+ raise ValueError(f"av-config file {p} did not contain a YAML mapping at the top level.")
80
+ return AutowareConfig.model_validate(data)
File without changes
@@ -0,0 +1,295 @@
1
+ """Hermetic unit tests for AutowareAdapter — no ROS 2 / Autoware install.
2
+
3
+ Fake ``rclpy`` and the Autoware message packages (``geometry_msgs.msg``,
4
+ ``autoware_adapi_v1_msgs.srv``, ``tier4_planning_msgs.msg``) are injected into
5
+ ``sys.modules`` so the adapter's lazy imports resolve against controllable
6
+ doubles. The fakes implement only the slice the adapter touches; real Autoware
7
+ behavior is verified separately on a Linux + Autoware host.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ import sys
14
+ from collections.abc import Iterator
15
+ from types import ModuleType, SimpleNamespace
16
+ from typing import Any
17
+
18
+ import pytest
19
+ from urml_ros2_runtime.substrate.base import TrajectoryAdapter
20
+
21
+ # --------------------------------------------------------------------------
22
+ # Fakes
23
+ # --------------------------------------------------------------------------
24
+
25
+
26
+ class _FakeFuture:
27
+ def __init__(self, value: Any) -> None:
28
+ self._value = value
29
+
30
+ def result(self) -> Any:
31
+ return self._value
32
+
33
+
34
+ class _FakeClient:
35
+ # Test-level controls, reset by the fixture.
36
+ available: bool = True
37
+ success_by_service: dict[str, bool] = {} # noqa: RUF012
38
+ calls: list[dict[str, Any]] = [] # noqa: RUF012
39
+
40
+ def __init__(self, _srv_type: Any, service_name: str) -> None:
41
+ self.service_name = service_name
42
+
43
+ def wait_for_service(self, *, timeout_sec: float) -> bool:
44
+ return _FakeClient.available
45
+
46
+ def call_async(self, request: Any) -> _FakeFuture:
47
+ _FakeClient.calls.append({"service": self.service_name, "request": request})
48
+ ok = _FakeClient.success_by_service.get(self.service_name, True)
49
+ response = SimpleNamespace(status=SimpleNamespace(success=ok, message="" if ok else "declined"))
50
+ return _FakeFuture(response)
51
+
52
+
53
+ class _FakePublisher:
54
+ published: list[dict[str, Any]] = [] # noqa: RUF012
55
+
56
+ def __init__(self, topic: str) -> None:
57
+ self.topic = topic
58
+
59
+ def publish(self, msg: Any) -> None:
60
+ _FakePublisher.published.append({"topic": self.topic, "msg": msg})
61
+
62
+
63
+ class _FakeClock:
64
+ def now(self) -> Any:
65
+ return SimpleNamespace(to_msg=lambda: SimpleNamespace())
66
+
67
+
68
+ class _FakeNode:
69
+ def __init__(self, name: str, namespace: str = "") -> None:
70
+ self.name = name
71
+ self.namespace = namespace
72
+ self.destroyed = False
73
+
74
+ def create_client(self, srv_type: Any, service_name: str) -> _FakeClient:
75
+ return _FakeClient(srv_type, service_name)
76
+
77
+ def create_publisher(self, _msg_type: Any, topic: str, _qos: int) -> _FakePublisher:
78
+ return _FakePublisher(topic)
79
+
80
+ def get_clock(self) -> _FakeClock:
81
+ return _FakeClock()
82
+
83
+ def destroy_node(self) -> None:
84
+ self.destroyed = True
85
+
86
+
87
+ # ROS message doubles ------------------------------------------------------
88
+
89
+
90
+ class _Pose:
91
+ def __init__(self) -> None:
92
+ self.position = SimpleNamespace(x=0.0, y=0.0, z=0.0)
93
+ self.orientation = SimpleNamespace(x=0.0, y=0.0, z=0.0, w=1.0)
94
+
95
+
96
+ class _Header:
97
+ def __init__(self) -> None:
98
+ self.frame_id = ""
99
+ self.stamp = None
100
+
101
+
102
+ class _SetRoutePointsRequest:
103
+ def __init__(self) -> None:
104
+ self.header = _Header()
105
+ self.goal = None
106
+ self.waypoints: list[Any] = []
107
+
108
+
109
+ class _SetRoutePoints:
110
+ Request = _SetRoutePointsRequest
111
+
112
+
113
+ class _EmptyRequest:
114
+ pass
115
+
116
+
117
+ class _ClearRoute:
118
+ Request = _EmptyRequest
119
+
120
+
121
+ class _ChangeOperationMode:
122
+ Request = _EmptyRequest
123
+
124
+
125
+ class _VelocityLimit:
126
+ def __init__(self) -> None:
127
+ self.stamp = None
128
+ self.max_velocity = 0.0
129
+
130
+
131
+ def _make_module(name: str, **attrs: Any) -> ModuleType:
132
+ mod = ModuleType(name)
133
+ for k, v in attrs.items():
134
+ setattr(mod, k, v)
135
+ return mod
136
+
137
+
138
+ @pytest.fixture
139
+ def fake_ros() -> Iterator[None]:
140
+ _FakeClient.available = True
141
+ _FakeClient.success_by_service = {}
142
+ _FakeClient.calls = []
143
+ _FakePublisher.published = []
144
+
145
+ rclpy = _make_module(
146
+ "rclpy",
147
+ create_node=lambda name, namespace="": _FakeNode(name, namespace),
148
+ spin_until_future_complete=lambda _node, _future, timeout_sec=None: None,
149
+ )
150
+ geometry = _make_module("geometry_msgs")
151
+ geometry_msg = _make_module("geometry_msgs.msg", Pose=_Pose)
152
+ adapi = _make_module("autoware_adapi_v1_msgs")
153
+ adapi_srv = _make_module(
154
+ "autoware_adapi_v1_msgs.srv",
155
+ SetRoutePoints=_SetRoutePoints,
156
+ ClearRoute=_ClearRoute,
157
+ ChangeOperationMode=_ChangeOperationMode,
158
+ )
159
+ tier4 = _make_module("tier4_planning_msgs")
160
+ tier4_msg = _make_module("tier4_planning_msgs.msg", VelocityLimit=_VelocityLimit)
161
+
162
+ mods = {
163
+ "rclpy": rclpy,
164
+ "geometry_msgs": geometry,
165
+ "geometry_msgs.msg": geometry_msg,
166
+ "autoware_adapi_v1_msgs": adapi,
167
+ "autoware_adapi_v1_msgs.srv": adapi_srv,
168
+ "tier4_planning_msgs": tier4,
169
+ "tier4_planning_msgs.msg": tier4_msg,
170
+ }
171
+ saved = {k: sys.modules.get(k) for k in mods}
172
+ sys.modules.update(mods)
173
+ try:
174
+ yield
175
+ finally:
176
+ for k, v in saved.items():
177
+ if v is None:
178
+ sys.modules.pop(k, None)
179
+ else:
180
+ sys.modules[k] = v
181
+
182
+
183
+ def _config(**over: Any) -> Any:
184
+ from urml_av_runtime import AutowareConfig
185
+
186
+ base: dict[str, Any] = {
187
+ "location_to_pose": {
188
+ "depot": {"x": 0.0, "y": 0.0, "yaw": 0.0},
189
+ "dropoff": {"x": 30.0, "y": 12.0, "yaw": math.pi / 2},
190
+ }
191
+ }
192
+ base.update(over)
193
+ return AutowareConfig.model_validate(base)
194
+
195
+
196
+ # --------------------------------------------------------------------------
197
+ # Tests
198
+ # --------------------------------------------------------------------------
199
+
200
+
201
+ def test_is_a_trajectory_adapter(fake_ros: None) -> None:
202
+ from urml_av_runtime import AutowareAdapter
203
+
204
+ with AutowareAdapter(_config()) as a:
205
+ assert isinstance(a, TrajectoryAdapter)
206
+
207
+
208
+ def test_plan_then_follow_happy_path(fake_ros: None) -> None:
209
+ from urml_av_runtime import AutowareAdapter
210
+
211
+ with AutowareAdapter(_config()) as a:
212
+ plan = a.plan_trajectory(start=None, goal="dropoff", along="city_map")
213
+ assert plan.success and plan.payload is not None
214
+ assert plan.payload["route_set"] is True
215
+ assert plan.payload["goal"]["x"] == 30.0
216
+ assert plan.payload["along"] == "city_map"
217
+
218
+ nav = a.follow_trajectory_goal(trajectory=plan.payload, max_velocity_mps=12.0)
219
+ assert nav.success
220
+
221
+ services = [c["service"] for c in _FakeClient.calls]
222
+ assert "/api/routing/set_route_points" in services
223
+ assert "/api/operation_mode/change_to_autonomous" in services
224
+ assert "/api/routing/clear_route" in services # cleared before planning
225
+
226
+ # Goal pose built with yaw -> quaternion about z.
227
+ set_call = next(c for c in _FakeClient.calls if c["service"] == "/api/routing/set_route_points")
228
+ goal = set_call["request"].goal
229
+ assert goal.position.x == 30.0 and goal.position.y == 12.0
230
+ assert goal.orientation.z == pytest.approx(math.sin(math.pi / 4))
231
+ assert goal.orientation.w == pytest.approx(math.cos(math.pi / 4))
232
+
233
+ # Speed cap published to the velocity-limit topic.
234
+ assert len(_FakePublisher.published) == 1
235
+ pub = _FakePublisher.published[0]
236
+ assert pub["topic"] == "/planning/scenario_planning/max_velocity"
237
+ assert pub["msg"].max_velocity == 12.0
238
+
239
+
240
+ def test_plan_goal_as_pose_dict(fake_ros: None) -> None:
241
+ from urml_av_runtime import AutowareAdapter
242
+
243
+ with AutowareAdapter(_config()) as a:
244
+ plan = a.plan_trajectory(start=None, goal={"x": 5.0, "y": -2.0})
245
+ assert plan.success and plan.payload is not None
246
+ assert plan.payload["goal"] == {"x": 5.0, "y": -2.0, "z": 0.0, "yaw": 0.0}
247
+
248
+
249
+ def test_plan_goal_unresolvable(fake_ros: None) -> None:
250
+ from urml_av_runtime import AutowareAdapter
251
+
252
+ with AutowareAdapter(_config()) as a:
253
+ plan = a.plan_trajectory(start=None, goal="nowhere")
254
+ assert plan.success is False
255
+ assert plan.reason is not None and plan.reason.startswith("goal_not_resolvable")
256
+
257
+
258
+ def test_route_rejected_by_ad_api(fake_ros: None) -> None:
259
+ from urml_av_runtime import AutowareAdapter
260
+
261
+ _FakeClient.success_by_service = {"/api/routing/set_route_points": False}
262
+ with AutowareAdapter(_config()) as a:
263
+ plan = a.plan_trajectory(start=None, goal="dropoff")
264
+ assert plan.success is False
265
+ assert plan.reason is not None and plan.reason.startswith("route_rejected")
266
+
267
+
268
+ def test_engage_rejected_by_ad_api(fake_ros: None) -> None:
269
+ from urml_av_runtime import AutowareAdapter
270
+
271
+ _FakeClient.success_by_service = {"/api/operation_mode/change_to_autonomous": False}
272
+ with AutowareAdapter(_config()) as a:
273
+ plan = a.plan_trajectory(start=None, goal="dropoff")
274
+ nav = a.follow_trajectory_goal(trajectory=plan.payload)
275
+ assert nav.success is False
276
+ assert nav.reason is not None and nav.reason.startswith("engage_rejected")
277
+
278
+
279
+ def test_follow_without_a_route(fake_ros: None) -> None:
280
+ from urml_av_runtime import AutowareAdapter
281
+
282
+ with AutowareAdapter(_config()) as a:
283
+ nav = a.follow_trajectory_goal(trajectory=None)
284
+ assert nav.success is False
285
+ assert nav.reason is not None and nav.reason.startswith("no_route")
286
+
287
+
288
+ def test_service_unavailable(fake_ros: None) -> None:
289
+ from urml_av_runtime import AutowareAdapter
290
+
291
+ _FakeClient.available = False
292
+ with AutowareAdapter(_config()) as a:
293
+ plan = a.plan_trajectory(start=None, goal="dropoff")
294
+ assert plan.success is False
295
+ assert plan.reason is not None and "service_unavailable" in plan.reason