urml-embedded-runtime 0.5.0__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,27 @@
1
+ """urml_embedded_runtime — educational-MCU reference runtime for URML.
2
+
3
+ EmbeddedAdapter (+ EmbeddedConfig, load_embedded_config)
4
+ micro:bit / Arduino-class platforms over a plain serial line.
5
+ **No ROS 2 dependency** — URML scales DOWN to a microcontroller,
6
+ serving the educational flywheel (RFC-0011). pyserial is imported
7
+ lazily (the [serial] extra), so this module loads on every host.
8
+ Built against the frozen substrate Protocol per RFC-0014; the
9
+ minimal-MCU manifest gap is recorded in SPEC-GAPS.md (RFC-0018),
10
+ not silently patched.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from urml_embedded_runtime._version import __version__
16
+ from urml_embedded_runtime.adapter import (
17
+ EmbeddedAdapter,
18
+ EmbeddedConfig,
19
+ load_embedded_config,
20
+ )
21
+
22
+ __all__ = [
23
+ "EmbeddedAdapter",
24
+ "EmbeddedConfig",
25
+ "__version__",
26
+ "load_embedded_config",
27
+ ]
@@ -0,0 +1,3 @@
1
+ """Package version. Bumped per release."""
2
+
3
+ __version__ = "0.5.0"
@@ -0,0 +1,298 @@
1
+ """EmbeddedAdapter — micro:bit / Arduino-class MCU over serial.
2
+
3
+ URML scales DOWN to a microcontroller: a buggy whose firmware reads
4
+ short ASCII commands off a serial line. **No ROS 2 dependency** — the
5
+ educational-flywheel analog of the PX4/marine no-ROS proof, serving
6
+ RFC-0011 educational. Mirrors :class:`BlueRovAdapter`: lazy
7
+ ``pyserial``, cached lazily-opened port, failures returned not raised.
8
+
9
+ ## v0.1 method coverage
10
+
11
+ Supported: ``move_to``/``hover`` (write the configured command),
12
+ ``grasp``/``release`` (write the configured gripper-servo command),
13
+ ``wait``, ``measure`` (query + read one line), ``wait_for``
14
+ (read-once), ``report`` (local sink, no cloud), ``scan`` (documented
15
+ stub).
16
+
17
+ Not supported on a tiny MCU (returned, not raised): ``dock``,
18
+ ``detect``, ``capture``, ``speak``, ``listen``. The drone trio is
19
+ ``not_applicable_mcu``.
20
+
21
+ The minimal-MCU manifest gap (a non-mobile sensor/LED node cannot
22
+ honestly fill the manifest's mobility/perception blocks; raw LED/GPIO
23
+ actuation has no verb) is recorded in ``SPEC-GAPS.md`` → RFC-0018
24
+ (manifest subset) cross-referencing RFC-0017 (the actuation verb), not
25
+ silently invented here.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from contextlib import suppress
31
+ from typing import Any, Literal
32
+
33
+ from urml_ros2_runtime.substrate.base import (
34
+ ProgramCallResult,
35
+ unsupported_program_call,
36
+ CaptureResult,
37
+ DetectionResult,
38
+ ListenResult,
39
+ ManipulationResult,
40
+ MeasurementResult,
41
+ NavigationResult,
42
+ ScanResult,
43
+ SubstrateResult,
44
+ WaitResult,
45
+ )
46
+
47
+ from urml_embedded_runtime._version import __version__
48
+ from urml_embedded_runtime.config import EmbeddedConfig, load_embedded_config
49
+
50
+ __all__ = [
51
+ "EmbeddedAdapter",
52
+ "EmbeddedConfig",
53
+ "__version__",
54
+ "load_embedded_config",
55
+ ]
56
+
57
+ _NOT_SUPPORTED = (
58
+ "not_supported_on_mcu: a micro:bit/Arduino-class board has no {capability}. "
59
+ "The URML program, manifest, and validator are unchanged; pair a richer "
60
+ "board or a companion."
61
+ )
62
+ _NOT_APPLICABLE = "not_applicable_mcu: {capability} has no meaning for a tabletop educational buggy."
63
+
64
+
65
+ def _require_pyserial() -> Any:
66
+ """Lazy-import pyserial with a clear error when missing."""
67
+ try:
68
+ import serial # type: ignore[import-not-found,unused-ignore]
69
+ except ImportError as exc:
70
+ raise RuntimeError(
71
+ "pyserial is not installed. EmbeddedAdapter requires the [serial] extra.\n"
72
+ " Install with: pip install urml-embedded-runtime[serial]"
73
+ ) from exc
74
+ return serial
75
+
76
+
77
+ class EmbeddedAdapter:
78
+ """Educational-MCU adapter implementing the URML ROSAdapter Protocol."""
79
+
80
+ BRAND = "embedded"
81
+
82
+ def __init__(self, config: EmbeddedConfig | None = None) -> None:
83
+ self._serial = _require_pyserial()
84
+ self._config = config or EmbeddedConfig()
85
+ self._port: Any = None
86
+ self._reports: list[dict[str, Any]] = []
87
+ self._closed = False
88
+
89
+ def _open(self) -> Any:
90
+ if self._port is not None:
91
+ return self._port
92
+ self._port = self._serial.serial_for_url(
93
+ self._config.port,
94
+ baudrate=self._config.baudrate,
95
+ timeout=self._config.read_timeout_seconds,
96
+ )
97
+ return self._port
98
+
99
+ def _send(self, command: str) -> None:
100
+ port = self._open()
101
+ port.write((command + "\n").encode("ascii"))
102
+
103
+ def close(self) -> None:
104
+ if self._closed:
105
+ return
106
+ if self._port is not None:
107
+ with suppress(Exception):
108
+ self._port.close()
109
+ self._closed = True
110
+
111
+ def __enter__(self) -> EmbeddedAdapter:
112
+ return self
113
+
114
+ def __exit__(self, *_: object) -> None:
115
+ self.close()
116
+
117
+ # ------------------------------------------------------------------
118
+ # Supported
119
+ # ------------------------------------------------------------------
120
+
121
+ def send_navigation_goal(
122
+ self,
123
+ *,
124
+ location: str | None = None,
125
+ pose: dict[str, float] | None = None,
126
+ frame: str | None = None,
127
+ carrying: dict[str, Any] | None = None,
128
+ speed: float | None = None,
129
+ ) -> NavigationResult:
130
+ if location is None:
131
+ return NavigationResult(
132
+ success=False,
133
+ reason="mcu_requires_named_location: a buggy drives to firmware-named "
134
+ "commands; raw pose goals are not meaningful on an MCU.",
135
+ )
136
+ cmd = self._config.resolve_location(location)
137
+ if cmd is None:
138
+ return NavigationResult(
139
+ success=False,
140
+ reason=f"location_not_configured: {location!r} is declared in the "
141
+ "manifest but not mapped to a command in embedded_adapter.yaml.",
142
+ )
143
+ self._send(cmd)
144
+ return NavigationResult(success=True, final_pose=None, frame=frame or "buggy")
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
+ cmd = self._config.manipulation_commands.get(action)
160
+ if cmd is None:
161
+ return ManipulationResult(
162
+ success=False,
163
+ reason=f"manipulation_command_not_configured: {action!r} is not mapped "
164
+ "to a command in embedded_adapter.yaml.",
165
+ )
166
+ self._send(cmd)
167
+ return ManipulationResult(success=True, grip_force_n=force_n)
168
+
169
+ def wait_passively(self, *, duration_seconds: float) -> SubstrateResult:
170
+ self._open()
171
+ return SubstrateResult(success=True)
172
+
173
+ def take_measurement(self, *, what: str, target: str | None, sensor: str | None) -> MeasurementResult:
174
+ port = self._open()
175
+ port.write(b"MEASURE\n")
176
+ line = port.readline()
177
+ try:
178
+ value: float | None = float(line.decode("ascii", "ignore").strip())
179
+ except (ValueError, AttributeError):
180
+ value = None
181
+ return MeasurementResult(success=True, payload={"value": value, "what": what})
182
+
183
+ def wait_for_condition(
184
+ self,
185
+ *,
186
+ kind: Literal["event", "signal", "input", "sensor_threshold"],
187
+ name: str | None,
188
+ input_mode: str | None,
189
+ threshold: dict[str, Any] | None,
190
+ timeout_seconds: float | None,
191
+ ) -> WaitResult:
192
+ port = self._open()
193
+ line = port.readline()
194
+ return WaitResult(success=True, timed_out=not line, payload=None)
195
+
196
+ def emit_report(
197
+ self,
198
+ *,
199
+ to: str,
200
+ facts: dict[str, Any],
201
+ attachments: list[str] | None,
202
+ status: Literal["success", "partial", "failure"],
203
+ severity: Literal["info", "notice", "warning", "error"],
204
+ ) -> SubstrateResult:
205
+ self._reports.append({"to": to, "status": status, "severity": severity, "facts": facts})
206
+ return SubstrateResult(success=True)
207
+
208
+ def run_scan(
209
+ self,
210
+ *,
211
+ area: dict[str, Any],
212
+ pattern: Literal["serpentine", "spiral", "grid", "adaptive"],
213
+ overlap: float,
214
+ altitude: float | None,
215
+ media: Literal["photo", "video", "sensor_only"],
216
+ sensor: str | None,
217
+ ) -> ScanResult:
218
+ # A scan is waypoints plus a capture at each one, and this adapter
219
+ # does neither. Reporting success would claim an area was covered
220
+ # when nothing moved.
221
+ return ScanResult(success=False, reason=_NOT_SUPPORTED.format(capability="area-scan controller"))
222
+
223
+ # ------------------------------------------------------------------
224
+ # Not supported on a tiny MCU
225
+ # ------------------------------------------------------------------
226
+
227
+ def send_docking_goal(self, *, station: str, service: str, until: str | None = None) -> NavigationResult:
228
+ return NavigationResult(success=False, reason=_NOT_SUPPORTED.format(capability="docking station"))
229
+
230
+ def query_detection(
231
+ self,
232
+ *,
233
+ object_class: str,
234
+ attributes: dict[str, Any] | None = None,
235
+ where_near: str | None = None,
236
+ where_within: float | None = None,
237
+ ) -> DetectionResult:
238
+ return DetectionResult(success=False, reason=_NOT_SUPPORTED.format(capability="onboard detection"))
239
+
240
+ def capture_media(
241
+ self,
242
+ *,
243
+ media: Literal["photo", "video"],
244
+ target: str | None,
245
+ duration_seconds: float | None,
246
+ attributes: dict[str, Any] | None,
247
+ camera: str | None = None,
248
+ ) -> CaptureResult:
249
+ return CaptureResult(success=False, reason=_NOT_SUPPORTED.format(capability="recordable camera"))
250
+
251
+ def emit_speech(
252
+ self,
253
+ *,
254
+ utterance: str,
255
+ locale: str | None,
256
+ style: Literal["notice", "warning", "conversational"],
257
+ interrupt: bool,
258
+ ) -> SubstrateResult:
259
+ return SubstrateResult(success=False, reason=_NOT_SUPPORTED.format(capability="speaker"))
260
+
261
+ def acquire_speech(
262
+ self,
263
+ *,
264
+ prompt: str | None,
265
+ locale: str | None,
266
+ timeout_seconds: float | None,
267
+ expected: Literal["free_form", "confirmation", "choice"],
268
+ choices: list[str] | None,
269
+ ) -> ListenResult:
270
+ return ListenResult(success=False, reason=_NOT_SUPPORTED.format(capability="microphone"))
271
+
272
+ def send_takeoff_goal(self, *, altitude: float, climb_rate: float | None = None) -> NavigationResult:
273
+ return NavigationResult(success=False, reason=_NOT_APPLICABLE.format(capability="take_off"))
274
+
275
+ def send_land_goal(
276
+ self,
277
+ *,
278
+ at: str | None = None,
279
+ precision: Literal["standard", "precise"] = "standard",
280
+ ) -> NavigationResult:
281
+ return NavigationResult(success=False, reason=_NOT_APPLICABLE.format(capability="land"))
282
+
283
+ def send_return_to_home_goal(
284
+ self,
285
+ *,
286
+ speed: float | None = None,
287
+ altitude: float | None = None,
288
+ ) -> NavigationResult:
289
+ return NavigationResult(success=False, reason=_NOT_APPLICABLE.format(capability="return_to_home"))
290
+
291
+ def call_named_program(
292
+ self,
293
+ *,
294
+ name: str,
295
+ args: dict[str, Any] | None = None,
296
+ ) -> ProgramCallResult:
297
+ """``call_program``: this substrate exposes no named programs (RFC-0015)."""
298
+ return unsupported_program_call('embedded')
@@ -0,0 +1,47 @@
1
+ """Deployment-side configuration for ``EmbeddedAdapter``.
2
+
3
+ A micro:bit / Arduino-class buggy is driven by writing short ASCII
4
+ commands over a serial line (the firmware on the board interprets
5
+ them). Which command string a manifest-declared location maps to is
6
+ board- and sketch-specific, so it does NOT belong in the URML
7
+ program/manifest/envelope — it lives in an ``embedded_adapter.yaml``
8
+ (the same principle as the PX4 runtime's ``location_to_pose``).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+
15
+ import yaml
16
+ from pydantic import BaseModel, ConfigDict, Field
17
+
18
+
19
+ class EmbeddedConfig(BaseModel):
20
+ """Serial connection + command-mapping config."""
21
+
22
+ model_config = ConfigDict(extra="forbid")
23
+
24
+ port: str = Field(
25
+ default="loop://",
26
+ description="pyserial port. A real micro:bit: 'COM3' / '/dev/ttyACM0'. 'loop://' is the test loopback.",
27
+ )
28
+ baudrate: int = Field(default=115200, gt=0)
29
+ read_timeout_seconds: float = 2.0
30
+
31
+ #: location name -> the ASCII command the firmware drives on.
32
+ location_to_command: dict[str, str] = Field(default_factory=dict)
33
+ #: 'grasp' / 'release' -> the ASCII command for the gripper servo.
34
+ manipulation_commands: dict[str, str] = Field(default_factory=dict)
35
+
36
+ def resolve_location(self, name: str) -> str | None:
37
+ return self.location_to_command.get(name)
38
+
39
+
40
+ def load_embedded_config(path: str | Path) -> EmbeddedConfig:
41
+ """Parse an ``embedded_adapter.yaml`` file into an ``EmbeddedConfig``."""
42
+ p = Path(path)
43
+ with p.open(encoding="utf-8") as fh:
44
+ data = yaml.safe_load(fh) or {}
45
+ if not isinstance(data, dict):
46
+ raise ValueError(f"embedded-config file {p} did not contain a YAML mapping at the top level.")
47
+ return EmbeddedConfig.model_validate(data)
File without changes
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.5
2
+ Name: urml-embedded-runtime
3
+ Version: 0.5.0
4
+ Summary: Educational-MCU reference runtime for URML — micro:bit / Arduino-class over serial, zero ROS.
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: arduino,education,firmata,microbit,robotics,runtime,serial,urml
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: License :: Other/Proprietary License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Education
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: pydantic<3,>=2.6
22
+ Requires-Dist: pyyaml<7,>=6.0
23
+ Requires-Dist: urml-ros2-runtime>=0.5.0
24
+ Requires-Dist: urml-validator>=0.5.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == 'dev'
27
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
28
+ Requires-Dist: pytest>=8; extra == 'dev'
29
+ Requires-Dist: ruff>=0.5; extra == 'dev'
30
+ Provides-Extra: firmata
31
+ Requires-Dist: pyfirmata2>=2.4; extra == 'firmata'
32
+ Provides-Extra: serial
33
+ Requires-Dist: pyserial<4,>=3.5; extra == 'serial'
34
+ Description-Content-Type: text/markdown
35
+
36
+ <p align="center">
37
+ <a href="https://urml.dev"><img src="https://urml.dev/favicon.svg" alt="URML" width="72" height="72"></a>
38
+ </p>
39
+
40
+ <p align="center">
41
+ A small, opinionated, human-readable language for describing robot intent.
42
+ </p>
43
+
44
+ <p align="center">
45
+ <a href="https://urml.dev"><b>urml.dev</b></a>
46
+ </p>
47
+
48
+ ---
49
+
50
+ # urml-embedded-runtime
51
+
52
+ **Educational-MCU reference runtime for URML** — `EmbeddedAdapter` for **micro:bit / Arduino-class** buggies over a plain serial line, **zero ROS**.
53
+
54
+ URML scales *down* to a microcontroller: a buggy whose firmware reads short ASCII commands off serial. The educational-flywheel analog of the PX4/marine no-ROS proof (RFC-0011 educational profile), mirroring `BlueRovAdapter`: lazy `pyserial`, cached lazy port, failures returned not raised. Built against the frozen Protocol per [RFC-0014](../../docs/rfcs/0014-substrate-conformance.md).
55
+
56
+ ## Method coverage
57
+
58
+ | URML primitive | v0.1 |
59
+ |---|---|
60
+ | `move_to` / `hover` | write the configured firmware command |
61
+ | `grasp` / `release` | write the configured gripper-servo command |
62
+ | `wait` | hold (success) |
63
+ | `measure` / `wait_for` | query + read one serial line |
64
+ | `report` | structured record to a local sink (no cloud) |
65
+ | `scan` | documented not-supported result: no area-scan controller (a scan is waypoints plus a capture at each one) |
66
+
67
+ `dock`, `detect`, `capture`, `speak`, `listen` return `not_supported_on_mcu`. The drone trio returns `not_applicable_mcu`.
68
+
69
+ ## Spec gaps (RFC-0014 protocol)
70
+
71
+ A *mobile* buggy fits the v0.1 schema honestly (it really is `differential`). A non-mobile LED/sensor MCU node does not — filed as **RFC-0018 (Draft)**: a minimal-MCU manifest subset, explicitly cross-referencing **RFC-0017** for the raw-actuation verb (not duplicated). See [`SPEC-GAPS.md`](SPEC-GAPS.md). `educational` validates with no schema change (`program.profile` is an open `Identifier`).
72
+
73
+ ## Install / use
74
+
75
+ ```bash
76
+ pip install -e reference/embedded-runtime[serial] # installs pyserial
77
+ ```
78
+
79
+ ```python
80
+ from urml_embedded_runtime import EmbeddedAdapter, EmbeddedConfig
81
+ cfg = EmbeddedConfig(port="/dev/ttyACM0",
82
+ location_to_command={"waypoint_a": "GO A", "dock": "HOME"})
83
+ with EmbeddedAdapter(cfg) as buggy:
84
+ assert buggy.send_navigation_goal(location="waypoint_a").success
85
+ ```
86
+
87
+ ## Status
88
+
89
+ **v0.1 (this release):**
90
+ - `EmbeddedAdapter` + `EmbeddedConfig` (pyserial, no ROS). `microbit_edu` manifest + `conformance/fixtures/educational/01_buggy_patrol_positive.yaml` verified through the runner (hermetic against `MockROSAdapter`; adapter-agnostic against `EmbeddedAdapter`). First fixture under the new `educational` profile dir.
91
+ - Hermetic unit tests: nav (configured + unmapped), grasp, measure, scan (not supported), lifecycle, the not-supported / not-applicable sentinels, the missing-`[serial]`-extra error, the conformance hook; no pyserial install required.
92
+ - Gated `.github/workflows/embedded-integration.yml`: `embedded-smoke` (real pyserial loopback), `embedded-arm64-build` (Jetson-class QEMU), `embedded-board-e2e` placeholder against a real micro:bit/Arduino (opt-in via the `run_placeholder` dispatch input; first run is a calibration run by design).
93
+
94
+ **Follow-ups (not yet):** RFC-0018 outcome (minimal-MCU subset); a `pyfirmata2` path for stock Firmata sketches.
95
+
96
+ ## Core Commitment
97
+
98
+ 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. `pyserial`/`pyfirmata2` are optional extras imported lazily, never at module load.
99
+
100
+ ## Related documents
101
+
102
+ - [`/reference/marine-runtime/`](../marine-runtime/) — the zero-ROS sibling whose structure this mirrors.
103
+ - [`/spec/profiles/educational/`](../../spec/profiles/educational/) — the RFC-0011 profile this serves.
104
+ - [`/docs/rfcs/0018-minimal-mcu-capability-subset.md`](../../docs/rfcs/0018-minimal-mcu-capability-subset.md) — the surfaced spec gap.
@@ -0,0 +1,8 @@
1
+ urml_embedded_runtime/__init__.py,sha256=9Z0CcfFoRul2c9VPFKja1pRy0ukVa4649F935DhlqS4,886
2
+ urml_embedded_runtime/_version.py,sha256=GhEpeFCtTCp-bVev1I9B_MSg50q8bPayhz1y1kQbgBU,66
3
+ urml_embedded_runtime/adapter.py,sha256=iDCOW31x9BdyFGKqeGcEF0G0fkT0GlL2VZl_hSZEncc,10645
4
+ urml_embedded_runtime/config.py,sha256=qwb-GFu7XE0fF69I5rM0Imn1GTeloGUsU59-HoFUxjI,1793
5
+ urml_embedded_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ urml_embedded_runtime-0.5.0.dist-info/METADATA,sha256=znU1zVVynniBM_t4zhpoewhRbqjSExYbX_DRxj6bZ6o,5380
7
+ urml_embedded_runtime-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ urml_embedded_runtime-0.5.0.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