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,225 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The Machine side: one injected Runtime, started at init and stopped at shutdown.
6
+
7
+ A mixin that goes ahead of opensmi's ``BaseMachine``:
8
+
9
+ .. code-block:: python
10
+
11
+ class Robot(ROS2MachineMixin, BaseMachine):
12
+ async def _init(self) -> None:
13
+ await super()._init()
14
+ await self.add_component(Platform(name="Platform"))
15
+
16
+
17
+ config = ROS2Config.from_toml("ros2.toml")
18
+ runtime = Runtime(domain_id=config.domain_id, node_name=config.node_name)
19
+ await server.add_machine(Robot(runtime=runtime, ros2_config=config))
20
+
21
+ The application constructs the (unstarted) Runtime, because a Runtime is the unit of one Domain ID
22
+ and tests need to pass a double; the mixin owns its lifetime. It starts before the Machine's
23
+ ``_init``, since Components subscribe while building their nodes, and stops after its
24
+ ``_shutdown``. A Machine that fails to build stops its Runtime too.
25
+
26
+ The Machine also adds the StartupSkill opensmi expects (default
27
+ :class:`~opensmi.ros2.server.required.ROS2StartupSkill`), which starts each
28
+ Component's StartupSkill so that startup completes only when every Required Binding is satisfied.
29
+ It holds the default Projection registry that each Component derives its own from, and the
30
+ byte-string ceiling, which is published before any Component is built
31
+ (:mod:`opensmi.ros2.server.limits`). Through :class:`opensmi.ros2.server.events.ROS2ModelChangeMixin`
32
+ it carries the BindingEvent and the standard model-change event, and the Machine-wide cap on
33
+ mutations. A Machine may declare a TF Binding of its own and runs the TF poll for every
34
+ SpatialObject on it (:mod:`opensmi.ros2.server.transforms`).
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ from collections.abc import AsyncGenerator
40
+ from typing import TYPE_CHECKING, Any
41
+
42
+ from opensmi.core.lifecycle_mixin import lifecycle
43
+ from opensmi.server.base_machinery_item import BaseMachineryItem
44
+ from opensmi.server.base_startup_skill import BaseStartupSkill
45
+
46
+ from opensmi.ros2.server.bindings import TFBinding, resolve_bindings
47
+ from opensmi.ros2.server.config import ROS2Config
48
+ from opensmi.ros2.server.errors import DeclarationError
49
+ from opensmi.ros2.server.events import ROS2ModelChangeMixin
50
+ from opensmi.ros2.server.introspection import ROS2IntrospectionComponent
51
+ from opensmi.ros2.server.limits import publish_byte_string_ceiling
52
+ from opensmi.ros2.server.projections import DEFAULT_REGISTRY
53
+ from opensmi.ros2.server.required import ROS2StartupSkill, close_startup_skills
54
+ from opensmi.ros2.server.transforms import ROS2TransformMirrorMixin
55
+
56
+ if TYPE_CHECKING:
57
+ from collections.abc import Sequence
58
+ from pathlib import Path
59
+
60
+ from opensmi.ros2.runtime.interface import RuntimeInterface
61
+ from opensmi.ros2.server.bindings import Binding
62
+ from opensmi.ros2.server.projection import Projection, ProjectionRegistry
63
+
64
+ __all__ = ["ROS2MachineMixin"]
65
+
66
+
67
+ class ROS2MachineMixin(ROS2ModelChangeMixin, ROS2TransformMirrorMixin):
68
+ """Gives a Machine its Runtime, and its Runtime a lifetime.
69
+
70
+ :cvar introspection_component_type: The Component that answers what is on the ROS2 graph and
71
+ what this Machine is bound to. It is always added, with no flag to turn it off;
72
+ the access level on its mutators is the safeguard. Replaceable to add listings.
73
+ :cvar startup_skill_type: The StartupSkill added when the Machine registers none of its own.
74
+ Replace it with a subclass of the stock one.
75
+ :cvar projections: The Projections this Machine adds to the shipped catalogue. Every Component
76
+ on it derives its own registry from the result.
77
+ :cvar bindings: TF Bindings only: the one frame the Machine is. Any other kind is
78
+ refused, because it would land nowhere.
79
+ :cvar bindings_toml: A Binding file whose declarations union with ``bindings``, or ``None``.
80
+ """
81
+
82
+ introspection_component_type: type[ROS2IntrospectionComponent] = ROS2IntrospectionComponent
83
+ projections: Sequence[Projection] = ()
84
+ bindings: Sequence[Binding] = ()
85
+ bindings_toml: str | Path | None = None
86
+ startup_skill_type: type[ROS2StartupSkill] = ROS2StartupSkill
87
+
88
+ def __init__(
89
+ self,
90
+ *args: Any,
91
+ runtime: RuntimeInterface,
92
+ ros2_config: ROS2Config | None = None,
93
+ **kwargs: Any,
94
+ ) -> None:
95
+ """Take the Runtime this Machine owns, and pass everything else to opensmi.
96
+
97
+ :param runtime: The Runtime, constructed and not yet started.
98
+ :param ros2_config: The ROS2 settings this deployment loaded, or ``None`` for the
99
+ defaults. The Components read the settings that are not the Runtime's from it.
100
+ """
101
+ super().__init__(*args, **kwargs)
102
+ self._ros2_runtime = runtime
103
+ self._ros2_config = ros2_config or ROS2Config()
104
+ self._resolved_projections: ProjectionRegistry | None = None
105
+ self._resolved_bindings: tuple[Binding, ...] | None = None
106
+ self._ros2_byte_string_ceiling = 0
107
+
108
+ @property
109
+ def runtime(self) -> RuntimeInterface:
110
+ """Return this Machine's Runtime, which is where all its ROS2 access goes."""
111
+ return self._ros2_runtime
112
+
113
+ @property
114
+ def ros2_config(self) -> ROS2Config:
115
+ """Return the ROS2 settings this Machine was built with, defaults included."""
116
+ return self._ros2_config
117
+
118
+ @property
119
+ def ros2_bindings(self) -> tuple[Binding, ...]:
120
+ """Return the Bindings this Machine declared, which may only be TF Bindings.
121
+
122
+ Resolved once and held.
123
+
124
+ :raises DeclarationError: When a kind other than :class:`TFBinding` is declared.
125
+ :raises DuplicateBindingNameError: When one name appears twice, in either source.
126
+ """
127
+ if self._resolved_bindings is None:
128
+ resolved = resolve_bindings(self.bindings, self.bindings_toml)
129
+ _require_only_frames(self, resolved)
130
+ self._resolved_bindings = resolved
131
+ return self._resolved_bindings
132
+
133
+ @property
134
+ def ros2_projections(self) -> ProjectionRegistry:
135
+ """Return this Machine's default registry: the shipped catalogue plus its own entries.
136
+
137
+ Resolved once and held. Every Component derives its own registry from this one; nothing
138
+ discovers an entry, and no Component's curation reaches another's.
139
+
140
+ :raises DuplicateProjectionError: When an entry covers a type the shipped catalogue
141
+ already covers and does not say ``override=True``.
142
+ """
143
+ if self._resolved_projections is None:
144
+ self._resolved_projections = DEFAULT_REGISTRY.extended(self.projections)
145
+ return self._resolved_projections
146
+
147
+ @property
148
+ def ros2_byte_string_ceiling(self) -> int:
149
+ """Return how many bytes a bulk payload on this Machine may carry, or ``0`` for no limit.
150
+
151
+ Published in the server's capability variable at init and applied by the Projection that
152
+ produces the bytes. Zero before init.
153
+ """
154
+ return self._ros2_byte_string_ceiling
155
+
156
+ async def _init(self) -> None:
157
+ """Let opensmi initialise the Machine, then add the introspection Component.
158
+
159
+ The introspection Component comes first, so it browses ahead of whatever this Machine
160
+ declares. The Machine's own SpatialObject, if it declared a TF Binding, is created next so
161
+ that it joins the list before any Component's.
162
+ """
163
+ await super()._init() # pyright: ignore[reportAttributeAccessIssue]
164
+ add_component: Any = getattr(self, "add_component") # noqa: B009 -- opensmi's, not ours
165
+ await add_component(self.introspection_component_type())
166
+ await self._init_ros2_spatial_object()
167
+
168
+ async def _shutdown(self) -> None:
169
+ """Close the Machine's TF watch, then let opensmi shut the Machine down."""
170
+ await self._stop_spatial_object()
171
+ await super()._shutdown() # pyright: ignore[reportAttributeAccessIssue]
172
+
173
+ @lifecycle(after=BaseMachineryItem.lifecycle_machinery_item)
174
+ async def lifecycle_ros2_startup(self) -> AsyncGenerator[None]:
175
+ """Add the default StartupSkill unless the Machine registered one; release it at the end.
176
+
177
+ Runs after the Machine's ``_init`` so that a StartupSkill registered there is seen however
178
+ it is ordered against ``super()._init()``. The Skill gets the ``skill_access_level`` of
179
+ the ROS2 settings, so the orchestrator can start the Machine with no operator.
180
+ It is released before the Components are shut down, because it holds a task and a watch.
181
+ """
182
+ skills: Any = getattr(self, "skill_set") # noqa: B009 -- opensmi's, not ours
183
+ if BaseStartupSkill.NAME not in skills:
184
+ add_skill: Any = getattr(self, "add_skill") # noqa: B009 -- opensmi's, not ours
185
+ await add_skill(self.startup_skill_type(minimum_access_level=self._ros2_config.skill_access_level))
186
+ yield
187
+ await close_startup_skills(self)
188
+
189
+ @lifecycle(before=BaseMachineryItem.lifecycle_machinery_item)
190
+ async def lifecycle_ros2_runtime(self) -> AsyncGenerator[None]:
191
+ """Start the Runtime and publish the byte-string ceiling; stop the Runtime at the end.
192
+
193
+ Runs before the Machine's ``_init`` and after its ``_shutdown``. opensmi rolls a failed
194
+ init back through this step too, so a Machine that refuses to boot leaves no rclpy
195
+ Context or executor thread behind. A stop that was not clean is logged, not raised.
196
+
197
+ :raises RuntimeAlreadyStartedError: When the injected Runtime is already up.
198
+ """
199
+ await self._ros2_runtime.start()
200
+ try:
201
+ self._ros2_byte_string_ceiling = await publish_byte_string_ceiling(self.server.ua_server)
202
+ except BaseException:
203
+ await self._ros2_runtime.stop()
204
+ raise
205
+ yield
206
+ outcome = await self._ros2_runtime.stop()
207
+ if not outcome.ok:
208
+ self.logger.warning("The Runtime did not stop cleanly", faults=outcome.faults)
209
+
210
+
211
+ def _require_only_frames(machine: ROS2MachineMixin, declared: tuple[Binding, ...]) -> None:
212
+ """Refuse a Machine-level declaration that is not about where this Machine is.
213
+
214
+ :raises DeclarationError: On any kind but :class:`TFBinding`.
215
+ """
216
+ wrong = [each for each in declared if not isinstance(each, TFBinding)]
217
+ if not wrong:
218
+ return
219
+ listed = ", ".join(f"{each.name!r} ({type(each).__name__})" for each in wrong)
220
+ message = (
221
+ f"{type(machine).__name__} declares {listed} on the Machine; a Machine exposes nothing of "
222
+ f"its own but where it is in space, so the only kind it may declare is a TFBinding -- "
223
+ f"every other kind lands on a Component's Monitoring, ParameterSet, MethodSet or SkillSet"
224
+ )
225
+ raise DeclarationError(message)
@@ -0,0 +1,307 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """A service is a Method: a client writes the request, calls, and reads what came back.
6
+
7
+ ====================== ========================================================================
8
+ ``ParameterSet`` The request's fields, writable in any state. They are the Method's
9
+ arguments, because opensmi's ``Call`` takes none of its own.
10
+ ``Call`` Read the Parameters, build the request, send it, write the response.
11
+ ``FinalResultData`` The response's fields, written when the call returns.
12
+ ====================== ========================================================================
13
+
14
+ A Method has no Monitoring, because a service has no feedback.
15
+
16
+ opensmi's ``Call`` checks the access level (the Skill level, ``skill_access_level``, default
17
+ :data:`~opensmi.ros2.server.access.SKILL_ACCESS_LEVEL`, because a service call commands the robot),
18
+ the Lock and a completed startup, then runs :meth:`ROS2ServiceMethod.execute_method`. A
19
+ ``UaStatusCodeError`` raised there becomes the returned status code; anything else becomes
20
+ ``BadInternalError``.
21
+
22
+ Two kinds of failure are told apart. A transport failure means the call did not happen: no server
23
+ on the path gives ``BadNotConnected``, a server that took the request and went quiet gives
24
+ ``BadTimeout``. This is the one place where the UA layer translates an error itself, because a
25
+ missing service server reported as an internal error would blame the wrong party. An application
26
+ failure (the service ran and refused) answers ``Good`` with the response in FinalResultData. A
27
+ declaration may name the verdict field (``success_field``); a ``False`` in it answers
28
+ ``BadRequestNotAllowed`` with the response still written. No field is detected automatically,
29
+ since ROS2 has no standard success field; a wrong name fails at init.
30
+
31
+ FinalResultData and the Parameters are never reset, so FinalResultData holds the last response
32
+ that arrived; the status code is the verdict on the latest call. Post-call work goes into an
33
+ override of ``execute_method`` that calls ``super()`` first.
34
+
35
+ :func:`default_request_from` and :func:`default_response_to` are pure functions of a message and
36
+ its Projection context. A declaration may name its own pair; a replacement that needs the
37
+ instance overrides :meth:`ROS2ServiceMethod.build_request` or
38
+ :meth:`ROS2ServiceMethod.read_response`. The containers are built in
39
+ :mod:`opensmi.ros2.server.containers`.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ from typing import TYPE_CHECKING, ClassVar, Final
45
+
46
+ from asyncua import ua
47
+ from asyncua.ua.status_codes import StatusCodes
48
+ from opensmi.server import BaseMachineryItem, BaseMethod
49
+ from opensmi.server.mixins import FinalResultDataMixin, ParameterSetMixin, ParentMixin
50
+
51
+ from opensmi.ros2.runtime.errors import ServiceCallTimeoutError, ServiceUnavailableError
52
+ from opensmi.ros2.runtime.guard import require_sendable
53
+ from opensmi.ros2.runtime.messages import PrimitiveType
54
+ from opensmi.ros2.runtime.selection import SEPARATOR
55
+ from opensmi.ros2.server.access import SKILL_ACCESS_LEVEL
56
+ from opensmi.ros2.server.containers import ROS2ContainerMixin, VariableContainer
57
+ from opensmi.ros2.server.errors import SuccessFieldError
58
+ from opensmi.ros2.server.projection import narrowed, require_invertible, shaped
59
+
60
+ if TYPE_CHECKING:
61
+ from collections.abc import Mapping
62
+
63
+ from opensmi.ros2.runtime.interface import RuntimeInterface
64
+ from opensmi.ros2.runtime.messages import Message, ServiceTypes
65
+ from opensmi.ros2.server.bindings import MethodBinding
66
+ from opensmi.ros2.server.projection import ProjectionContext
67
+
68
+ __all__ = [
69
+ "REFUSED_BY_THE_SERVICE",
70
+ "TRANSPORT_STATUS",
71
+ "ROS2ServiceMethod",
72
+ "default_request_from",
73
+ "default_response_to",
74
+ ]
75
+
76
+ TRANSPORT_STATUS: Final[Mapping[type[Exception], int]] = {
77
+ ServiceUnavailableError: StatusCodes.BadNotConnected,
78
+ ServiceCallTimeoutError: StatusCodes.BadTimeout,
79
+ }
80
+ """The two ways a call does not happen, and the UA status code each becomes.
81
+
82
+ They differ for an operator: nothing serves the path, or something serves it and is stuck.
83
+ """
84
+
85
+
86
+ _TRANSPORT_FAILURES: Final = tuple(TRANSPORT_STATUS)
87
+ """What :meth:`ROS2ServiceMethod._call_the_service` catches, derived from the table."""
88
+
89
+
90
+ REFUSED_BY_THE_SERVICE: Final = StatusCodes.BadRequestNotAllowed
91
+ """What a Method answers when the field named by ``success_field`` came back ``False``.
92
+
93
+ ``BadInvalidState`` would assert why the service refused; only the service's own reason text,
94
+ which is in FinalResultData beside this code, can say that.
95
+ """
96
+
97
+
98
+ def default_request_from(
99
+ request_type: type[Message],
100
+ values: Mapping[str, object],
101
+ context: ProjectionContext,
102
+ ) -> Message:
103
+ """Build a request message out of what a client wrote into a Method's Parameters.
104
+
105
+ The Projection covering the request type, run backwards. A pure function: no server,
106
+ ``rclpy`` or event loop.
107
+
108
+ :raises NotInvertibleError: When a field of the request has no value, because the selection
109
+ removed it or no Parameter carries it. Such a field is refused instead of filled with a
110
+ default.
111
+ """
112
+ return context.registry.find(request_type.ros2.type_name).inverse_of(request_type, values, context)
113
+
114
+
115
+ def default_response_to(response: Message, context: ProjectionContext) -> Mapping[str, object]:
116
+ """Read a response message into the FinalResultData variables its type was shaped into."""
117
+ return context.registry.find(type(response).ros2.type_name).decode(response, context)
118
+
119
+
120
+ class ROS2ServiceMethod(
121
+ ROS2ContainerMixin,
122
+ ParentMixin[BaseMachineryItem],
123
+ FinalResultDataMixin,
124
+ ParameterSetMixin,
125
+ BaseMethod,
126
+ ):
127
+ """The Method one :class:`~opensmi.ros2.server.bindings.MethodBinding` becomes.
128
+
129
+ Constructed by the declaring Component. A declaration may name a subclass of this class to add
130
+ behaviour; the subclass is checked when the declaration is read.
131
+ """
132
+
133
+ callable_kind: ClassVar[str] = "Method"
134
+
135
+ def __init__(
136
+ self,
137
+ *,
138
+ binding: MethodBinding,
139
+ runtime: RuntimeInterface,
140
+ context: ProjectionContext,
141
+ minimum_access_level: int = SKILL_ACCESS_LEVEL,
142
+ ) -> None:
143
+ """Resolve everything about the declaration that can be wrong, before any node exists.
144
+
145
+ A missing interface package, a pattern that matches nothing, a request that cannot be
146
+ built backwards or a bad ``success_field`` fails here instead of on the first ``Call``.
147
+
148
+ :param binding: What to build.
149
+ :param runtime: Where the request is sent. The Machine's, reached through the Component.
150
+ :param context: The Projection context of the Component, with nothing selected yet. The
151
+ Method narrows it once per surface (request, response).
152
+ :param minimum_access_level: The level a caller needs.
153
+ :raises MessageTypeError: When the service type cannot be resolved.
154
+ :raises FieldSelectionError: When a selection pattern matches nothing.
155
+ :raises NotInvertibleError: When the request type reaches a Projection that cannot run
156
+ backwards.
157
+ :raises SuccessFieldError: When ``success_field`` names a field the response does not
158
+ have, or one that is not a ``bool``.
159
+ """
160
+ # A service call commands the robot as a Skill does, so it asks for the Skill level.
161
+ super().__init__(name=binding.name, minimum_access_level=minimum_access_level)
162
+ self._binding = binding
163
+ self._runtime = runtime
164
+ self._types: ServiceTypes = runtime.describe_service(binding.service_type)
165
+ self._request_context = narrowed(context, self._types.request, binding.selection)
166
+ self._response_context = narrowed(context, self._types.response, binding.response_selection)
167
+ require_invertible(self._types.request, self._request_context)
168
+ _require_a_bool_field(self._types.response, binding)
169
+ self._request_plan = shaped(self._types.request, self._request_context)
170
+ self._response_plan = shaped(self._types.response, self._response_context)
171
+ # opensmi's containers exist from first use; `_init` fills these records.
172
+ self._parameters = VariableContainer(name="ParameterSet", container=self.parameter_set)
173
+ self._results = VariableContainer(name="FinalResultData", container=self.final_result_data)
174
+
175
+ @property
176
+ def binding(self) -> MethodBinding:
177
+ """Return the declaration this Method was built from."""
178
+ return self._binding
179
+
180
+ @property
181
+ def service_types(self) -> ServiceTypes:
182
+ """Return the request and response types of the service this Method is bound to."""
183
+ return self._types
184
+
185
+ async def _init(self) -> None:
186
+ """Let opensmi register the Call, create the variables, and prove the defaults can be sent.
187
+
188
+ Building a request from the initial Parameters must work, so a value ROS2 would abort on
189
+ fails here, on the machine of whoever wrote the declaration.
190
+ """
191
+ await super()._init()
192
+ await self._create(self._request_plan, self._parameters, message_type=self._types.request, writable=True)
193
+ await self._create(self._response_plan, self._results, message_type=self._types.response)
194
+ require_sendable(await self.build_request(await self.read_parameters()))
195
+
196
+ async def read_parameters(self) -> Mapping[str, object]:
197
+ """Return what the ParameterSet holds now, by variable name."""
198
+ return await self._read_values(self._parameters)
199
+
200
+ async def read_results(self) -> Mapping[str, object]:
201
+ """Return what the FinalResultData holds now, by variable name."""
202
+ return await self._read_values(self._results)
203
+
204
+ async def build_request(self, values: Mapping[str, object]) -> Message:
205
+ """Return the request message to send, given what a client wrote into the Parameters.
206
+
207
+ Override on a custom class when building the request needs the instance. The declaration's
208
+ ``request_from`` is the pure-function form, and :func:`default_request_from` is the
209
+ default. An override must also work with the declaration's defaults, because ``_init``
210
+ calls it once with them. A Parameter a subclass adds after ``super()._init()`` does not
211
+ exist yet at that point, so an override reading it must tolerate its absence.
212
+ """
213
+ build = self._binding.request_from or default_request_from
214
+ return build(self._types.request, values, self._request_context)
215
+
216
+ async def read_response(self, response: Message) -> Mapping[str, object]:
217
+ """Return the FinalResultData values one response message carries, by variable name.
218
+
219
+ Overridable like :meth:`build_request`; the declaration's ``response_to`` is the
220
+ pure-function form and :func:`default_response_to` the default.
221
+ """
222
+ read = self._binding.response_to or default_response_to
223
+ return read(response, self._response_context)
224
+
225
+ async def execute_method(self) -> None:
226
+ """Call the service and write what answered.
227
+
228
+ opensmi's only hook, called after the access level, Lock and startup checks.
229
+
230
+ :raises UaStatusCodeError: The code :data:`TRANSPORT_STATUS` gives a transport failure,
231
+ or :data:`REFUSED_BY_THE_SERVICE` when the ``success_field`` came back ``False``
232
+ (after the response has been written).
233
+ """
234
+ request = await self.build_request(await self.read_parameters())
235
+ response = await self._call_the_service(request)
236
+ await self._write_values(self._results, await self.read_response(response))
237
+ self._require_the_service_agreed(response)
238
+
239
+ async def _call_the_service(self, request: Message) -> Message:
240
+ """Send one request, turning the two transport failures into UA status codes."""
241
+ try:
242
+ return await self._runtime.call_service(
243
+ service=self._binding.path,
244
+ service_type=self._types,
245
+ request=request,
246
+ server_timeout=self._binding.server_timeout,
247
+ call_timeout=self._binding.call_timeout,
248
+ )
249
+ except _TRANSPORT_FAILURES as error:
250
+ # Logged too: the status code says that the call did not happen, never which service.
251
+ self.logger.exception(
252
+ "The ROS2 service call did not happen",
253
+ binding=self._binding.name,
254
+ service=self._binding.path,
255
+ )
256
+ raise ua.UaStatusCodeError(_transport_status(error)) from error
257
+
258
+ def _require_the_service_agreed(self, response: Message) -> None:
259
+ """Refuse a call the service answered with no, if the declaration named the field.
260
+
261
+ Read off the response message, not FinalResultData, so a selection that hides the field
262
+ does not hide the refusal.
263
+
264
+ :raises UaStatusCodeError: When the named field came back ``False``.
265
+ """
266
+ named = self._binding.success_field
267
+ if named is None or getattr(response, named):
268
+ return
269
+ raise ua.UaStatusCodeError(REFUSED_BY_THE_SERVICE)
270
+
271
+
272
+ def _transport_status(error: Exception) -> int:
273
+ """Return the UA status code one transport failure becomes.
274
+
275
+ The fallback is unreachable today. It keeps an error class added later without a table entry
276
+ on opensmi's own answer instead of a ``StopIteration`` inside an exception handler.
277
+ """
278
+ return next(
279
+ (code for kind, code in TRANSPORT_STATUS.items() if isinstance(error, kind)), StatusCodes.BadInternalError
280
+ )
281
+
282
+
283
+ def _require_a_bool_field(response_type: type[Message], binding: MethodBinding) -> None:
284
+ """Refuse a ``success_field`` the response has no bool field for.
285
+
286
+ :raises SuccessFieldError: When the field is absent, or is present and is not a ``bool``.
287
+ """
288
+ named = binding.success_field
289
+ if named is None:
290
+ return
291
+ if SEPARATOR in named:
292
+ message = (
293
+ f"the Binding {binding.name!r} names {named!r} as the field carrying the verdict of "
294
+ f"{response_type.ros2.type_name}, and a verdict is read off a field of the response "
295
+ f"itself rather than down a path; name a top-level bool field"
296
+ )
297
+ raise SuccessFieldError(message)
298
+ described = next((each for each in response_type.ros2.fields if each.name == named), None)
299
+ if described is not None and described.field_type == PrimitiveType(name="bool"):
300
+ return
301
+ listed = ", ".join(each.name for each in response_type.ros2.fields) or "no fields at all"
302
+ found = "is not there" if described is None else f"is a {described.ros2_text}, not a bool"
303
+ message = (
304
+ f"the Binding {binding.name!r} names {named!r} as the field carrying the verdict of "
305
+ f"{response_type.ros2.type_name}, and it {found}; that response has: {listed}"
306
+ )
307
+ raise SuccessFieldError(message)