OpenSMI-ROS2 0.1.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.
Files changed (89) hide show
  1. opensmi/ros2/__init__.py +89 -0
  2. opensmi/ros2/__main__.py +11 -0
  3. opensmi/ros2/cli.py +143 -0
  4. opensmi/ros2/py.typed +0 -0
  5. opensmi/ros2/runtime/__init__.py +67 -0
  6. opensmi/ros2/runtime/_decode.py +101 -0
  7. opensmi/ros2/runtime/_encode.py +102 -0
  8. opensmi/ros2/runtime/_parser.py +147 -0
  9. opensmi/ros2/runtime/errors.py +141 -0
  10. opensmi/ros2/runtime/goal.py +232 -0
  11. opensmi/ros2/runtime/graph.py +288 -0
  12. opensmi/ros2/runtime/guard.py +213 -0
  13. opensmi/ros2/runtime/interface.py +140 -0
  14. opensmi/ros2/runtime/messages/__init__.py +503 -0
  15. opensmi/ros2/runtime/messages/industrial_msgs.py +62 -0
  16. opensmi/ros2/runtime/messages/industrial_msgs.pyi +159 -0
  17. opensmi/ros2/runtime/messages/motoros2_interfaces.py +79 -0
  18. opensmi/ros2/runtime/messages/motoros2_interfaces.pyi +307 -0
  19. opensmi/ros2/runtime/messages/neo_msgs2.py +55 -0
  20. opensmi/ros2/runtime/messages/neo_msgs2.pyi +138 -0
  21. opensmi/ros2/runtime/messages/neo_srvs2.py +72 -0
  22. opensmi/ros2/runtime/messages/neo_srvs2.pyi +224 -0
  23. opensmi/ros2/runtime/outcomes.py +103 -0
  24. opensmi/ros2/runtime/parameters.py +723 -0
  25. opensmi/ros2/runtime/publisher.py +125 -0
  26. opensmi/ros2/runtime/qos.py +394 -0
  27. opensmi/ros2/runtime/runtime.py +1171 -0
  28. opensmi/ros2/runtime/selection.py +150 -0
  29. opensmi/ros2/runtime/stamp.py +100 -0
  30. opensmi/ros2/runtime/subscription.py +354 -0
  31. opensmi/ros2/runtime/tf.py +714 -0
  32. opensmi/ros2/server/__init__.py +148 -0
  33. opensmi/ros2/server/access.py +109 -0
  34. opensmi/ros2/server/bindings/__init__.py +92 -0
  35. opensmi/ros2/server/bindings/_base.py +154 -0
  36. opensmi/ros2/server/bindings/action.py +133 -0
  37. opensmi/ros2/server/bindings/keyed.py +127 -0
  38. opensmi/ros2/server/bindings/lifecycle.py +131 -0
  39. opensmi/ros2/server/bindings/method.py +130 -0
  40. opensmi/ros2/server/bindings/monitoring.py +109 -0
  41. opensmi/ros2/server/bindings/parameter.py +133 -0
  42. opensmi/ros2/server/bindings/publisher.py +192 -0
  43. opensmi/ros2/server/bindings/registry.py +95 -0
  44. opensmi/ros2/server/bindings/tf.py +256 -0
  45. opensmi/ros2/server/browse_names.py +94 -0
  46. opensmi/ros2/server/component.py +334 -0
  47. opensmi/ros2/server/config.py +493 -0
  48. opensmi/ros2/server/containers.py +191 -0
  49. opensmi/ros2/server/drivers.py +421 -0
  50. opensmi/ros2/server/errors.py +159 -0
  51. opensmi/ros2/server/events.py +406 -0
  52. opensmi/ros2/server/introspection.py +850 -0
  53. opensmi/ros2/server/keyed.py +749 -0
  54. opensmi/ros2/server/lifecycle.py +238 -0
  55. opensmi/ros2/server/limits.py +66 -0
  56. opensmi/ros2/server/loader.py +977 -0
  57. opensmi/ros2/server/machine.py +225 -0
  58. opensmi/ros2/server/method.py +307 -0
  59. opensmi/ros2/server/mirror.py +582 -0
  60. opensmi/ros2/server/mutation.py +992 -0
  61. opensmi/ros2/server/nodesets/Opc.Ua.SmartFactory.ROS2.NodeSet2.xml +85 -0
  62. opensmi/ros2/server/nodesets/__init__.py +18 -0
  63. opensmi/ros2/server/nodesets/smart_factory_ros2.py +26 -0
  64. opensmi/ros2/server/parameters.py +704 -0
  65. opensmi/ros2/server/projection.py +1176 -0
  66. opensmi/ros2/server/projections/__init__.py +41 -0
  67. opensmi/ros2/server/projections/scope.py +222 -0
  68. opensmi/ros2/server/provenance.py +121 -0
  69. opensmi/ros2/server/publisher.py +781 -0
  70. opensmi/ros2/server/recipes.py +514 -0
  71. opensmi/ros2/server/required.py +633 -0
  72. opensmi/ros2/server/skill.py +363 -0
  73. opensmi/ros2/server/spatial.py +283 -0
  74. opensmi/ros2/server/startup.py +626 -0
  75. opensmi/ros2/server/status.py +107 -0
  76. opensmi/ros2/server/structures.py +135 -0
  77. opensmi/ros2/server/transforms/__init__.py +39 -0
  78. opensmi/ros2/server/transforms/conversions.py +58 -0
  79. opensmi/ros2/server/transforms/filing.py +340 -0
  80. opensmi/ros2/server/transforms/mirror.py +462 -0
  81. opensmi/ros2/server/transforms/outward.py +180 -0
  82. opensmi/ros2/server/transforms/records.py +195 -0
  83. opensmi/ros2/server/transforms/spatial.py +154 -0
  84. opensmi_ros2-0.1.0.dist-info/METADATA +183 -0
  85. opensmi_ros2-0.1.0.dist-info/RECORD +89 -0
  86. opensmi_ros2-0.1.0.dist-info/WHEEL +5 -0
  87. opensmi_ros2-0.1.0.dist-info/entry_points.txt +2 -0
  88. opensmi_ros2-0.1.0.dist-info/licenses/LICENSES/MIT.txt +18 -0
  89. opensmi_ros2-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,89 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Expose a ROS2 system as an OPC UA server, built on opensmi.server and the SkillSet information model.
6
+
7
+ A ROS2 robot shows up to an OPC UA client as a Machine with Components that carry Skills, Methods and
8
+ Monitoring variables, not as a list of topics, services and actions. You declare what to expose with
9
+ Bindings on a Component. A Binding ties one ROS2 noun to its place in the address space:
10
+
11
+ ======================== =====================================================================
12
+ ROS2 side OPC UA side
13
+ ======================== =====================================================================
14
+ Topic, read Monitoring variables
15
+ Topic, published Skill
16
+ Service Method
17
+ Action Skill, with feedback and a Result
18
+ Lifecycle node StartupSkill
19
+ TF tree RSL Locations inside a SpatialObject
20
+ Diagnostics topic One member per diagnostic id, and an event per level change
21
+ Node parameters Parameters, writable, with ROS2's own answer as the status code
22
+ ======================== =====================================================================
23
+
24
+ The distribution is OpenSMI-ROS2, imported as the namespace package ``opensmi.ros2`` next to
25
+ ``opensmi.server`` and ``opensmi.core``. It has two halves:
26
+
27
+ * :mod:`opensmi.ros2.runtime` owns ``rclpy`` and knows nothing about OPC UA. It imports only the
28
+ standard library, ``rclpy`` and ``tf2_ros`` from ROS2, ``structlog`` and ``typing-extensions``.
29
+ * :mod:`opensmi.ros2.server` is the OPC UA layer on top of ``opensmi.server``. Start there.
30
+
31
+ Requirements: a sourced ROS2 Jazzy (no other distribution), Linux and Python 3.11 or newer. ``rclpy``
32
+ comes from the ROS2 installation, not from PyPI. On WSL, Fast DDS needs ``FASTDDS_BUILTIN_TRANSPORTS=SHM``.
33
+
34
+ A whole server with one Component that reads the ``std_msgs/String`` topic ``/chatter``, as the
35
+ ROS2 demo talker publishes it:
36
+
37
+ .. code-block:: python
38
+
39
+ import asyncio
40
+
41
+ from asyncua import ua
42
+ from opensmi.server import BaseComponent, BaseMachine, Server
43
+
44
+ from opensmi.ros2.runtime import Runtime
45
+ from opensmi.ros2.server import MonitoringBinding, ROS2ComponentMixin, ROS2MachineMixin
46
+
47
+
48
+ class Talker(ROS2ComponentMixin, BaseComponent):
49
+ bindings = (MonitoringBinding(name="Chatter", path="/chatter", message_type="std_msgs/msg/String"),)
50
+
51
+ async def _write_identification(self) -> None:
52
+ await self.identification.SerialNumber.write("talker-0001")
53
+ await self.identification.Manufacturer.write(ua.LocalizedText("Example", "en-US"))
54
+
55
+
56
+ class Robot(ROS2MachineMixin, BaseMachine):
57
+ async def _write_identification(self) -> None:
58
+ await self.identification.SerialNumber.write("robot-0001")
59
+ await self.identification.ProductInstanceUri.write("urn:example:robot")
60
+ await self.identification.Manufacturer.write(ua.LocalizedText("Example", "en-US"))
61
+
62
+ async def _init(self) -> None:
63
+ await super()._init()
64
+ await self.add_component(Talker(name="Talker"))
65
+
66
+
67
+ async def main() -> None:
68
+ async with Server() as server:
69
+ await server.add_machine(Robot(runtime=Runtime(domain_id=0)))
70
+ await server.start(blocking=True)
71
+
72
+
73
+ asyncio.run(main())
74
+
75
+ Start ``ros2 run demo_nodes_py talker``, run the script and connect a client. The Component Talker
76
+ then has a Monitoring variable ``Chatter/Data`` that changes with every message. Mixins go before the
77
+ opensmi base class. The application creates the Runtime and hands it to the Machine, which starts it
78
+ before anything is built and stops it afterwards.
79
+
80
+ The other kinds work the same way: :class:`~opensmi.ros2.server.MethodBinding`,
81
+ :class:`~opensmi.ros2.server.ActionBinding`, :class:`~opensmi.ros2.server.PublisherBinding`,
82
+ :class:`~opensmi.ros2.server.ROS2ParameterBinding`, :class:`~opensmi.ros2.server.LifecycleBinding`,
83
+ :class:`~opensmi.ros2.server.KeyedBinding` and :class:`~opensmi.ros2.server.TFBinding`. The example
84
+ Component in the repository (``examples/component.py``) declares one of each. A server can also come up
85
+ from one TOML file with ``opensmi-ros2 serve machine.toml``; see :mod:`opensmi.ros2.server.loader` and
86
+ :mod:`opensmi.ros2.cli`.
87
+
88
+ Not supported yet: removing Bindings or nodes at runtime, and a suspendable StartupSkill.
89
+ """
@@ -0,0 +1,11 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """``python -m opensmi.ros2``: the same command line as the ``opensmi-ros2`` console script."""
6
+
7
+ import sys
8
+
9
+ from opensmi.ros2.cli import main
10
+
11
+ sys.exit(main())
opensmi/ros2/cli.py ADDED
@@ -0,0 +1,143 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The command line: ``opensmi-ros2 serve machine.toml`` and ``python -m opensmi.ros2``.
6
+
7
+ Both call :func:`main`, which reads the file with :func:`~opensmi.ros2.server.loader.load_machine`,
8
+ builds opensmi's ``Server``, adds the Machine and serves until Ctrl+C or SIGTERM.
9
+
10
+ .. code-block:: console
11
+
12
+ opensmi-ros2 serve machine.toml
13
+ opensmi-ros2 serve machine.toml --server-config other-server.toml
14
+
15
+ ``rclpy`` is imported only once the whole file has been validated, so ``--help`` and a file with
16
+ mistakes work on a machine without ROS2.
17
+
18
+ ``[server] config = "server.toml"`` in the machine file and ``--server-config PATH`` point to an
19
+ opensmi server configuration (endpoint, users, logging). The command line wins. A path in the file is
20
+ relative to the file, a path on the command line to the working directory.
21
+
22
+ Exit status: 0 after a clean stop, 1 when the file or a configuration cannot be used (each mistake is
23
+ printed to stderr, one per line, and nothing has been started), 2 for a command line argparse refuses.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import asyncio
30
+ import contextlib
31
+ import signal
32
+ import sys
33
+ from pathlib import Path
34
+ from typing import TYPE_CHECKING
35
+
36
+ from opensmi.server import Server
37
+
38
+ from opensmi.ros2.server.errors import FileDeclarationError
39
+ from opensmi.ros2.server.loader import load_machine
40
+
41
+ if TYPE_CHECKING:
42
+ from collections.abc import Callable, Sequence
43
+
44
+ from opensmi.ros2.runtime.interface import RuntimeInterface
45
+ from opensmi.ros2.server.config import ROS2Config
46
+ from opensmi.ros2.server.loader import ConfiguredMachine
47
+
48
+ __all__ = ["main", "serve"]
49
+
50
+ PROG = "opensmi-ros2"
51
+
52
+
53
+ class _UnusableError(Exception):
54
+ """Something the user gave cannot be used; the message is what to tell them."""
55
+
56
+
57
+ def _parser() -> argparse.ArgumentParser:
58
+ parser = argparse.ArgumentParser(prog=PROG, description="Expose a ROS2 system as an OPC UA server.")
59
+ commands = parser.add_subparsers(dest="command", required=True, metavar="command")
60
+ serve_parser = commands.add_parser(
61
+ "serve",
62
+ help="start a server from a machine file and run until interrupted",
63
+ description="Start a server from a machine file and run until interrupted (Ctrl+C or SIGTERM).",
64
+ )
65
+ serve_parser.add_argument("machine_file", metavar="machine.toml", type=Path, help="the machine file (TOML)")
66
+ serve_parser.add_argument(
67
+ "--server-config",
68
+ metavar="PATH",
69
+ type=Path,
70
+ help="opensmi server configuration (endpoint, users, logging); overrides [server] config in the machine file",
71
+ )
72
+ return parser
73
+
74
+
75
+ async def serve(machine: ConfiguredMachine, *, server_config: Path | None, stop: asyncio.Event) -> None:
76
+ """Serve a Machine in an opensmi Server until ``stop`` is set, then shut the server down.
77
+
78
+ :param machine: The Machine to serve.
79
+ :param server_config: An opensmi server configuration file, or ``None`` for opensmi's defaults.
80
+ :param stop: Set to ask for a clean stop. Cancelling the task stops it as well.
81
+ :raises _UnusableError: When the server configuration cannot be read.
82
+ """
83
+ try:
84
+ server = Server(config=server_config)
85
+ except Exception as error:
86
+ msg = f"cannot use the server configuration {str(server_config)!r}: {error}"
87
+ raise _UnusableError(msg) from error
88
+ async with server:
89
+ await server.add_machine(machine)
90
+ await server.start(blocking=False)
91
+ await stop.wait()
92
+
93
+
94
+ async def _run(machine: ConfiguredMachine, server_config: Path | None) -> None:
95
+ """Serve until SIGINT or SIGTERM, where the loop can listen for them."""
96
+ stop = asyncio.Event()
97
+ loop = asyncio.get_running_loop()
98
+ for number in (signal.SIGINT, signal.SIGTERM):
99
+ # Not available on Windows' loop; asyncio.run turns Ctrl+C into a cancellation there.
100
+ with contextlib.suppress(NotImplementedError, ValueError, RuntimeError):
101
+ loop.add_signal_handler(number, stop.set)
102
+ await serve(machine, server_config=server_config, stop=stop)
103
+
104
+
105
+ def _require_file(given: Path | None) -> None:
106
+ """Refuse a ``--server-config`` that is not a file, before anything is built."""
107
+ if given is not None and not given.is_file():
108
+ msg = f"--server-config {str(given)!r} is not a file"
109
+ raise _UnusableError(msg)
110
+
111
+
112
+ def _refuse(message: str) -> int:
113
+ """Say on stderr why nothing was started, and return the exit status for it."""
114
+ sys.stderr.write(f"{PROG}: {message}\n")
115
+ return 1
116
+
117
+
118
+ def main(
119
+ argv: Sequence[str] | None = None,
120
+ *,
121
+ runtime_factory: Callable[[ROS2Config], RuntimeInterface] | None = None,
122
+ ) -> int:
123
+ """Run the command line and return its exit status.
124
+
125
+ :param argv: The arguments after the program name; ``None`` reads ``sys.argv``.
126
+ :param runtime_factory: Passed to ``load_machine``; ``None`` builds the real Runtime, which
127
+ needs ``rclpy``. A test passes one that returns its fake.
128
+ """
129
+ arguments = _parser().parse_args(argv)
130
+ path: Path = arguments.machine_file
131
+ try:
132
+ _require_file(arguments.server_config)
133
+ machine = load_machine(path, runtime_factory=runtime_factory)
134
+ except (FileDeclarationError, _UnusableError) as error:
135
+ return _refuse(str(error))
136
+ except OSError as error:
137
+ return _refuse(f"cannot read {str(path)!r}: {error.strerror or error}")
138
+ try:
139
+ with contextlib.suppress(KeyboardInterrupt):
140
+ asyncio.run(_run(machine, arguments.server_config or machine.server_config))
141
+ except _UnusableError as error:
142
+ return _refuse(str(error))
143
+ return 0
opensmi/ros2/py.typed ADDED
File without changes
@@ -0,0 +1,67 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The portable half: the Runtime, the sole owner of ROS2 access for one Machine.
6
+
7
+ This is the only part of the project that imports ``rclpy``. It speaks ROS2 vocabulary, knows
8
+ nothing about OPC UA and imports nothing from :mod:`opensmi.ros2.server` (enforced by
9
+ ``tests/test_import_boundary.py``).
10
+
11
+ The package exports what a server author touches: the :class:`Runtime` handed to a Machine, the
12
+ :class:`RuntimeInterface` it implements, the :class:`Message` base that Binding callbacks receive,
13
+ the :class:`ParameterType` of a parameter Binding and the QoS types. A custom lifecycle driver
14
+ also needs the :class:`Subscription` and :class:`ServiceTypes` returned by
15
+ :meth:`RuntimeInterface.subscribe` and :meth:`RuntimeInterface.describe_service`, the
16
+ :class:`QoSIncompatibility` and :class:`Provenance` records of a Subscription's QoS, and the
17
+ :class:`TypeHashMismatch` records. Everything else is internal plumbing (see CONTRIBUTING.md).
18
+
19
+ Only ``Runtime`` is exported lazily. The rest imports without a ROS2 installation, which the
20
+ server half and its tests rely on. Accessing ``Runtime`` without ROS2 raises ``ImportError``.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from typing import TYPE_CHECKING
26
+
27
+ from opensmi.ros2.runtime.interface import RuntimeInterface
28
+ from opensmi.ros2.runtime.messages import Message, ServiceTypes
29
+ from opensmi.ros2.runtime.parameters import ParameterType
30
+ from opensmi.ros2.runtime.qos import (
31
+ Durability,
32
+ Liveliness,
33
+ Provenance,
34
+ QoSIncompatibility,
35
+ QoSProfile,
36
+ Reliability,
37
+ )
38
+ from opensmi.ros2.runtime.subscription import Subscription, TypeHashMismatch
39
+
40
+ if TYPE_CHECKING:
41
+ from opensmi.ros2.runtime.runtime import Runtime
42
+
43
+ __all__ = [
44
+ "Durability",
45
+ "Liveliness",
46
+ "Message",
47
+ "ParameterType",
48
+ "Provenance",
49
+ "QoSIncompatibility",
50
+ "QoSProfile",
51
+ "Reliability",
52
+ "Runtime",
53
+ "RuntimeInterface",
54
+ "ServiceTypes",
55
+ "Subscription",
56
+ "TypeHashMismatch",
57
+ ]
58
+
59
+
60
+ def __getattr__(name: str) -> object:
61
+ """Resolve :class:`Runtime` on first use, so that importing this package needs no ROS2."""
62
+ if name == "Runtime":
63
+ from opensmi.ros2.runtime.runtime import Runtime
64
+
65
+ return Runtime
66
+ message = f"module {__name__!r} has no attribute {name!r}"
67
+ raise AttributeError(message)
@@ -0,0 +1,101 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The Decoder: one live ROS2 message instance becomes one message dataclass.
6
+
7
+ It runs on the event loop. ``rclpy`` objects use ``numpy.ndarray`` and ``array.array`` containers
8
+ and nested generated objects, none of which may cross into the server half. Each becomes a plain
9
+ Python value:
10
+
11
+ * a container of bytes (``uint8`` or ``byte``, fixed or not) becomes ``bytes``;
12
+ * every other container becomes a ``tuple``;
13
+ * a nested message becomes its own message dataclass;
14
+ * a ``byte`` scalar, which ``rclpy`` hands over as a one-byte ``bytes``, becomes an ``int``.
15
+
16
+ ``messages.is_byte_container`` decides the first case, so the dataclass annotation and the decoded
17
+ value agree. The per-field plan is cached per message dataclass.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from functools import cache
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from opensmi.ros2.runtime.messages import (
26
+ ArrayType,
27
+ NestedType,
28
+ PrimitiveType,
29
+ SequenceType,
30
+ is_byte_container,
31
+ )
32
+
33
+ if TYPE_CHECKING:
34
+ from collections.abc import Callable, Sequence
35
+
36
+ from opensmi.ros2.runtime.messages import ElementType, FieldType, Message
37
+
38
+
39
+ def decode(message: Any, message_type: type[Message]) -> Message:
40
+ """Convert one live ROS2 message instance into an instance of its message dataclass."""
41
+ return message_type(**{name: decode_field(getattr(message, name)) for name, decode_field in _plan(message_type)})
42
+
43
+
44
+ @cache
45
+ def _plan(message_type: type[Message]) -> tuple[tuple[str, Callable[[Any], Any]], ...]:
46
+ """Return the field-name and field-decoder pairs for a message dataclass, in field order."""
47
+ return tuple(
48
+ (field.name, _field_decoder(field.field_type, message_type.ros2_nested.get(field.name)))
49
+ for field in message_type.ros2.fields
50
+ )
51
+
52
+
53
+ def _field_decoder(field_type: FieldType, nested: type[Message] | None) -> Callable[[Any], Any]:
54
+ """Return the function that turns one ``rclpy`` field value into its plain Python value."""
55
+ if is_byte_container(field_type):
56
+ return _as_bytes
57
+ match field_type:
58
+ case ArrayType(element=element) | SequenceType(element=element):
59
+ decode_element = _element_decoder(element, nested)
60
+ if decode_element is None:
61
+ return tuple
62
+ return lambda value: tuple(decode_element(item) for item in value)
63
+ case _:
64
+ return _element_decoder(field_type, nested) or _unchanged
65
+
66
+
67
+ def _element_decoder(element: ElementType, nested: type[Message] | None) -> Callable[[Any], Any] | None:
68
+ """Return the decoder for a scalar, or ``None`` when the value already needs no work."""
69
+ match element:
70
+ case NestedType() if nested is not None:
71
+ return lambda value: decode(value, nested)
72
+ case PrimitiveType(name="byte"):
73
+ return _as_int
74
+ case _:
75
+ return None
76
+
77
+
78
+ def _unchanged(value: Any) -> Any:
79
+ """Return the value as it came (``rclpy`` already hands over a builtin)."""
80
+ return value
81
+
82
+
83
+ def _as_int(value: Any) -> int:
84
+ """Return a ``byte`` scalar (a one-byte ``bytes`` in ``rclpy``) as an integer."""
85
+ if isinstance(value, (bytes, bytearray)):
86
+ return value[0]
87
+ return int(value)
88
+
89
+
90
+ def _as_bytes(value: Any) -> bytes:
91
+ """Return a container of bytes as ``bytes``.
92
+
93
+ ``rclpy`` hands over a ``numpy.ndarray`` for a fixed ``uint8`` array, ``array.array('B')`` for
94
+ a ``uint8`` sequence and a list of one-byte ``bytes`` for an ``octet`` sequence.
95
+ """
96
+ if isinstance(value, (bytes, bytearray, memoryview)):
97
+ return bytes(value)
98
+ items: Sequence[Any] = value
99
+ if len(items) and isinstance(items[0], (bytes, bytearray)):
100
+ return b"".join(items)
101
+ return bytes(items)
@@ -0,0 +1,102 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The Encoder: one message dataclass becomes one live ROS2 message instance.
6
+
7
+ The mirror of :mod:`opensmi.ros2.runtime._decode`, so that no ``rclpy`` object crosses the seam.
8
+ It runs on the event loop. Each conversion inverts one the Decoder made, and a wrong shape
9
+ aborts the process instead of raising:
10
+
11
+ * a nested message becomes its generated interface class again;
12
+ * a ``tuple`` becomes a ``list``, which the generated constructors accept for every container;
13
+ * ``bytes`` stays ``bytes`` for a ``uint8`` container and becomes a list of one-byte values for
14
+ an ``octet`` one;
15
+ * a ``byte`` scalar becomes a one-byte ``bytes`` again, because handing the int back dies on
16
+ ``Assertion 'PyBytes_Check(field)' failed`` (pinned by a Jazzy test).
17
+
18
+ The Encoder does not validate. :mod:`opensmi.ros2.runtime.guard` does that beforehand, as a pure
19
+ function that needs no ROS2 installation to test.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from functools import cache
25
+ from typing import TYPE_CHECKING, Any
26
+
27
+ from opensmi.ros2.runtime._decode import _unchanged
28
+ from opensmi.ros2.runtime._parser import import_interface_class
29
+ from opensmi.ros2.runtime.messages import (
30
+ ArrayType,
31
+ NestedType,
32
+ PrimitiveType,
33
+ SequenceType,
34
+ is_byte_container,
35
+ )
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Callable
39
+
40
+ from opensmi.ros2.runtime.messages import ElementType, FieldType, Message
41
+
42
+
43
+ def encode(message: Message) -> Any:
44
+ """Convert one message dataclass into the ``rclpy`` object its ROS2 type is.
45
+
46
+ :param message: The payload, already checked by
47
+ :func:`opensmi.ros2.runtime.guard.require_sendable`.
48
+ :raises MissingInterfacePackageError: When the type's interface package is not installed,
49
+ which a declared type is refused for at init and an encoded one cannot reach.
50
+ """
51
+ interface_class, plan = _plan(type(message))
52
+ return interface_class(**{name: encode_field(getattr(message, name)) for name, encode_field in plan})
53
+
54
+
55
+ @cache
56
+ def _plan(message_type: type[Message]) -> tuple[Any, tuple[tuple[str, Callable[[Any], Any]], ...]]:
57
+ """Return the interface class and the field-name and field-encoder pairs, in field order."""
58
+ return (
59
+ import_interface_class(message_type.ros2.type_name),
60
+ tuple(
61
+ (field.name, _field_encoder(field.field_type, message_type.ros2_nested.get(field.name)))
62
+ for field in message_type.ros2.fields
63
+ ),
64
+ )
65
+
66
+
67
+ def _field_encoder(field_type: FieldType, nested: type[Message] | None) -> Callable[[Any], Any]:
68
+ """Return the function that turns one decoded field value back into what ``rclpy`` wants."""
69
+ if is_byte_container(field_type):
70
+ return _bytes_for(field_type)
71
+ match field_type:
72
+ case ArrayType(element=element) | SequenceType(element=element):
73
+ encode_element = _element_encoder(element, nested)
74
+ if encode_element is None:
75
+ return list
76
+ return lambda value: [encode_element(item) for item in value]
77
+ case _:
78
+ return _element_encoder(field_type, nested) or _unchanged
79
+
80
+
81
+ def _element_encoder(element: ElementType, nested: type[Message] | None) -> Callable[[Any], Any] | None:
82
+ """Return the encoder for a scalar, or ``None`` when the value already needs no work."""
83
+ match element:
84
+ case NestedType() if nested is not None:
85
+ return encode
86
+ case PrimitiveType(name="byte"):
87
+ return _as_one_byte
88
+ case _:
89
+ return None
90
+
91
+
92
+ def _as_one_byte(value: Any) -> bytes:
93
+ """Return a ``byte`` scalar as the one-byte ``bytes`` ``rclpy`` uses for IDL ``octet``."""
94
+ return value if isinstance(value, bytes) else bytes([value])
95
+
96
+
97
+ def _bytes_for(field_type: FieldType) -> Callable[[Any], Any]:
98
+ """Return how a byte container is handed over: ``uint8`` as a buffer, ``byte`` as a list of ``bytes``."""
99
+ element = field_type.element if isinstance(field_type, (ArrayType, SequenceType)) else field_type
100
+ if isinstance(element, PrimitiveType) and element.name == "byte":
101
+ return lambda value: [bytes([item]) for item in value]
102
+ return bytes
@@ -0,0 +1,147 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The Parser: a ROS2 interface definition becomes a field structure and its types.
6
+
7
+ It reads the installed interface package by introspection over the generated class. The vendored
8
+ parser in ``tools/catalog/`` reads the other source and produces the same ``MessageDescription``;
9
+ a Jazzy CI job checks that the two agree. This is the one module that imports interface packages,
10
+ and it imports no ``rclpy``. Private: an interface class must not reach code above the seam.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import importlib
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from opensmi.ros2.runtime.errors import MissingInterfacePackageError, UnusableMessageTypeError
19
+ from opensmi.ros2.runtime.messages import (
20
+ ACTION_MEMBERS,
21
+ SERVICE_MEMBERS,
22
+ FieldDescription,
23
+ MessageDescription,
24
+ canonical_type_name,
25
+ parse_field_type,
26
+ )
27
+
28
+ if TYPE_CHECKING:
29
+ from collections.abc import Iterable
30
+
31
+
32
+ def describe(type_name: str) -> MessageDescription:
33
+ """Return the structure of a ROS2 message type, read off its installed interface class."""
34
+ canonical = canonical_type_name(type_name)
35
+ return _describe_class(canonical, import_interface_class(canonical))
36
+
37
+
38
+ def import_interface_class(type_name: str) -> Any:
39
+ """Import and return the generated interface class for a ROS2 type name.
40
+
41
+ :param type_name: ``package/kind/Name``, or ``package/Name`` for a message.
42
+ :raises InvalidMessageTypeNameError: When the name has neither shape.
43
+ :raises MissingInterfacePackageError: When the interface package is not installed. This is
44
+ fatal at init: ``rclpy`` cannot subscribe to a type without its typesupport.
45
+ :raises UnusableMessageTypeError: When the package is installed but has no such message.
46
+ """
47
+ package, kind, module, name = _import_package(type_name)
48
+ interface_class = getattr(module, name, None) or _action_member(module, name)
49
+ if interface_class is None or not hasattr(interface_class, "get_fields_and_field_types"):
50
+ message = f"{package}.{kind} is installed but does not define the message {name!r}"
51
+ raise UnusableMessageTypeError(message)
52
+ return interface_class
53
+
54
+
55
+ def import_action_class(type_name: str) -> Any:
56
+ """Import and return the generated class for a ROS2 action type (``package/action/Name``).
57
+
58
+ :raises InvalidMessageTypeNameError: When the name has the wrong shape.
59
+ :raises MissingInterfacePackageError: When the interface package is not installed.
60
+ :raises UnusableMessageTypeError: When the package has no such action.
61
+ """
62
+ return _import_members(type_name, "action", ACTION_MEMBERS)
63
+
64
+
65
+ def import_service_class(type_name: str) -> Any:
66
+ """Import and return the generated class for a ROS2 service type (``package/srv/Name``).
67
+
68
+ :raises InvalidMessageTypeNameError: When the name has the wrong shape.
69
+ :raises MissingInterfacePackageError: When the interface package is not installed.
70
+ :raises UnusableMessageTypeError: When the package has no such service.
71
+ """
72
+ return _import_members(type_name, "service", SERVICE_MEMBERS)
73
+
74
+
75
+ def _import_members(type_name: str, what: str, members: Iterable[str]) -> Any:
76
+ """Import an action or service class, which has no fields of its own and so skips :func:`import_interface_class`."""
77
+ package, kind, module, name = _import_package(type_name)
78
+ interface_class = getattr(module, name, None)
79
+ if interface_class is None or not all(hasattr(interface_class, member) for member in members):
80
+ message = f"{package}.{kind} is installed but does not define the {what} {name!r}"
81
+ raise UnusableMessageTypeError(message)
82
+ return interface_class
83
+
84
+
85
+ def _import_package(type_name: str) -> tuple[str, str, Any, str]:
86
+ """Import the module one ROS2 type lives in, and return the parts of its name with it.
87
+
88
+ :raises MissingInterfacePackageError: When the interface package is not installed.
89
+ :raises UnusableMessageTypeError: When the package is installed but the module is not there.
90
+ """
91
+ package, kind, name = canonical_type_name(type_name).split("/")
92
+ try:
93
+ module = importlib.import_module(f"{package}.{kind}")
94
+ except ModuleNotFoundError as error:
95
+ if error.name == package:
96
+ message = (
97
+ f"the interface package {package!r} is not installed, so no Binding can receive "
98
+ f"{type_name!r}; install the package or drop the declaration"
99
+ )
100
+ raise MissingInterfacePackageError(message) from error
101
+ message = f"{package} is installed but {package}.{kind} could not be imported"
102
+ raise UnusableMessageTypeError(message) from error
103
+ return package, kind, module, name
104
+
105
+
106
+ def _action_member(module: Any, name: str) -> Any:
107
+ """Return the generated class of an action's goal, feedback or result, or ``None``.
108
+
109
+ The package exports only ``Fibonacci``, while ROS2 names the goal ``Fibonacci_Goal`` elsewhere,
110
+ so that spelling is resolved as ``Fibonacci.Goal``. The suffix must be an action member name,
111
+ so a message genuinely called ``Foo_Bar`` is not mistaken for a member of a missing ``Foo``.
112
+ """
113
+ parent, _, member = name.rpartition("_")
114
+ if not parent or member not in ACTION_MEMBERS:
115
+ return None
116
+ return getattr(getattr(module, parent, None), member, None)
117
+
118
+
119
+ def _describe_class(type_name: str, interface_class: Any) -> MessageDescription:
120
+ """Model every field of an interface class, in declaration order."""
121
+ # Both come from the same member list in the same order. The strict zip raises if a future
122
+ # generator breaks that, instead of pairing a field with another field's type.
123
+ field_types: dict[str, str] = interface_class.get_fields_and_field_types()
124
+ slots: tuple[object, ...] = interface_class.SLOT_TYPES
125
+ fields = tuple(
126
+ FieldDescription(
127
+ name=name,
128
+ field_type=parse_field_type(text, nested_type_name=_nested_type_name(slot)),
129
+ ros2_text=text,
130
+ )
131
+ for (name, text), slot in zip(field_types.items(), slots, strict=True)
132
+ )
133
+ return MessageDescription(type_name=type_name, fields=fields)
134
+
135
+
136
+ def _nested_type_name(slot: object) -> str | None:
137
+ """Return the fully qualified name of a slot's nested type, or ``None`` when it has none.
138
+
139
+ The field-type string drops the ``msg``/``srv``/``action`` namespace, which only the slot keeps.
140
+ """
141
+ # An Array or a sequence wraps its element type; a scalar field's slot is the element type.
142
+ element: Any = getattr(slot, "value_type", slot)
143
+ namespaces: tuple[str, ...] | None = getattr(element, "namespaces", None)
144
+ if namespaces is None:
145
+ return None
146
+ name: str = element.name
147
+ return "/".join([*namespaces, name])