urml-embedded-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,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,69 @@
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
+ <p align="center">
6
+ A small, opinionated, human-readable language for describing robot intent.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://urml.dev"><b>urml.dev</b></a>
11
+ </p>
12
+
13
+ ---
14
+
15
+ # urml-embedded-runtime
16
+
17
+ **Educational-MCU reference runtime for URML** — `EmbeddedAdapter` for **micro:bit / Arduino-class** buggies over a plain serial line, **zero ROS**.
18
+
19
+ 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).
20
+
21
+ ## Method coverage
22
+
23
+ | URML primitive | v0.1 |
24
+ |---|---|
25
+ | `move_to` / `hover` | write the configured firmware command |
26
+ | `grasp` / `release` | write the configured gripper-servo command |
27
+ | `wait` | hold (success) |
28
+ | `measure` / `wait_for` | query + read one serial line |
29
+ | `report` | structured record to a local sink (no cloud) |
30
+ | `scan` | documented not-supported result: no area-scan controller (a scan is waypoints plus a capture at each one) |
31
+
32
+ `dock`, `detect`, `capture`, `speak`, `listen` return `not_supported_on_mcu`. The drone trio returns `not_applicable_mcu`.
33
+
34
+ ## Spec gaps (RFC-0014 protocol)
35
+
36
+ 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`).
37
+
38
+ ## Install / use
39
+
40
+ ```bash
41
+ pip install -e reference/embedded-runtime[serial] # installs pyserial
42
+ ```
43
+
44
+ ```python
45
+ from urml_embedded_runtime import EmbeddedAdapter, EmbeddedConfig
46
+ cfg = EmbeddedConfig(port="/dev/ttyACM0",
47
+ location_to_command={"waypoint_a": "GO A", "dock": "HOME"})
48
+ with EmbeddedAdapter(cfg) as buggy:
49
+ assert buggy.send_navigation_goal(location="waypoint_a").success
50
+ ```
51
+
52
+ ## Status
53
+
54
+ **v0.1 (this release):**
55
+ - `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.
56
+ - 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.
57
+ - 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).
58
+
59
+ **Follow-ups (not yet):** RFC-0018 outcome (minimal-MCU subset); a `pyfirmata2` path for stock Firmata sketches.
60
+
61
+ ## Core Commitment
62
+
63
+ 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.
64
+
65
+ ## Related documents
66
+
67
+ - [`/reference/marine-runtime/`](../marine-runtime/) — the zero-ROS sibling whose structure this mirrors.
68
+ - [`/spec/profiles/educational/`](../../spec/profiles/educational/) — the RFC-0011 profile this serves.
69
+ - [`/docs/rfcs/0018-minimal-mcu-capability-subset.md`](../../docs/rfcs/0018-minimal-mcu-capability-subset.md) — the surfaced spec gap.
@@ -0,0 +1,54 @@
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
+ <p align="center">
6
+ A small, opinionated, human-readable language for describing robot intent.
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://urml.dev"><b>urml.dev</b></a>
11
+ </p>
12
+
13
+ ---
14
+
15
+ # SPEC-GAPS — urml-embedded-runtime
16
+
17
+ Per the spec-gap protocol (RFC-0014): built strictly against the
18
+ frozen substrate Protocol. Needs surfaced are recorded here; the
19
+ genuinely inexpressible become RFC Drafts for maintainer decision —
20
+ never a silent primitive/schema change.
21
+
22
+ ## Genuinely inexpressible → RFC Draft filed
23
+
24
+ - **RFC-0018 — minimal-MCU capability subset.** A *mobile* educational
25
+ buggy (the conformance fixture here) fits the v0.1 schema honestly:
26
+ it is genuinely `mobility.drive_type: differential`. But a large
27
+ class of educational MCU nodes — a fixed micro:bit with only an LED,
28
+ a buzzer, and a light sensor; a breadboard with a servo — has **no
29
+ honest `mobility`**, no camera/`perception` block, and no
30
+ manipulator. The manifest's blocks are individually optional, yet
31
+ there is no way to declare "this is a minimal actuator/sensor node"
32
+ such that the conformance suite can check it as a coherent class.
33
+ Pretending such a board has `differential` mobility to satisfy a
34
+ fixture would be a lie. Filed as RFC-0018 (Draft) — a *manifest*
35
+ minimal-subset declaration. It explicitly cross-references **RFC-0017**
36
+ (digital-I/O actuation): "blink the LED" is an actuation-verb gap
37
+ owned by RFC-0017, not duplicated here; RFC-0018 is only the
38
+ capability-declaration half.
39
+
40
+ ## Composable (no gap, documented)
41
+
42
+ - A 2-wheel micro:bit/Arduino buggy is honestly `differential`;
43
+ `move_to` over a named, firmware-mapped command (config-side
44
+ `location_to_command`, the px4 `location_to_pose` pattern). No URML
45
+ surface change — this is the shipped, green path.
46
+ - `grasp`/`release` → a configured gripper-servo command. Honest for a
47
+ buggy with a claw; absent ⇒ a clear unsuccessful result, not a gap.
48
+
49
+ ## Scope note
50
+
51
+ This serves the RFC-0011 educational profile. `program.profile` is an
52
+ open `Identifier`, so `educational` validates with **no** schema
53
+ change, and RFC-0011's profile is documented-not-enforced in v0.1 —
54
+ the fixture is honest as a core-primitive program under that profile.
@@ -0,0 +1,81 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "urml-embedded-runtime"
7
+ version = "0.5.0"
8
+ description = "Educational-MCU reference runtime for URML — micro:bit / Arduino-class over serial, zero ROS."
9
+ readme = "README.md"
10
+ license = { text = "BUSL-1.1" }
11
+ requires-python = ">=3.11"
12
+ authors = [{ name = "URML Maintainers" }]
13
+ keywords = ["robotics", "education", "microbit", "arduino", "serial", "firmata", "urml", "runtime"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Intended Audience :: Education",
18
+ "License :: Other/Proprietary License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Education",
24
+ ]
25
+ dependencies = [
26
+ "pydantic>=2.6,<3",
27
+ "PyYAML>=6.0,<7",
28
+ "urml-validator>=0.5.0",
29
+ "urml-ros2-runtime>=0.5.0",
30
+ ]
31
+
32
+ [project.optional-dependencies]
33
+ # The educational flywheel (RFC-0011): micro:bit / Arduino-class
34
+ # platforms a contributor can actually own. Driven over a plain serial
35
+ # line — pyserial is pure-Python + offline; pyfirmata2 is the optional
36
+ # Firmata path. Both imported lazily, so urml_embedded_runtime imports
37
+ # on every host without them. Zero ROS — URML scales DOWN to an MCU.
38
+ serial = [
39
+ "pyserial>=3.5,<4",
40
+ ]
41
+ firmata = [
42
+ "pyfirmata2>=2.4",
43
+ ]
44
+ dev = [
45
+ "pytest>=8",
46
+ "pytest-cov>=5",
47
+ "ruff>=0.5",
48
+ "mypy>=1.10",
49
+ ]
50
+
51
+ [project.urls]
52
+ Homepage = "https://github.com/urml-dev/URML"
53
+ Repository = "https://github.com/urml-dev/URML"
54
+ Issues = "https://github.com/urml-dev/URML/issues"
55
+
56
+ [tool.hatch.build.targets.wheel]
57
+ packages = ["src/urml_embedded_runtime"]
58
+
59
+ [tool.ruff]
60
+ line-length = 120
61
+ target-version = "py311"
62
+ src = ["src", "tests"]
63
+
64
+ [tool.ruff.lint]
65
+ select = ["E", "F", "W", "I", "B", "UP", "N", "ANN", "RUF"]
66
+ ignore = ["ANN401"]
67
+
68
+ [tool.ruff.lint.per-file-ignores]
69
+ "tests/*" = ["ANN"]
70
+
71
+ [tool.mypy]
72
+ strict = true
73
+ python_version = "3.11"
74
+ plugins = ["pydantic.mypy"]
75
+ mypy_path = "src"
76
+ packages = ["urml_embedded_runtime"]
77
+
78
+ [tool.pytest.ini_options]
79
+ minversion = "8.0"
80
+ testpaths = ["tests"]
81
+ addopts = ["-q", "--strict-markers"]
@@ -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,49 @@
1
+ """Live smoke for EmbeddedAdapter under a real ``pyserial`` install.
2
+
3
+ The educational-MCU analog of the PX4 runtime's
4
+ ``tests/integration/test_px4_adapter_live.py``. The *light* gate: it
5
+ needs only the real ``pyserial`` wheel. It opens the ``loop://``
6
+ loopback (no board) and confirms the ``ConformanceRunner.adapter_factory``
7
+ hook accepts the adapter. A real micro:bit/Arduino-driven run is the
8
+ documented calibration step in ``embedded-integration.yml``.
9
+
10
+ ## Gating
11
+
12
+ The default ``pytest`` invocation skips this module entirely. The
13
+ ``embedded-smoke`` job in ``.github/workflows/embedded-integration.yml``
14
+ sets ``URML_EMBEDDED_INTEGRATION=1`` and runs it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ import pytest
22
+
23
+ pytestmark = pytest.mark.skipif(
24
+ os.environ.get("URML_EMBEDDED_INTEGRATION") != "1",
25
+ reason="Set URML_EMBEDDED_INTEGRATION=1 to run the embedded live smoke (real pyserial, loopback).",
26
+ )
27
+
28
+
29
+ def test_real_pyserial_is_importable() -> None:
30
+ """The real pyserial module is available under the smoke env."""
31
+ import serial # noqa: F401
32
+
33
+
34
+ def test_adapter_opens_loopback_against_real_pyserial() -> None:
35
+ """EmbeddedAdapter opens the real pyserial loop:// loopback (no board)."""
36
+ from urml_embedded_runtime import EmbeddedAdapter, EmbeddedConfig
37
+
38
+ with EmbeddedAdapter(EmbeddedConfig(port="loop://")) as buggy:
39
+ assert buggy.wait_passively(duration_seconds=0.0).success # forces a real _open()
40
+
41
+
42
+ def test_conformance_runner_accepts_real_adapter_factory() -> None:
43
+ """The ConformanceRunner accepts a real EmbeddedAdapter factory."""
44
+ from urml_conformance import ConformanceRunner
45
+
46
+ from urml_embedded_runtime import EmbeddedAdapter
47
+
48
+ runner = ConformanceRunner(adapter_factory=lambda: EmbeddedAdapter())
49
+ assert runner is not None
@@ -0,0 +1,121 @@
1
+ """Hermetic unit tests for EmbeddedAdapter — no pyserial install needed.
2
+
3
+ A fake ``serial`` module is injected into ``sys.modules`` so
4
+ ``_require_pyserial`` resolves and ``_open`` runs against a
5
+ controllable loopback double (the technique px4/marine/opcua use).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from collections.abc import Iterator
12
+ from types import ModuleType
13
+ from typing import Any
14
+
15
+ import pytest
16
+ from urml_ros2_runtime.substrate.base import DetectionResult, ROSAdapter
17
+
18
+
19
+ class _FakePort:
20
+ def __init__(self) -> None:
21
+ self.written: list[bytes] = []
22
+ self.closed = False
23
+
24
+ def write(self, data: bytes) -> int:
25
+ self.written.append(data)
26
+ return len(data)
27
+
28
+ def readline(self) -> bytes:
29
+ return b"21.5\n"
30
+
31
+ def close(self) -> None:
32
+ self.closed = True
33
+
34
+
35
+ class _FakeSerial(ModuleType):
36
+ def __init__(self) -> None:
37
+ super().__init__("serial")
38
+ self.last_port: _FakePort | None = None
39
+
40
+ def serial_for_url(url: str, baudrate: int = 115200, timeout: float = 2.0) -> _FakePort:
41
+ p = _FakePort()
42
+ self.last_port = p
43
+ return p
44
+
45
+ self.serial_for_url = serial_for_url # type: ignore[attr-defined]
46
+
47
+
48
+ @pytest.fixture
49
+ def fake_serial() -> Iterator[_FakeSerial]:
50
+ fake = _FakeSerial()
51
+ saved = sys.modules.get("serial")
52
+ sys.modules["serial"] = fake
53
+ try:
54
+ yield fake
55
+ finally:
56
+ if saved is None:
57
+ sys.modules.pop("serial", None)
58
+ else:
59
+ sys.modules["serial"] = saved
60
+
61
+
62
+ def test_buggy_lifecycle(fake_serial: _FakeSerial) -> None:
63
+ from urml_embedded_runtime import EmbeddedAdapter, EmbeddedConfig
64
+
65
+ cfg = EmbeddedConfig(
66
+ location_to_command={"waypoint_a": "GO A", "dock": "HOME"},
67
+ manipulation_commands={"grasp": "CLAW C", "release": "CLAW O"},
68
+ )
69
+ with EmbeddedAdapter(cfg) as buggy:
70
+ assert isinstance(buggy, ROSAdapter)
71
+ ok = buggy.send_navigation_goal(location="waypoint_a")
72
+ assert ok.success
73
+ assert fake_serial.last_port is not None and fake_serial.last_port.written[0] == b"GO A\n"
74
+ miss = buggy.send_navigation_goal(location="nowhere")
75
+ assert miss.success is False and miss.reason is not None
76
+ assert miss.reason.startswith("location_not_configured")
77
+ assert buggy.send_manipulation_goal(action="grasp").success
78
+ meas = buggy.take_measurement(what="light", target=None, sensor=None)
79
+ assert meas.success and meas.payload is not None and meas.payload["value"] == 21.5
80
+ assert buggy.wait_passively(duration_seconds=0.1).success
81
+ scan = buggy.run_scan(
82
+ area={}, pattern="grid", overlap=0.1, altitude=None, media="sensor_only", sensor=None
83
+ )
84
+ assert not scan.success and "area-scan controller" in (scan.reason or "")
85
+
86
+
87
+ def test_unsupported_and_not_applicable_sentinels(fake_serial: _FakeSerial) -> None:
88
+ from urml_embedded_runtime import EmbeddedAdapter
89
+
90
+ buggy = EmbeddedAdapter()
91
+ det: DetectionResult = buggy.query_detection(object_class="ball")
92
+ assert det.success is False and det.reason is not None
93
+ assert det.reason.startswith("not_supported_on_mcu")
94
+ nores = buggy.send_manipulation_goal(action="grasp")
95
+ assert nores.success is False and nores.reason is not None
96
+ assert nores.reason.startswith("manipulation_command_not_configured")
97
+ for r in (buggy.send_takeoff_goal(altitude=1.0), buggy.send_land_goal(), buggy.send_return_to_home_goal()):
98
+ assert r.success is False
99
+ assert r.reason is not None and r.reason.startswith("not_applicable_mcu")
100
+
101
+
102
+ def test_missing_pyserial_is_actionable(monkeypatch: pytest.MonkeyPatch) -> None:
103
+ """Construction without the [serial] extra raises a clear error.
104
+
105
+ Setting the sys.modules entry to None forces ``import serial`` to
106
+ raise ImportError deterministically, whether or not pyserial is
107
+ actually installed in the test environment.
108
+ """
109
+ from urml_embedded_runtime import EmbeddedAdapter
110
+
111
+ monkeypatch.setitem(sys.modules, "serial", None)
112
+ with pytest.raises(RuntimeError, match=r"\[serial\] extra"):
113
+ EmbeddedAdapter()
114
+
115
+
116
+ def test_conformance_runner_accepts_factory(fake_serial: _FakeSerial) -> None:
117
+ from urml_conformance import ConformanceRunner
118
+
119
+ from urml_embedded_runtime import EmbeddedAdapter
120
+
121
+ assert ConformanceRunner(adapter_factory=lambda: EmbeddedAdapter()) is not None