urml-legged-runtime 0.5.2__py3-none-any.whl

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,44 @@
1
+ """urml_legged_runtime — legged/quadruped reference runtime for URML.
2
+
3
+ One first-class adapter per vendor, both implementing the
4
+ substrate-neutral ``ROSAdapter`` Protocol:
5
+
6
+ SpotAdapter (+ SpotConfig, load_spot_config)
7
+ Boston Dynamics Spot via the ``bosdyn`` gRPC SDK. No ROS 2
8
+ dependency (the [spot] extra installs the bosdyn wheels). Like
9
+ PX4Adapter, a second proof the spec carries no ROS assumptions.
10
+
11
+ AnymalAdapter
12
+ ANYbotics ANYmal — a ROS 2 quadruped, so it composes the ROS 2
13
+ runtime's RclpyAdapter (the industrial-arm single-sourced-substrate
14
+ pattern). No duplicated ROS 2 plumbing.
15
+
16
+ LEGGED_ADAPTERS
17
+ Name → class registry ({"spot": SpotAdapter, "anymal":
18
+ AnymalAdapter}) for config-driven selection (CI matrices, the
19
+ conformance adapter_factory).
20
+
21
+ Both bosdyn and rclpy are imported lazily, so this module loads on
22
+ every host; constructing an adapter needs that vendor's runtime
23
+ (the [spot] extra, or a sourced ROS 2 environment).
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from urml_legged_runtime._version import __version__
29
+ from urml_legged_runtime.anymal import AnymalAdapter
30
+ from urml_legged_runtime.spot import SpotAdapter, SpotConfig, load_spot_config
31
+
32
+ LEGGED_ADAPTERS: dict[str, type] = {
33
+ "spot": SpotAdapter,
34
+ "anymal": AnymalAdapter,
35
+ }
36
+
37
+ __all__ = [
38
+ "LEGGED_ADAPTERS",
39
+ "AnymalAdapter",
40
+ "SpotAdapter",
41
+ "SpotConfig",
42
+ "__version__",
43
+ "load_spot_config",
44
+ ]
@@ -0,0 +1,3 @@
1
+ """Package version. Bumped per release."""
2
+
3
+ __version__ = "0.5.2"
@@ -0,0 +1,244 @@
1
+ """AnymalAdapter — ANYbotics ANYmal, a ROS 2 inspection quadruped.
2
+
3
+ Unlike Spot (its own gRPC SDK), ANYmal speaks ROS 2, so this adapter
4
+ composes the ROS 2 runtime's :class:`RclpyAdapter` — the same
5
+ single-sourced-substrate pattern the industrial-arm runtime uses for
6
+ ABB/FANUC/KUKA/YASKAWA. The per-brand surface is real (distinct class,
7
+ brand-scoped not-supported tag); the ROS 2 plumbing is not duplicated.
8
+
9
+ A bare ANYmal is a four-legged inspection platform: it navigates
10
+ (``move_to`` / ``hover``), dwells, measures (inspection-payload
11
+ sensors), waits on cell/site signals, and reports. It has no arm and no
12
+ flight. Those primitives return ``not_supported_on_quadruped[anymal]``
13
+ rather than raising — the same pattern PX4Adapter and the industrial
14
+ arms use. A cell pairing ANYmal with a manipulation or vision payload
15
+ dispatches through a companion adapter (the drone-stack pattern).
16
+
17
+ ``rclpy`` is imported lazily inside :class:`RclpyAdapter`, so importing
18
+ this module works on every host; constructing the adapter needs a
19
+ sourced ROS 2 environment. Hermetic tests inject a fake inner adapter
20
+ via ``inner_factory`` and never touch rclpy.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from collections.abc import Callable
26
+ from contextlib import suppress
27
+ from typing import Any, Literal
28
+
29
+ from urml_ros2_runtime.substrate.adapter_config import AdapterConfig
30
+ from urml_ros2_runtime.substrate.base import (
31
+ ProgramCallResult,
32
+ unsupported_program_call,
33
+ CaptureResult,
34
+ DetectionResult,
35
+ ListenResult,
36
+ ManipulationResult,
37
+ MeasurementResult,
38
+ NavigationResult,
39
+ ROSAdapter,
40
+ ScanResult,
41
+ SubstrateResult,
42
+ WaitResult,
43
+ )
44
+ from urml_ros2_runtime.substrate.rclpy_adapter import RclpyAdapter
45
+
46
+ __all__ = ["AnymalAdapter"]
47
+
48
+ _NOT_SUPPORTED = (
49
+ "not_supported_on_quadruped[anymal]: a bare ANYmal inspection robot has no "
50
+ "{capability}. Pair it with a companion adapter (manipulation / vision "
51
+ "payload) for full coverage; the URML program, manifest, and validator "
52
+ "are unchanged."
53
+ )
54
+
55
+ InnerFactory = Callable[[], ROSAdapter]
56
+
57
+
58
+ class AnymalAdapter:
59
+ """ANYbotics ANYmal adapter (ROS 2), composing RclpyAdapter."""
60
+
61
+ BRAND = "anymal"
62
+
63
+ def __init__(
64
+ self,
65
+ config: AdapterConfig | None = None,
66
+ *,
67
+ node_name: str = "urml_anymal_quadruped",
68
+ inner_factory: InnerFactory | None = None,
69
+ ) -> None:
70
+ self._config = config or AdapterConfig()
71
+ factory: InnerFactory = inner_factory or (lambda: RclpyAdapter(self._config, node_name=node_name))
72
+ self._inner: ROSAdapter = factory()
73
+ self._closed = False
74
+
75
+ def close(self) -> None:
76
+ if self._closed:
77
+ return
78
+ inner_close = getattr(self._inner, "close", None)
79
+ if callable(inner_close):
80
+ with suppress(Exception):
81
+ inner_close()
82
+ self._closed = True
83
+
84
+ def __enter__(self) -> AnymalAdapter:
85
+ return self
86
+
87
+ def __exit__(self, *_: object) -> None:
88
+ self.close()
89
+
90
+ def _reason(self, capability: str) -> str:
91
+ return _NOT_SUPPORTED.format(capability=capability)
92
+
93
+ # ------------------------------------------------------------------
94
+ # Supported — delegate to the composed RclpyAdapter
95
+ # ------------------------------------------------------------------
96
+
97
+ def send_navigation_goal(
98
+ self,
99
+ *,
100
+ location: str | None = None,
101
+ pose: dict[str, float] | None = None,
102
+ frame: str | None = None,
103
+ carrying: dict[str, Any] | None = None,
104
+ speed: float | None = None,
105
+ ) -> NavigationResult:
106
+ return self._inner.send_navigation_goal(
107
+ location=location, pose=pose, frame=frame, carrying=carrying, speed=speed
108
+ )
109
+
110
+ def take_measurement(self, *, what: str, target: str | None, sensor: str | None) -> MeasurementResult:
111
+ return self._inner.take_measurement(what=what, target=target, sensor=sensor)
112
+
113
+ def wait_for_condition(
114
+ self,
115
+ *,
116
+ kind: Literal["event", "signal", "input", "sensor_threshold"],
117
+ name: str | None,
118
+ input_mode: str | None,
119
+ threshold: dict[str, Any] | None,
120
+ timeout_seconds: float | None,
121
+ ) -> WaitResult:
122
+ return self._inner.wait_for_condition(
123
+ kind=kind, name=name, input_mode=input_mode, threshold=threshold, timeout_seconds=timeout_seconds
124
+ )
125
+
126
+ def wait_passively(self, *, duration_seconds: float) -> SubstrateResult:
127
+ return self._inner.wait_passively(duration_seconds=duration_seconds)
128
+
129
+ def emit_report(
130
+ self,
131
+ *,
132
+ to: str,
133
+ facts: dict[str, Any],
134
+ attachments: list[str] | None,
135
+ status: Literal["success", "partial", "failure"],
136
+ severity: Literal["info", "notice", "warning", "error"],
137
+ ) -> SubstrateResult:
138
+ return self._inner.emit_report(
139
+ to=to, facts=facts, attachments=attachments, status=status, severity=severity
140
+ )
141
+
142
+ # ------------------------------------------------------------------
143
+ # Not supported on a bare ANYmal
144
+ # ------------------------------------------------------------------
145
+
146
+ def send_manipulation_goal(
147
+ self,
148
+ *,
149
+ action: Literal["grasp", "release"],
150
+ target: dict[str, Any] | None = None,
151
+ force_n: float | None = None,
152
+ approach: Literal["top", "side", "front", "auto"] = "auto",
153
+ release_mode: Literal["drop", "place", "hand_to_user"] | None = None,
154
+ release_at: dict[str, Any] | str | None = None,
155
+ arm: str | None = None,
156
+ grasp_type: str | None = None,
157
+ target_motion: str | None = None,
158
+ ) -> ManipulationResult:
159
+ return ManipulationResult(success=False, reason=self._reason("arm"))
160
+
161
+ def send_docking_goal(self, *, station: str, service: str, until: str | None = None) -> NavigationResult:
162
+ return NavigationResult(success=False, reason=self._reason("docking station"))
163
+
164
+ def query_detection(
165
+ self,
166
+ *,
167
+ object_class: str,
168
+ attributes: dict[str, Any] | None = None,
169
+ where_near: str | None = None,
170
+ where_within: float | None = None,
171
+ ) -> DetectionResult:
172
+ return DetectionResult(success=False, reason=self._reason("onboard object detection"))
173
+
174
+ def run_scan(
175
+ self,
176
+ *,
177
+ area: dict[str, Any],
178
+ pattern: Literal["serpentine", "spiral", "grid", "adaptive"],
179
+ overlap: float,
180
+ altitude: float | None,
181
+ media: Literal["photo", "video", "sensor_only"],
182
+ sensor: str | None,
183
+ ) -> ScanResult:
184
+ return ScanResult(success=False, reason=self._reason("area-scan payload"))
185
+
186
+ def capture_media(
187
+ self,
188
+ *,
189
+ media: Literal["photo", "video"],
190
+ target: str | None,
191
+ duration_seconds: float | None,
192
+ attributes: dict[str, Any] | None,
193
+ camera: str | None = None,
194
+ ) -> CaptureResult:
195
+ return CaptureResult(success=False, reason=self._reason("capture payload"))
196
+
197
+ def emit_speech(
198
+ self,
199
+ *,
200
+ utterance: str,
201
+ locale: str | None,
202
+ style: Literal["notice", "warning", "conversational"],
203
+ interrupt: bool,
204
+ ) -> SubstrateResult:
205
+ return SubstrateResult(success=False, reason=self._reason("speaker"))
206
+
207
+ def acquire_speech(
208
+ self,
209
+ *,
210
+ prompt: str | None,
211
+ locale: str | None,
212
+ timeout_seconds: float | None,
213
+ expected: Literal["free_form", "confirmation", "choice"],
214
+ choices: list[str] | None,
215
+ ) -> ListenResult:
216
+ return ListenResult(success=False, reason=self._reason("microphone"))
217
+
218
+ def send_takeoff_goal(self, *, altitude: float, climb_rate: float | None = None) -> NavigationResult:
219
+ return NavigationResult(success=False, reason=self._reason("flight capability"))
220
+
221
+ def send_land_goal(
222
+ self,
223
+ *,
224
+ at: str | None = None,
225
+ precision: Literal["standard", "precise"] = "standard",
226
+ ) -> NavigationResult:
227
+ return NavigationResult(success=False, reason=self._reason("flight capability"))
228
+
229
+ def send_return_to_home_goal(
230
+ self,
231
+ *,
232
+ speed: float | None = None,
233
+ altitude: float | None = None,
234
+ ) -> NavigationResult:
235
+ return NavigationResult(success=False, reason=self._reason("flight capability"))
236
+
237
+ def call_named_program(
238
+ self,
239
+ *,
240
+ name: str,
241
+ args: dict[str, Any] | None = None,
242
+ ) -> ProgramCallResult:
243
+ """``call_program``: this substrate exposes no named programs (RFC-0015)."""
244
+ return unsupported_program_call('legged')
File without changes
@@ -0,0 +1,450 @@
1
+ """SpotAdapter — Boston Dynamics Spot, via the ``bosdyn`` gRPC SDK.
2
+
3
+ Implements the substrate-neutral ``ROSAdapter`` Protocol. **No ROS 2
4
+ dependency** — Spot speaks its own gRPC SDK, so this adapter (like
5
+ PX4Adapter for MAVLink) is a second proof that URML's spec carries no
6
+ ROS assumptions.
7
+
8
+ ## Lazy bosdyn
9
+
10
+ ``bosdyn-*`` are normal PyPI wheels, but imported lazily at construction
11
+ so ``import urml_legged_runtime`` works on every host (Windows included).
12
+ Constructing :class:`SpotAdapter` needs the ``[spot]`` extra; the error
13
+ when it is missing is clear and actionable. Spot is also credentialed:
14
+ :class:`SpotConfig` stores the *names* of the environment variables that
15
+ hold the username/password, never the secrets themselves.
16
+
17
+ ## v0.1 method coverage
18
+
19
+ Supported (mapped to bosdyn clients):
20
+
21
+ - ``move_to`` / ``hover`` → GraphNav navigation to a configured waypoint
22
+ (location name → waypoint id via :class:`SpotConfig`), or a body
23
+ trajectory command when a pose is given.
24
+ - ``dock`` → ``bosdyn.client.docking`` blocking dock.
25
+ - ``wait`` → a held stand command for the duration.
26
+ - ``measure`` → robot-state telemetry (battery, e-stop) — *partial*.
27
+ - ``wait_for`` → robot-state poll against a predicate — *partial*.
28
+ - ``report`` → structured record to a local sink (no cloud — the
29
+ manifesto bars cloud deps in reference runtimes).
30
+ - ``scan`` → documented not-supported result: this adapter does not
31
+ expand an area into waypoints or capture along them.
32
+
33
+ Not supported on a bare Spot (no arm / not native), returned not raised
34
+ as ``not_supported_on_spot``: ``grasp`` / ``release`` (needs the Spot
35
+ Arm; a manifest with ``manipulation`` + the arm SDK is a follow-up),
36
+ ``detect`` (general off-board vision), ``capture``, ``speak``,
37
+ ``listen``, and the drone trio ``take_off`` / ``land`` /
38
+ ``return_to_home``. Failures are returned, never raised, except an
39
+ unrecoverable transport break (the runtime wraps that).
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import os
45
+ import time
46
+ from contextlib import suppress
47
+ from typing import Any, Literal
48
+
49
+ import yaml
50
+ from pydantic import BaseModel, ConfigDict, Field
51
+ from urml_ros2_runtime.substrate.base import (
52
+ CaptureResult,
53
+ DetectionResult,
54
+ ListenResult,
55
+ ManipulationResult,
56
+ MeasurementResult,
57
+ NavigationResult,
58
+ ProgramCallResult,
59
+ ScanResult,
60
+ SubstrateResult,
61
+ WaitResult,
62
+ unsupported_program_call,
63
+ )
64
+
65
+ from urml_legged_runtime._version import __version__
66
+
67
+ __all__ = ["SpotAdapter", "SpotConfig", "__version__", "load_spot_config"]
68
+
69
+ _NOT_SUPPORTED = (
70
+ "not_supported_on_spot: a bare Spot has no {capability}. Pair Spot with "
71
+ "the Spot Arm SDK (manipulation) or a vision/speech companion adapter for "
72
+ "full coverage; the URML program, manifest, and validator are unchanged."
73
+ )
74
+
75
+
76
+ class SpotConfig(BaseModel):
77
+ """Deployment-side Spot connection config.
78
+
79
+ Credentials are referenced by environment-variable *name* — the
80
+ adapter reads ``os.environ`` at connect time. Secrets never live in
81
+ this file or in the URML artifacts.
82
+ """
83
+
84
+ model_config = ConfigDict(extra="forbid")
85
+
86
+ hostname: str = Field(
87
+ default="192.168.80.3",
88
+ description="Spot/sim gRPC endpoint. The robot's default robot-network address.",
89
+ )
90
+ username_env: str = Field(
91
+ default="BOSDYN_CLIENT_USERNAME",
92
+ description="Name of the env var holding the Spot username.",
93
+ )
94
+ password_env: str = Field(
95
+ default="BOSDYN_CLIENT_PASSWORD",
96
+ description="Name of the env var holding the Spot password.",
97
+ )
98
+ location_to_waypoint: dict[str, str] = Field(
99
+ default_factory=dict,
100
+ description="Map manifest-declared location names to GraphNav waypoint ids.",
101
+ )
102
+ command_timeout_seconds: float = 10.0
103
+ arm_attached: bool = Field(
104
+ default=False,
105
+ description=(
106
+ "True when the deployment carries the Spot Arm. Enables grasp/release "
107
+ "through the manipulation-api and robot-command services; a bare Spot "
108
+ "keeps returning the not-supported sentinel."
109
+ ),
110
+ )
111
+ grasp_frame: str = Field(
112
+ default="vision",
113
+ description="Spot frame a resolved target pose is expressed in for PickObject.",
114
+ )
115
+
116
+ def resolve_location(self, name: str) -> str | None:
117
+ """Return the GraphNav waypoint id for a named location, or None."""
118
+ return self.location_to_waypoint.get(name)
119
+
120
+
121
+ def load_spot_config(path: str) -> SpotConfig:
122
+ """Parse a ``spot_adapter.yaml`` file into a :class:`SpotConfig`."""
123
+ with open(path, encoding="utf-8") as fh:
124
+ data = yaml.safe_load(fh) or {}
125
+ if not isinstance(data, dict):
126
+ raise ValueError(f"spot-config file {path} did not contain a YAML mapping at the top level.")
127
+ return SpotConfig.model_validate(data)
128
+
129
+
130
+ def _require_bosdyn() -> Any:
131
+ """Lazy-import the bosdyn client SDK with a clear error when missing."""
132
+ try:
133
+ import bosdyn.client # type: ignore[import-not-found,unused-ignore]
134
+ except ImportError as exc:
135
+ raise RuntimeError(
136
+ "bosdyn is not installed. SpotAdapter requires the [spot] extra.\n"
137
+ " Install with: pip install urml-legged-runtime[spot]"
138
+ ) from exc
139
+ return bosdyn.client
140
+
141
+
142
+ class SpotAdapter:
143
+ """Boston Dynamics Spot adapter implementing the URML ROSAdapter Protocol."""
144
+
145
+ BRAND = "spot"
146
+
147
+ def __init__(self, config: SpotConfig | None = None) -> None:
148
+ self._bosdyn = _require_bosdyn()
149
+ self._config = config or SpotConfig()
150
+ self._robot: Any = None
151
+ self._reports: list[dict[str, Any]] = []
152
+ self._closed = False
153
+
154
+ # ------------------------------------------------------------------
155
+ # Lifecycle
156
+ # ------------------------------------------------------------------
157
+
158
+ def _connect(self) -> Any:
159
+ """Open + authenticate the Spot robot lazily; cache for reuse."""
160
+ if self._robot is not None:
161
+ return self._robot
162
+ sdk = self._bosdyn.create_standard_sdk("urml-spot-adapter")
163
+ robot = sdk.create_robot(self._config.hostname)
164
+ username = os.environ.get(self._config.username_env, "")
165
+ password = os.environ.get(self._config.password_env, "")
166
+ robot.authenticate(username, password)
167
+ robot.time_sync.wait_for_sync()
168
+ self._robot = robot
169
+ return robot
170
+
171
+ def close(self) -> None:
172
+ """Release the robot. Safe to call multiple times."""
173
+ if self._closed:
174
+ return
175
+ if self._robot is not None:
176
+ with suppress(Exception):
177
+ self._robot.power_off(cut_immediately=False)
178
+ self._closed = True
179
+
180
+ def __enter__(self) -> SpotAdapter:
181
+ return self
182
+
183
+ def __exit__(self, *_: object) -> None:
184
+ self.close()
185
+
186
+ def _reason(self, capability: str) -> str:
187
+ return _NOT_SUPPORTED.format(capability=capability)
188
+
189
+ # ------------------------------------------------------------------
190
+ # Supported
191
+ # ------------------------------------------------------------------
192
+
193
+ def send_navigation_goal(
194
+ self,
195
+ *,
196
+ location: str | None = None,
197
+ pose: dict[str, float] | None = None,
198
+ frame: str | None = None,
199
+ carrying: dict[str, Any] | None = None,
200
+ speed: float | None = None,
201
+ ) -> NavigationResult:
202
+ if location is None and pose is None:
203
+ return NavigationResult(success=False, reason="send_navigation_goal called without location or pose")
204
+ if location is not None:
205
+ waypoint = self._config.resolve_location(location)
206
+ if waypoint is None:
207
+ return NavigationResult(
208
+ success=False,
209
+ reason=f"location_not_configured: {location!r} is declared in the "
210
+ "manifest but not mapped to a GraphNav waypoint in spot_adapter.yaml.",
211
+ )
212
+ robot = self._connect()
213
+ ok, reason = self._drive(robot, location=location, pose=pose)
214
+ return NavigationResult(success=ok, reason=reason, final_pose=pose if ok else None, frame=frame)
215
+
216
+ def _drive(self, robot: Any, *, location: str | None, pose: dict[str, float] | None) -> tuple[bool, str | None]:
217
+ """Issue the GraphNav / trajectory command. Returns (success, reason)."""
218
+ graphnav = robot.ensure_client("graph-nav")
219
+ if location is not None:
220
+ graphnav.navigate_to(self._config.resolve_location(location))
221
+ else:
222
+ graphnav.navigate_to_anchor(pose or {})
223
+ return True, None
224
+
225
+ def send_docking_goal(
226
+ self,
227
+ *,
228
+ station: str,
229
+ service: str,
230
+ until: str | None = None,
231
+ ) -> NavigationResult:
232
+ robot = self._connect()
233
+ docking = robot.ensure_client("docking")
234
+ with suppress(Exception):
235
+ docking.dock(station)
236
+ return NavigationResult(success=True)
237
+ return NavigationResult(success=False, reason=f"dock_failed: station={station!r}")
238
+
239
+ def wait_passively(self, *, duration_seconds: float) -> SubstrateResult:
240
+ robot = self._connect()
241
+ cmd = robot.ensure_client("robot-command")
242
+ with suppress(Exception):
243
+ cmd.stand(duration_seconds=duration_seconds)
244
+ return SubstrateResult(success=True)
245
+
246
+ def take_measurement(
247
+ self,
248
+ *,
249
+ what: str,
250
+ target: str | None,
251
+ sensor: str | None,
252
+ ) -> MeasurementResult:
253
+ robot = self._connect()
254
+ state_client = robot.ensure_client("robot-state")
255
+ state = state_client.get_robot_state()
256
+ battery = getattr(state, "battery_percentage", None)
257
+ return MeasurementResult(
258
+ success=True,
259
+ payload={"value": battery, "unit": "percent", "what": what},
260
+ )
261
+
262
+ def wait_for_condition(
263
+ self,
264
+ *,
265
+ kind: Literal["event", "signal", "input", "sensor_threshold"],
266
+ name: str | None,
267
+ input_mode: str | None,
268
+ threshold: dict[str, Any] | None,
269
+ timeout_seconds: float | None,
270
+ ) -> WaitResult:
271
+ robot = self._connect()
272
+ state_client = robot.ensure_client("robot-state")
273
+ state = state_client.get_robot_state()
274
+ return WaitResult(success=True, timed_out=False, payload={"observed": str(state)[:64]})
275
+
276
+ def emit_report(
277
+ self,
278
+ *,
279
+ to: str,
280
+ facts: dict[str, Any],
281
+ attachments: list[str] | None,
282
+ status: Literal["success", "partial", "failure"],
283
+ severity: Literal["info", "notice", "warning", "error"],
284
+ ) -> SubstrateResult:
285
+ # Structured record to a local sink. No cloud (manifesto).
286
+ self._reports.append({"to": to, "status": status, "severity": severity, "facts": facts})
287
+ return SubstrateResult(success=True)
288
+
289
+ def run_scan(
290
+ self,
291
+ *,
292
+ area: dict[str, Any],
293
+ pattern: Literal["serpentine", "spiral", "grid", "adaptive"],
294
+ overlap: float,
295
+ altitude: float | None,
296
+ media: Literal["photo", "video", "sensor_only"],
297
+ sensor: str | None,
298
+ ) -> ScanResult:
299
+ # A scan is waypoints plus a capture at each one, and this adapter
300
+ # does neither. Reporting success would claim an area was covered
301
+ # when nothing moved.
302
+ return ScanResult(success=False, reason=self._reason("area-scan controller"))
303
+
304
+ # ------------------------------------------------------------------
305
+ # Spot Arm (opt-in via SpotConfig.arm_attached)
306
+ # ------------------------------------------------------------------
307
+
308
+ def send_manipulation_goal(
309
+ self,
310
+ *,
311
+ action: Literal["grasp", "release"],
312
+ target: dict[str, Any] | None = None,
313
+ force_n: float | None = None,
314
+ approach: Literal["top", "side", "front", "auto"] = "auto",
315
+ release_mode: Literal["drop", "place", "hand_to_user"] | None = None,
316
+ release_at: dict[str, Any] | str | None = None,
317
+ arm: str | None = None,
318
+ grasp_type: str | None = None,
319
+ target_motion: str | None = None,
320
+ ) -> ManipulationResult:
321
+ """Grasp or release with the Spot Arm.
322
+
323
+ Grasp lowers to a manipulation-api ``PickObject`` at the resolved
324
+ target pose (URML validated the target against the manifest before
325
+ this call; the arm plans its own approach). Release opens the claw
326
+ via robot-command and stows the arm. ``grasp_type`` is accepted for
327
+ Protocol parity and ignored: the Spot gripper is a single-DoF claw.
328
+ A bare Spot (``arm_attached: false``) keeps the sentinel.
329
+ """
330
+ if not self._config.arm_attached:
331
+ return ManipulationResult(success=False, reason=self._reason("arm (arm_attached is false)"))
332
+ try:
333
+ if action == "grasp":
334
+ return self._arm_grasp(target)
335
+ return self._arm_release()
336
+ except Exception as exc: # bosdyn raises RpcError subclasses; keep the reason honest.
337
+ return ManipulationResult(success=False, reason=f"spot_arm_error: {exc}")
338
+
339
+ def _arm_grasp(self, target: dict[str, Any] | None) -> ManipulationResult:
340
+ pose = (target or {}).get("pose")
341
+ if not isinstance(pose, dict):
342
+ return ManipulationResult(success=False, reason="spot_arm_error: grasp target has no resolved pose")
343
+ from bosdyn.api import geometry_pb2, manipulation_api_pb2 # type: ignore[import-not-found,unused-ignore]
344
+
345
+ request = manipulation_api_pb2.ManipulationApiRequest(
346
+ pick_object=manipulation_api_pb2.PickObject(
347
+ frame_name=self._config.grasp_frame,
348
+ object_rt_frame=geometry_pb2.Vec3(
349
+ x=float(pose.get("x", 0.0)), y=float(pose.get("y", 0.0)), z=float(pose.get("z", 0.0))
350
+ ),
351
+ )
352
+ )
353
+ client = self._connect().ensure_client("manipulation-api")
354
+ response = client.manipulation_api_command(manipulation_api_request=request)
355
+ feedback_request = manipulation_api_pb2.ManipulationApiFeedbackRequest(
356
+ manipulation_cmd_id=response.manipulation_cmd_id
357
+ )
358
+ deadline = time.monotonic() + self._config.command_timeout_seconds
359
+ while True:
360
+ feedback = client.manipulation_api_feedback_command(manipulation_api_feedback_request=feedback_request)
361
+ state = manipulation_api_pb2.ManipulationFeedbackState.Name(feedback.current_state)
362
+ if state == "MANIP_STATE_DONE":
363
+ return ManipulationResult(success=True)
364
+ if state.startswith("MANIP_STATE_GRASP_FAILED") or state == "MANIP_STATE_GRASP_PLANNING_NO_SOLUTION":
365
+ return ManipulationResult(success=False, reason=f"spot_arm_grasp_failed: {state}")
366
+ if time.monotonic() > deadline:
367
+ return ManipulationResult(success=False, reason="spot_arm_error: grasp feedback timed out")
368
+ time.sleep(0.1)
369
+
370
+ def _arm_release(self) -> ManipulationResult:
371
+ from bosdyn.client.robot_command import RobotCommandBuilder # type: ignore[import-not-found,unused-ignore]
372
+
373
+ command = self._connect().ensure_client("robot-command")
374
+ command.robot_command(RobotCommandBuilder.claw_gripper_open_fraction_command(1.0))
375
+ command.robot_command(RobotCommandBuilder.arm_stow_command())
376
+ return ManipulationResult(success=True)
377
+
378
+ # ------------------------------------------------------------------
379
+ # Not supported on a bare Spot
380
+ # ------------------------------------------------------------------
381
+
382
+ def query_detection(
383
+ self,
384
+ *,
385
+ object_class: str,
386
+ attributes: dict[str, Any] | None = None,
387
+ where_near: str | None = None,
388
+ where_within: float | None = None,
389
+ ) -> DetectionResult:
390
+ return DetectionResult(success=False, reason=self._reason("general onboard perception"))
391
+
392
+ def capture_media(
393
+ self,
394
+ *,
395
+ media: Literal["photo", "video"],
396
+ target: str | None,
397
+ duration_seconds: float | None,
398
+ attributes: dict[str, Any] | None,
399
+ camera: str | None = None,
400
+ ) -> CaptureResult:
401
+ return CaptureResult(success=False, reason=self._reason("wired camera capture"))
402
+
403
+ def emit_speech(
404
+ self,
405
+ *,
406
+ utterance: str,
407
+ locale: str | None,
408
+ style: Literal["notice", "warning", "conversational"],
409
+ interrupt: bool,
410
+ ) -> SubstrateResult:
411
+ return SubstrateResult(success=False, reason=self._reason("speaker"))
412
+
413
+ def acquire_speech(
414
+ self,
415
+ *,
416
+ prompt: str | None,
417
+ locale: str | None,
418
+ timeout_seconds: float | None,
419
+ expected: Literal["free_form", "confirmation", "choice"],
420
+ choices: list[str] | None,
421
+ ) -> ListenResult:
422
+ return ListenResult(success=False, reason=self._reason("microphone"))
423
+
424
+ def send_takeoff_goal(self, *, altitude: float, climb_rate: float | None = None) -> NavigationResult:
425
+ return NavigationResult(success=False, reason=self._reason("flight capability"))
426
+
427
+ def send_land_goal(
428
+ self,
429
+ *,
430
+ at: str | None = None,
431
+ precision: Literal["standard", "precise"] = "standard",
432
+ ) -> NavigationResult:
433
+ return NavigationResult(success=False, reason=self._reason("flight capability"))
434
+
435
+ def send_return_to_home_goal(
436
+ self,
437
+ *,
438
+ speed: float | None = None,
439
+ altitude: float | None = None,
440
+ ) -> NavigationResult:
441
+ return NavigationResult(success=False, reason=self._reason("flight capability"))
442
+
443
+ def call_named_program(
444
+ self,
445
+ *,
446
+ name: str,
447
+ args: dict[str, Any] | None = None,
448
+ ) -> ProgramCallResult:
449
+ """``call_program``: this substrate exposes no named programs (RFC-0015)."""
450
+ return unsupported_program_call('legged')
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.5
2
+ Name: urml-legged-runtime
3
+ Version: 0.5.2
4
+ Summary: Legged/quadruped reference runtime for URML — Boston Dynamics Spot, ANYbotics ANYmal.
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: anybotics,anymal,boston-dynamics,legged,quadruped,robotics,runtime,spot,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.2
23
+ Requires-Dist: urml-validator>=0.5.2
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
+ Provides-Extra: spot
30
+ Requires-Dist: bosdyn-api>=4.0; extra == 'spot'
31
+ Requires-Dist: bosdyn-client>=4.0; extra == 'spot'
32
+ Requires-Dist: bosdyn-mission>=4.0; extra == 'spot'
33
+ Description-Content-Type: text/markdown
34
+
35
+ <p align="center">
36
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
37
+ </p>
38
+
39
+ <p align="center">
40
+ A small, opinionated, human-readable language for describing robot intent.
41
+ </p>
42
+
43
+ <p align="center">
44
+ <a href="https://urml.dev"><b>urml.dev</b></a>
45
+ </p>
46
+
47
+ ---
48
+
49
+ # urml-legged-runtime
50
+
51
+ **Legged/quadruped reference runtime for URML** — first-class adapters for **Boston Dynamics Spot** and **ANYbotics ANYmal**.
52
+
53
+ Two vendors, two substrates, the same `ROSAdapter` Protocol:
54
+
55
+ - **`SpotAdapter`** talks the Boston Dynamics `bosdyn` gRPC SDK directly. **No ROS 2 dependency** — like `PX4Adapter` for MAVLink, it is a second proof that URML's spec carries no ROS assumptions. Spot's own companion computer is commonly a Jetson, so the offline, Jetson-class deployment story is native here.
56
+ - **`AnymalAdapter`** speaks ROS 2, so it composes the ROS 2 runtime's `RclpyAdapter` — the same single-sourced-substrate pattern the industrial-arm runtime uses. No duplicated ROS 2 plumbing.
57
+
58
+ ## Method coverage
59
+
60
+ **SpotAdapter** (bosdyn):
61
+
62
+ | URML primitive | Mapping |
63
+ |---|---|
64
+ | `move_to` / `hover` | GraphNav navigate-to (location → waypoint via `SpotConfig`) |
65
+ | `dock` | `bosdyn.client.docking` blocking dock |
66
+ | `wait` | held stand command |
67
+ | `measure` | robot-state telemetry (battery / e-stop) — *partial* |
68
+ | `wait_for` | robot-state poll — *partial* |
69
+ | `report` | structured record to a local sink (no cloud) |
70
+ | `scan` | documented not-supported result: no area-scan controller (a scan is waypoints plus a capture at each one) |
71
+
72
+ Not supported on a bare Spot — `grasp`/`release` (needs the Spot Arm SDK), `detect`, `capture`, `speak`, `listen`, and the drone trio — return `not_supported_on_spot: ...` (returned, not raised).
73
+
74
+ **AnymalAdapter** (composes `RclpyAdapter`): `move_to`/`hover`, `wait`, `measure`, `wait_for`, `report` delegate to the ROS 2 substrate. `grasp`/`release` (no arm), `dock`, `detect`, `scan`, `capture`, `speak`, `listen`, and the drone trio return `not_supported_on_quadruped[anymal]: ...`. A payload-equipped ANYmal pairs with a companion adapter, exactly as the drone stack pairs flight with a ROS 2 companion.
75
+
76
+ ## Install
77
+
78
+ ```bash
79
+ pip install -e reference/legged-runtime # AnymalAdapter (needs a sourced ROS 2 env to construct)
80
+ pip install -e reference/legged-runtime[spot] # + SpotAdapter (bosdyn wheels)
81
+ ```
82
+
83
+ `bosdyn` and `rclpy` are imported lazily, so the package imports on every host; constructing an adapter needs that vendor's runtime.
84
+
85
+ ## Use
86
+
87
+ ```python
88
+ from urml_legged_runtime import SpotAdapter, SpotConfig
89
+
90
+ cfg = SpotConfig(hostname="192.168.80.3", location_to_waypoint={"dock": "wp-12"})
91
+ with SpotAdapter(cfg) as spot: # credentials read from env-var NAMES in cfg
92
+ assert spot.send_navigation_goal(location="dock").success
93
+ ```
94
+
95
+ ```python
96
+ from urml_conformance import ConformanceRunner
97
+ from urml_legged_runtime import LEGGED_ADAPTERS
98
+
99
+ runner = ConformanceRunner(adapter_factory=lambda: LEGGED_ADAPTERS["spot"]())
100
+ ```
101
+
102
+ ## Status
103
+
104
+ **v0.1 (this release):**
105
+ - `SpotAdapter` (standalone bosdyn) + `AnymalAdapter` (composes `RclpyAdapter`) + `LEGGED_ADAPTERS` registry.
106
+ - Hermetic unit tests: Spot against an injected fake `bosdyn` (navigation, dock, wait, measure, scan (not supported), every not-supported sentinel, lifecycle power-off, the missing-`[spot]`-extra error); ANYmal against an injected fake inner (delegation + not-supported + conformance hook + `runtime_checkable`).
107
+ - Gated `.github/workflows/legged-integration.yml`: `spot-smoke` (real bosdyn wheels), `spot-arm64-build` (the bosdyn stack under `linux/arm64` QEMU — the Jetson-companion signal, mirroring `px4-arm64-build`), and a gated `legged-sim-e2e` matrix that skips cleanly without a sim/credential.
108
+
109
+ **Follow-ups (not yet):**
110
+ - US-compliant capability manifests (Boston Dynamics — US/Hyundai-owned; ANYbotics — Switzerland). Blocked on the `Mobility.drive_type` schema, which has no `legged`/`quadruped` value; that is the Phase-5 RFC fast-follow. Quadruped conformance fixtures land with the RFC, not before (correct sequencing, not a shortcut).
111
+ - Spot Arm SDK wiring for `grasp`/`release`; a vision/speech companion split.
112
+ - A real Spot sim path: Boston Dynamics' public sim is weaker than PX4 SITL and Isaac-Sim Spot needs an RTX host (never the Jetson). Until that or hardware exists, the Spot integration lane is honestly the hermetic fake-bosdyn path; the gated sim job skips cleanly.
113
+
114
+ ## Core Commitment
115
+
116
+ This runtime is licensed under the 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.
117
+
118
+ ## Related documents
119
+
120
+ - [`/spec/layer-1-hal/`](../../spec/layer-1-hal/) — manifest schema (the `drive_type` gap is tracked by the Phase-5 RFC).
121
+ - [`/reference/ros2-runtime/`](../ros2-runtime/) — the substrate engine `AnymalAdapter` composes.
122
+ - [`/reference/px4-runtime/`](../px4-runtime/) — the no-ROS sibling whose structure `SpotAdapter` mirrors.
123
+ - [`/conformance/`](../../conformance/) — the test suite that decides conformance.
@@ -0,0 +1,8 @@
1
+ urml_legged_runtime/__init__.py,sha256=FeQYtjC4D6d4EtOW4945ZYU5Ooqow86zGP-gIIZB5Jw,1445
2
+ urml_legged_runtime/_version.py,sha256=wirsV7Pr4mdRTPYyy-xTH2cUbgmNbAtlfBk_dmsOTGU,66
3
+ urml_legged_runtime/anymal.py,sha256=Silcey47vXVVyuhTimOx4tXnrkTvVixy_8JxGGBTNBI,8657
4
+ urml_legged_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ urml_legged_runtime/spot.py,sha256=ZRTqeKnWZ2Nty60PivUjN7jA8QPqKvbKSa9GilcewFU,17903
6
+ urml_legged_runtime-0.5.2.dist-info/METADATA,sha256=OFPeDrmaU5ftYVLeultIhCCUVFUpoOdcytbGVxWyi5U,6602
7
+ urml_legged_runtime-0.5.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ urml_legged_runtime-0.5.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any