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.
- opensmi/ros2/__init__.py +89 -0
- opensmi/ros2/__main__.py +11 -0
- opensmi/ros2/cli.py +143 -0
- opensmi/ros2/py.typed +0 -0
- opensmi/ros2/runtime/__init__.py +67 -0
- opensmi/ros2/runtime/_decode.py +101 -0
- opensmi/ros2/runtime/_encode.py +102 -0
- opensmi/ros2/runtime/_parser.py +147 -0
- opensmi/ros2/runtime/errors.py +141 -0
- opensmi/ros2/runtime/goal.py +232 -0
- opensmi/ros2/runtime/graph.py +288 -0
- opensmi/ros2/runtime/guard.py +213 -0
- opensmi/ros2/runtime/interface.py +140 -0
- opensmi/ros2/runtime/messages/__init__.py +503 -0
- opensmi/ros2/runtime/messages/industrial_msgs.py +62 -0
- opensmi/ros2/runtime/messages/industrial_msgs.pyi +159 -0
- opensmi/ros2/runtime/messages/motoros2_interfaces.py +79 -0
- opensmi/ros2/runtime/messages/motoros2_interfaces.pyi +307 -0
- opensmi/ros2/runtime/messages/neo_msgs2.py +55 -0
- opensmi/ros2/runtime/messages/neo_msgs2.pyi +138 -0
- opensmi/ros2/runtime/messages/neo_srvs2.py +72 -0
- opensmi/ros2/runtime/messages/neo_srvs2.pyi +224 -0
- opensmi/ros2/runtime/outcomes.py +103 -0
- opensmi/ros2/runtime/parameters.py +723 -0
- opensmi/ros2/runtime/publisher.py +125 -0
- opensmi/ros2/runtime/qos.py +394 -0
- opensmi/ros2/runtime/runtime.py +1171 -0
- opensmi/ros2/runtime/selection.py +150 -0
- opensmi/ros2/runtime/stamp.py +100 -0
- opensmi/ros2/runtime/subscription.py +354 -0
- opensmi/ros2/runtime/tf.py +714 -0
- opensmi/ros2/server/__init__.py +148 -0
- opensmi/ros2/server/access.py +109 -0
- opensmi/ros2/server/bindings/__init__.py +92 -0
- opensmi/ros2/server/bindings/_base.py +154 -0
- opensmi/ros2/server/bindings/action.py +133 -0
- opensmi/ros2/server/bindings/keyed.py +127 -0
- opensmi/ros2/server/bindings/lifecycle.py +131 -0
- opensmi/ros2/server/bindings/method.py +130 -0
- opensmi/ros2/server/bindings/monitoring.py +109 -0
- opensmi/ros2/server/bindings/parameter.py +133 -0
- opensmi/ros2/server/bindings/publisher.py +192 -0
- opensmi/ros2/server/bindings/registry.py +95 -0
- opensmi/ros2/server/bindings/tf.py +256 -0
- opensmi/ros2/server/browse_names.py +94 -0
- opensmi/ros2/server/component.py +334 -0
- opensmi/ros2/server/config.py +493 -0
- opensmi/ros2/server/containers.py +191 -0
- opensmi/ros2/server/drivers.py +421 -0
- opensmi/ros2/server/errors.py +159 -0
- opensmi/ros2/server/events.py +406 -0
- opensmi/ros2/server/introspection.py +850 -0
- opensmi/ros2/server/keyed.py +749 -0
- opensmi/ros2/server/lifecycle.py +238 -0
- opensmi/ros2/server/limits.py +66 -0
- opensmi/ros2/server/loader.py +977 -0
- opensmi/ros2/server/machine.py +225 -0
- opensmi/ros2/server/method.py +307 -0
- opensmi/ros2/server/mirror.py +582 -0
- opensmi/ros2/server/mutation.py +992 -0
- opensmi/ros2/server/nodesets/Opc.Ua.SmartFactory.ROS2.NodeSet2.xml +85 -0
- opensmi/ros2/server/nodesets/__init__.py +18 -0
- opensmi/ros2/server/nodesets/smart_factory_ros2.py +26 -0
- opensmi/ros2/server/parameters.py +704 -0
- opensmi/ros2/server/projection.py +1176 -0
- opensmi/ros2/server/projections/__init__.py +41 -0
- opensmi/ros2/server/projections/scope.py +222 -0
- opensmi/ros2/server/provenance.py +121 -0
- opensmi/ros2/server/publisher.py +781 -0
- opensmi/ros2/server/recipes.py +514 -0
- opensmi/ros2/server/required.py +633 -0
- opensmi/ros2/server/skill.py +363 -0
- opensmi/ros2/server/spatial.py +283 -0
- opensmi/ros2/server/startup.py +626 -0
- opensmi/ros2/server/status.py +107 -0
- opensmi/ros2/server/structures.py +135 -0
- opensmi/ros2/server/transforms/__init__.py +39 -0
- opensmi/ros2/server/transforms/conversions.py +58 -0
- opensmi/ros2/server/transforms/filing.py +340 -0
- opensmi/ros2/server/transforms/mirror.py +462 -0
- opensmi/ros2/server/transforms/outward.py +180 -0
- opensmi/ros2/server/transforms/records.py +195 -0
- opensmi/ros2/server/transforms/spatial.py +154 -0
- opensmi_ros2-0.1.0.dist-info/METADATA +183 -0
- opensmi_ros2-0.1.0.dist-info/RECORD +89 -0
- opensmi_ros2-0.1.0.dist-info/WHEEL +5 -0
- opensmi_ros2-0.1.0.dist-info/entry_points.txt +2 -0
- opensmi_ros2-0.1.0.dist-info/licenses/LICENSES/MIT.txt +18 -0
- opensmi_ros2-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,977 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""Start a Machine from one TOML file, with no code of the deployer's.
|
|
6
|
+
|
|
7
|
+
.. code-block:: toml
|
|
8
|
+
|
|
9
|
+
[machine]
|
|
10
|
+
name = "Robot"
|
|
11
|
+
|
|
12
|
+
[machine.identification]
|
|
13
|
+
serial_number = "example-0001"
|
|
14
|
+
manufacturer = "Example Manufacturer"
|
|
15
|
+
product_instance_uri = "urn:example:opensmi-ros2:robot"
|
|
16
|
+
|
|
17
|
+
[ros2]
|
|
18
|
+
domain_id = 42
|
|
19
|
+
|
|
20
|
+
[[component]]
|
|
21
|
+
name = "Platform"
|
|
22
|
+
|
|
23
|
+
[[component.monitoring]]
|
|
24
|
+
name = "Odom"
|
|
25
|
+
path = "/odom"
|
|
26
|
+
message_type = "nav_msgs/msg/Odometry"
|
|
27
|
+
|
|
28
|
+
[[component]]
|
|
29
|
+
name = "Arm"
|
|
30
|
+
parent = "Platform"
|
|
31
|
+
|
|
32
|
+
The function :func:`load_machine` reads the file and returns a Machine ready for opensmi's
|
|
33
|
+
``Server.add_machine``.
|
|
34
|
+
|
|
35
|
+
The whole file is checked before anything is built. Every mistake is collected with the path to its
|
|
36
|
+
place (``component[1].monitoring[2].message_type``) and raised together as one
|
|
37
|
+
:class:`~opensmi.ros2.server.errors.FileDeclarationError`. The checks reuse the Binding declarations' own
|
|
38
|
+
validation and the loader of :mod:`opensmi.ros2.server.config`, so a new rule on a Binding applies to the
|
|
39
|
+
file at once. The Runtime comes from ``runtime_factory`` and is made only once the file has passed.
|
|
40
|
+
|
|
41
|
+
An optional ``[server] config = "server.toml"`` is resolved against the file's directory, must exist,
|
|
42
|
+
and is carried as ``ConfiguredMachine.server_config`` for the caller that builds the ``Server``, as
|
|
43
|
+
:mod:`opensmi.ros2.cli` does. Without it, opensmi's defaults apply.
|
|
44
|
+
|
|
45
|
+
A Component names its parent with ``parent`` (default: the Machine), and a parent comes before its
|
|
46
|
+
children in the file. A Binding file can be included with ``bindings_toml``.
|
|
47
|
+
|
|
48
|
+
``[[component.projection]]`` and ``[[machine.projection]]`` hold one Projection entry each: ``recipe``
|
|
49
|
+
(one of :data:`RECIPES`), ``type``, and the recipe's own parameters. The keys of a recipe are derived
|
|
50
|
+
from its dataclass, minus fields with no TOML spelling (callables) and minus the ``functions`` recipe,
|
|
51
|
+
which is only callables. Entries register through
|
|
52
|
+
:meth:`~opensmi.ros2.server.projection.ProjectionRegistry.extended` in the same layers as in Python
|
|
53
|
+
(Component, then Machine, then the shipped catalogue), so a second entry for one type is an error
|
|
54
|
+
unless it says ``override = true``. Every recipe takes ``override`` and ``type_hash``. ``scalar`` also
|
|
55
|
+
takes ``variant_type`` (a name such as ``Float``, or its number) and ``datatype`` (a namespace 0
|
|
56
|
+
DataType number), ``blob`` takes ``field`` and ``datatype``, ``enum`` takes ``fields`` (a table per
|
|
57
|
+
field name of number to label) and ``drop`` takes ``fields`` (a list of field paths):
|
|
58
|
+
|
|
59
|
+
.. code-block:: toml
|
|
60
|
+
|
|
61
|
+
[[component.projection]]
|
|
62
|
+
recipe = "drop"
|
|
63
|
+
type = "nav_msgs/msg/Odometry"
|
|
64
|
+
fields = ["pose/covariance", "twist/covariance"]
|
|
65
|
+
|
|
66
|
+
[[component.projection]]
|
|
67
|
+
recipe = "enum"
|
|
68
|
+
type = "sensor_msgs/msg/BatteryState"
|
|
69
|
+
|
|
70
|
+
[component.projection.fields.power_supply_status]
|
|
71
|
+
0 = "Unknown"
|
|
72
|
+
1 = "Charging"
|
|
73
|
+
|
|
74
|
+
[[component.projection]]
|
|
75
|
+
recipe = "scalar"
|
|
76
|
+
type = "std_msgs/msg/Float64"
|
|
77
|
+
variant_type = "Float"
|
|
78
|
+
|
|
79
|
+
A file may name the deployer's own classes by import path (``package.module.Name`` or
|
|
80
|
+
``package.module:Name``, the colon reaching a nested name): ``machine_class`` and ``component_class``,
|
|
81
|
+
``startup_skill_type``, ``driver_type`` inside a lifecycle table, and the callables of a projection
|
|
82
|
+
table (``recipe = "functions"``). Without a key the stock class applies. Importing runs that module's
|
|
83
|
+
code, so a machine file is trusted configuration. Nothing is imported until the whole file has passed
|
|
84
|
+
the structural checks. Import errors and classes of the wrong kind are reported at their key.
|
|
85
|
+
|
|
86
|
+
.. code-block:: toml
|
|
87
|
+
|
|
88
|
+
[machine]
|
|
89
|
+
name = "Robot"
|
|
90
|
+
machine_class = "my_robot.cell:Cell"
|
|
91
|
+
startup_skill_type = "my_robot.cell:CellStartup"
|
|
92
|
+
|
|
93
|
+
[[component]]
|
|
94
|
+
name = "Platform"
|
|
95
|
+
component_class = "my_robot.cell:Platform"
|
|
96
|
+
|
|
97
|
+
[[component.lifecycle]]
|
|
98
|
+
name = "Navigation"
|
|
99
|
+
path = "/lifecycle_manager"
|
|
100
|
+
driver_type = "my_robot.cell:NavigationDriver"
|
|
101
|
+
|
|
102
|
+
[[component.projection]]
|
|
103
|
+
recipe = "functions"
|
|
104
|
+
type = "my_msgs/msg/Pose"
|
|
105
|
+
shaped_by = "my_robot.curation:pose_shape"
|
|
106
|
+
decoded_by = "my_robot.curation:pose_decode"
|
|
107
|
+
encode = "my_robot.curation:pose_encode"
|
|
108
|
+
|
|
109
|
+
``machine_class`` must subclass :class:`ConfiguredMachine` and ``component_class``
|
|
110
|
+
:class:`ConfiguredComponent`; a class with its own ``__init__`` passes unknown keywords on to the base.
|
|
111
|
+
``startup_skill_type`` must subclass the stock StartupSkill (the lifecycle one on a Component with
|
|
112
|
+
lifecycle Bindings) and ``driver_type`` ``LifecycleDriver``. The ``functions`` recipe takes one key per
|
|
113
|
+
callable (``shaped_by``, ``decoded_by`` and the optional ``encode``); the ``encode`` of a ``blob`` is
|
|
114
|
+
named the same way.
|
|
115
|
+
|
|
116
|
+
Anything beyond Bindings, Projections, identification and these classes stays Python, such as
|
|
117
|
+
the Skill, Method or goal classes and the message functions of a Binding, and logic between declarations
|
|
118
|
+
(adding Components in a loop), which belongs in a ``machine_class``.
|
|
119
|
+
|
|
120
|
+
From Python:
|
|
121
|
+
|
|
122
|
+
.. code-block:: python
|
|
123
|
+
|
|
124
|
+
async with Server() as server:
|
|
125
|
+
await server.add_machine(load_machine("machine.toml"))
|
|
126
|
+
await server.start(blocking=True)
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
from __future__ import annotations
|
|
130
|
+
|
|
131
|
+
import importlib
|
|
132
|
+
import re
|
|
133
|
+
import tomllib
|
|
134
|
+
from dataclasses import MISSING, dataclass, field, fields, replace
|
|
135
|
+
from pathlib import Path
|
|
136
|
+
from typing import TYPE_CHECKING, Any, Final, NamedTuple, TypeVar
|
|
137
|
+
|
|
138
|
+
from asyncua import ua
|
|
139
|
+
from opensmi.server import BaseComponent, BaseMachine
|
|
140
|
+
|
|
141
|
+
from opensmi.ros2.server.bindings import TOML_KINDS, Binding, LifecycleBinding, load_bindings, resolve_bindings
|
|
142
|
+
from opensmi.ros2.server.component import ROS2ComponentMixin
|
|
143
|
+
from opensmi.ros2.server.config import (
|
|
144
|
+
FieldError,
|
|
145
|
+
ROS2Config,
|
|
146
|
+
TransformConfig,
|
|
147
|
+
declarable_keys,
|
|
148
|
+
from_dict,
|
|
149
|
+
python_keys,
|
|
150
|
+
)
|
|
151
|
+
from opensmi.ros2.server.drivers import LifecycleDriver
|
|
152
|
+
from opensmi.ros2.server.errors import DeclarationError, DuplicateProjectionError, FileDeclarationError
|
|
153
|
+
from opensmi.ros2.server.introspection import INTROSPECTION_NAME
|
|
154
|
+
from opensmi.ros2.server.machine import ROS2MachineMixin
|
|
155
|
+
from opensmi.ros2.server.projection import Projection, ProjectionRegistry
|
|
156
|
+
from opensmi.ros2.server.projections import DEFAULT_REGISTRY
|
|
157
|
+
from opensmi.ros2.server.recipes import Blob, Default, Drop, Enum, Functions, Scalar
|
|
158
|
+
from opensmi.ros2.server.required import ROS2StartupSkill
|
|
159
|
+
from opensmi.ros2.server.startup import ROS2LifecycleStartupSkill
|
|
160
|
+
|
|
161
|
+
if TYPE_CHECKING:
|
|
162
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
163
|
+
|
|
164
|
+
from opensmi.ros2.runtime.interface import RuntimeInterface
|
|
165
|
+
|
|
166
|
+
_T = TypeVar("_T")
|
|
167
|
+
|
|
168
|
+
__all__ = ["RECIPES", "ConfiguredComponent", "ConfiguredMachine", "Identification", "load_machine"]
|
|
169
|
+
|
|
170
|
+
_TOP_KEYS: Final = frozenset({"machine", "ros2", "server", "component"})
|
|
171
|
+
_MACHINE_KEYS: Final = frozenset({"name", "identification", "tf", "projection", "machine_class", "startup_skill_type"})
|
|
172
|
+
_COMPONENT_KEYS: Final = frozenset(
|
|
173
|
+
{
|
|
174
|
+
"name",
|
|
175
|
+
"parent",
|
|
176
|
+
"identification",
|
|
177
|
+
"bindings_toml",
|
|
178
|
+
"projection",
|
|
179
|
+
"component_class",
|
|
180
|
+
"startup_skill_type",
|
|
181
|
+
*TOML_KINDS,
|
|
182
|
+
}
|
|
183
|
+
)
|
|
184
|
+
_MACHINE_IDENTIFICATION: Final = ("serial_number", "manufacturer", "product_instance_uri")
|
|
185
|
+
_COMPONENT_IDENTIFICATION: Final = ("serial_number", "manufacturer")
|
|
186
|
+
"""A Component's identification block has no product URI; only a Machine's does."""
|
|
187
|
+
RECIPES: Final[Mapping[str, type[Projection]]] = {
|
|
188
|
+
"default": Default,
|
|
189
|
+
"scalar": Scalar,
|
|
190
|
+
"enum": Enum,
|
|
191
|
+
"blob": Blob,
|
|
192
|
+
"drop": Drop,
|
|
193
|
+
"functions": Functions,
|
|
194
|
+
}
|
|
195
|
+
"""The recipes a projection table can name. A test fails when a recipe of
|
|
196
|
+
:mod:`opensmi.ros2.server.recipes` is missing from it."""
|
|
197
|
+
_TYPE_KEY: Final = "type"
|
|
198
|
+
"""The key a table spells a recipe's ``type_name`` with."""
|
|
199
|
+
_PATH: Final = re.compile(r"[^\W\d]\w*(\.[^\W\d]\w*)*(:[^\W\d]\w*(\.[^\W\d]\w*)*)?")
|
|
200
|
+
"""An import path: dotted names, with an optional ``:`` before the attribute (which may be dotted)."""
|
|
201
|
+
_LOCALE: Final = "en-US"
|
|
202
|
+
"""The locale of the manufacturer's text; a file carries one string."""
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
206
|
+
class Identification:
|
|
207
|
+
"""The identification block of a Machine or Component, as a file gives it.
|
|
208
|
+
|
|
209
|
+
:ivar serial_number: The serial number, or ``None`` to leave it as opensmi has it.
|
|
210
|
+
:ivar manufacturer: The manufacturer's name, written with the locale ``en-US``.
|
|
211
|
+
:ivar product_instance_uri: The product instance URI.
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
serial_number: str | None = None
|
|
215
|
+
manufacturer: str | None = None
|
|
216
|
+
product_instance_uri: str | None = None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
async def _write_identification(item: Any, given: Identification) -> None:
|
|
220
|
+
"""Write what the file gave into the item's identification block."""
|
|
221
|
+
block = item.identification
|
|
222
|
+
if given.serial_number is not None:
|
|
223
|
+
await block.SerialNumber.write(given.serial_number)
|
|
224
|
+
if given.manufacturer is not None:
|
|
225
|
+
await block.Manufacturer.write(ua.LocalizedText(given.manufacturer, _LOCALE))
|
|
226
|
+
if given.product_instance_uri is not None:
|
|
227
|
+
await block.ProductInstanceUri.write(given.product_instance_uri)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class ConfiguredComponent(ROS2ComponentMixin, BaseComponent):
|
|
231
|
+
"""The stock Component a machine file declares: Bindings, identification and children.
|
|
232
|
+
|
|
233
|
+
Built by :func:`load_machine`, not by hand.
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
def __init__(
|
|
237
|
+
self,
|
|
238
|
+
*,
|
|
239
|
+
bindings: Sequence[Binding] = (),
|
|
240
|
+
identification: Identification | None = None,
|
|
241
|
+
children: Sequence[ConfiguredComponent] = (),
|
|
242
|
+
projections: Sequence[Projection] = (),
|
|
243
|
+
startup_skill_type: type[ROS2StartupSkill] | None = None,
|
|
244
|
+
**kwargs: Any,
|
|
245
|
+
) -> None:
|
|
246
|
+
"""Take the declarations this Component serves and the Components it contains.
|
|
247
|
+
|
|
248
|
+
A subclass named by ``component_class`` that defines ``__init__`` passes the keywords it does
|
|
249
|
+
not know on to this one.
|
|
250
|
+
|
|
251
|
+
:param bindings: Every Binding, inline and included, already resolved and unique by name.
|
|
252
|
+
:param projections: The Projections the file curates this Component's types with, ahead of
|
|
253
|
+
the Machine's.
|
|
254
|
+
:param identification: What to write into the identification block.
|
|
255
|
+
:param children: The Components registered under this one, in the order they start.
|
|
256
|
+
:param startup_skill_type: The StartupSkill class the file names, or ``None`` to leave the
|
|
257
|
+
class's own ``startup_skill_type`` as it is.
|
|
258
|
+
"""
|
|
259
|
+
super().__init__(**kwargs)
|
|
260
|
+
if startup_skill_type is not None:
|
|
261
|
+
self.startup_skill_type = startup_skill_type
|
|
262
|
+
self.bindings = tuple(bindings)
|
|
263
|
+
self.projections = tuple(projections)
|
|
264
|
+
self._given = identification or Identification()
|
|
265
|
+
self._children = tuple(children)
|
|
266
|
+
|
|
267
|
+
async def _write_identification(self) -> None:
|
|
268
|
+
await _write_identification(self, self._given)
|
|
269
|
+
|
|
270
|
+
async def _init(self) -> None:
|
|
271
|
+
"""Let the mixin build this Component, then register its children in file order."""
|
|
272
|
+
await super()._init()
|
|
273
|
+
for child in self._children:
|
|
274
|
+
await self.add_component(child)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class ConfiguredMachine(ROS2MachineMixin, BaseMachine):
|
|
278
|
+
"""The stock Machine a machine file declares: identification, TF Bindings and Components."""
|
|
279
|
+
|
|
280
|
+
def __init__(
|
|
281
|
+
self,
|
|
282
|
+
*,
|
|
283
|
+
identification: Identification,
|
|
284
|
+
components: Sequence[ConfiguredComponent] = (),
|
|
285
|
+
bindings: Sequence[Binding] = (),
|
|
286
|
+
projections: Sequence[Projection] = (),
|
|
287
|
+
server_config: Path | None = None,
|
|
288
|
+
startup_skill_type: type[ROS2StartupSkill] | None = None,
|
|
289
|
+
**kwargs: Any,
|
|
290
|
+
) -> None:
|
|
291
|
+
"""Take the identification, the top-level Components and the Machine's own TF Bindings.
|
|
292
|
+
|
|
293
|
+
A subclass named by ``machine_class`` that defines ``__init__`` passes the keywords it does
|
|
294
|
+
not know on to this one.
|
|
295
|
+
|
|
296
|
+
:param startup_skill_type: The StartupSkill class the file names, or ``None`` to leave the
|
|
297
|
+
class's own ``startup_skill_type`` as it is.
|
|
298
|
+
|
|
299
|
+
:param server_config: The opensmi server configuration the file points at, as an absolute
|
|
300
|
+
path, or ``None`` when it names none. The Machine only carries it; the caller that
|
|
301
|
+
builds the ``Server`` decides whether to use it.
|
|
302
|
+
"""
|
|
303
|
+
super().__init__(**kwargs)
|
|
304
|
+
if startup_skill_type is not None:
|
|
305
|
+
self.startup_skill_type = startup_skill_type
|
|
306
|
+
self.server_config = server_config
|
|
307
|
+
self.bindings = tuple(bindings)
|
|
308
|
+
self.projections = tuple(projections)
|
|
309
|
+
self._given = identification
|
|
310
|
+
self._top_level = tuple(components)
|
|
311
|
+
|
|
312
|
+
async def _write_identification(self) -> None:
|
|
313
|
+
await _write_identification(self, self._given)
|
|
314
|
+
|
|
315
|
+
async def _init(self) -> None:
|
|
316
|
+
"""Let the mixin build the Machine, then register its Components in file order."""
|
|
317
|
+
await super()._init()
|
|
318
|
+
for component in self._top_level:
|
|
319
|
+
await self.add_component(component)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@dataclass(slots=True)
|
|
323
|
+
class _Spec:
|
|
324
|
+
"""One Component as the file declares it, before anything is built."""
|
|
325
|
+
|
|
326
|
+
name: str
|
|
327
|
+
parent: str | None
|
|
328
|
+
identification: Identification
|
|
329
|
+
bindings: tuple[Binding, ...]
|
|
330
|
+
projections: tuple[Projection, ...]
|
|
331
|
+
component_class: _Ref | None = None
|
|
332
|
+
startup_skill_type: _Ref | None = None
|
|
333
|
+
children: list[_Spec] = field(default_factory=list)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@dataclass(slots=True)
|
|
337
|
+
class _Model:
|
|
338
|
+
"""A file that has passed every check."""
|
|
339
|
+
|
|
340
|
+
name: str
|
|
341
|
+
identification: Identification
|
|
342
|
+
bindings: tuple[Binding, ...]
|
|
343
|
+
projections: tuple[Projection, ...]
|
|
344
|
+
ros2: ROS2Config
|
|
345
|
+
server_config: Path | None
|
|
346
|
+
roots: list[_Spec]
|
|
347
|
+
machine_class: _Ref | None
|
|
348
|
+
startup_skill_type: _Ref | None
|
|
349
|
+
swaps: dict[int, Any]
|
|
350
|
+
"""What replaces each stand-in declaration (by ``id``) once its classes and callables are imported."""
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
@dataclass(slots=True)
|
|
354
|
+
class _Ref:
|
|
355
|
+
"""A class or callable the file names by import path, resolved only after the structure passed."""
|
|
356
|
+
|
|
357
|
+
path: str
|
|
358
|
+
"""Where the file names it, such as ``component[1].component_class``."""
|
|
359
|
+
text: str
|
|
360
|
+
complaint: Callable[[Any], str | None]
|
|
361
|
+
"""Returns what is wrong with the imported object, or ``None`` when it will do."""
|
|
362
|
+
value: Any = None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
@dataclass(slots=True)
|
|
366
|
+
class _Swap:
|
|
367
|
+
"""A frozen declaration built with stand-ins, rebuilt with the imported objects.
|
|
368
|
+
|
|
369
|
+
The stand-in takes part in the structural checks without needing the import.
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
stand_in: Any
|
|
373
|
+
refs: dict[str, _Ref]
|
|
374
|
+
path: str
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class _Problems:
|
|
378
|
+
"""The mistakes found so far, in the order the file reaches them, and what waits for an import."""
|
|
379
|
+
|
|
380
|
+
def __init__(self) -> None:
|
|
381
|
+
self.found: list[tuple[str, str]] = []
|
|
382
|
+
self.refs: list[_Ref] = []
|
|
383
|
+
self.swaps: list[_Swap] = []
|
|
384
|
+
|
|
385
|
+
def add(self, path: str, message: str) -> None:
|
|
386
|
+
self.found.append((path, message))
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _join(path: str, key: str | int) -> str:
|
|
390
|
+
if isinstance(key, int):
|
|
391
|
+
return f"{path}[{key}]"
|
|
392
|
+
return f"{path}.{key}" if path else key
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _table(value: Any, path: str, problems: _Problems) -> dict[str, Any] | None:
|
|
396
|
+
"""Return the value if it is a table, else report it at the path."""
|
|
397
|
+
if isinstance(value, dict):
|
|
398
|
+
return value
|
|
399
|
+
problems.add(path, f"expected a table, got {type(value).__name__}")
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _check_keys(table: Mapping[str, Any], allowed: Iterable[str], path: str, problems: _Problems) -> None:
|
|
404
|
+
"""Report each key the table has that the model does not know, at the key."""
|
|
405
|
+
known = sorted(allowed)
|
|
406
|
+
for key in table:
|
|
407
|
+
if key not in known:
|
|
408
|
+
problems.add(_join(path, key), f"unknown key; this table takes: {', '.join(known)}")
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _string(table: Mapping[str, Any], key: str, path: str, problems: _Problems) -> str | None:
|
|
412
|
+
"""Return a non-empty string value, or report a wrong one at its path (an absent key is silent)."""
|
|
413
|
+
value = table.get(key)
|
|
414
|
+
if isinstance(value, str) and value:
|
|
415
|
+
return value
|
|
416
|
+
if key in table:
|
|
417
|
+
problems.add(_join(path, key), f"expected a non-empty string, got {value!r}")
|
|
418
|
+
return None
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _reference(
|
|
422
|
+
table: Mapping[str, Any], key: str, path: str, problems: _Problems, complaint: Callable[[Any], str | None]
|
|
423
|
+
) -> _Ref | None:
|
|
424
|
+
"""Read a key that names a class or callable by import path, checking only its shape."""
|
|
425
|
+
text = _string(table, key, path, problems)
|
|
426
|
+
if text is None:
|
|
427
|
+
return None
|
|
428
|
+
here = _join(path, key)
|
|
429
|
+
if _PATH.fullmatch(text) is None or (":" not in text and "." not in text):
|
|
430
|
+
problems.add(here, f"{text!r} is not an import path; write package.module.Name or package.module:Name")
|
|
431
|
+
return None
|
|
432
|
+
ref = _Ref(here, text, complaint)
|
|
433
|
+
problems.refs.append(ref)
|
|
434
|
+
return ref
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _subclass_of(base: type, why: str) -> Callable[[Any], str | None]:
|
|
438
|
+
"""Return the check that an imported object is a class derived from ``base``."""
|
|
439
|
+
|
|
440
|
+
def complaint(value: Any) -> str | None:
|
|
441
|
+
if isinstance(value, type) and issubclass(value, base):
|
|
442
|
+
return None
|
|
443
|
+
shown = getattr(value, "__name__", repr(value))
|
|
444
|
+
return f"{shown} is not a subclass of {base.__name__}; {why}"
|
|
445
|
+
|
|
446
|
+
return complaint
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _callable(value: Any) -> str | None:
|
|
450
|
+
"""Return what is wrong with an imported object that has to be called, if anything."""
|
|
451
|
+
return None if callable(value) else f"{value!r} is not callable"
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _import(text: str) -> Any:
|
|
455
|
+
"""Import the object an import path names.
|
|
456
|
+
|
|
457
|
+
:raises LookupError: With what went wrong, when the module does not import or lacks the attribute.
|
|
458
|
+
"""
|
|
459
|
+
module_name, _, attribute = text.partition(":")
|
|
460
|
+
if not attribute:
|
|
461
|
+
module_name, _, attribute = text.rpartition(".")
|
|
462
|
+
try:
|
|
463
|
+
found = importlib.import_module(module_name)
|
|
464
|
+
except Exception as error: # the file names arbitrary code; whatever it raises is a mistake of the file
|
|
465
|
+
message = f"cannot import module {module_name!r}: {type(error).__name__}: {error}"
|
|
466
|
+
raise LookupError(message) from error
|
|
467
|
+
for part in attribute.split("."):
|
|
468
|
+
try:
|
|
469
|
+
found = getattr(found, part)
|
|
470
|
+
except AttributeError as error:
|
|
471
|
+
message = f"module {module_name!r} has no attribute {attribute!r}"
|
|
472
|
+
raise LookupError(message) from error
|
|
473
|
+
return found
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _resolve(problems: _Problems) -> dict[int, Any]:
|
|
477
|
+
"""Import everything the file names, report what fails, and rebuild the stand-in declarations.
|
|
478
|
+
|
|
479
|
+
:return: The real declaration for each stand-in, by the stand-in's ``id``.
|
|
480
|
+
"""
|
|
481
|
+
for ref in problems.refs:
|
|
482
|
+
try:
|
|
483
|
+
value = _import(ref.text)
|
|
484
|
+
except LookupError as error:
|
|
485
|
+
problems.add(ref.path, str(error))
|
|
486
|
+
continue
|
|
487
|
+
complaint = ref.complaint(value)
|
|
488
|
+
if complaint is not None:
|
|
489
|
+
problems.add(ref.path, complaint)
|
|
490
|
+
continue
|
|
491
|
+
ref.value = value
|
|
492
|
+
real: dict[int, Any] = {}
|
|
493
|
+
for swap in problems.swaps:
|
|
494
|
+
if any(each.value is None for each in swap.refs.values()):
|
|
495
|
+
continue
|
|
496
|
+
try:
|
|
497
|
+
real[id(swap.stand_in)] = replace(swap.stand_in, **{key: each.value for key, each in swap.refs.items()})
|
|
498
|
+
except (DeclarationError, ValueError, TypeError) as error:
|
|
499
|
+
problems.add(swap.path, str(error))
|
|
500
|
+
return real
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _identification(raw: Any, path: str, problems: _Problems, *, machine: bool) -> Identification:
|
|
504
|
+
"""Read an identification table. opensmi refuses to start an item that leaves an entry empty."""
|
|
505
|
+
keys = _MACHINE_IDENTIFICATION if machine else _COMPONENT_IDENTIFICATION
|
|
506
|
+
table = _table(raw if raw is not None else {}, path, problems)
|
|
507
|
+
if table is None:
|
|
508
|
+
return Identification()
|
|
509
|
+
_check_keys(table, keys, path, problems)
|
|
510
|
+
values = {key: _string(table, key, path, problems) for key in keys}
|
|
511
|
+
for key in keys:
|
|
512
|
+
if key not in table:
|
|
513
|
+
problems.add(_join(path, key), "missing; opensmi needs it to start")
|
|
514
|
+
return Identification(**values)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _declare(kind: type[Any], entry: Any, path: str, problems: _Problems) -> Binding | None:
|
|
518
|
+
"""Build one Binding from its table through the declaration's own checks."""
|
|
519
|
+
table = _table(entry, path, problems)
|
|
520
|
+
if table is None:
|
|
521
|
+
return None
|
|
522
|
+
driver: _Ref | None = None
|
|
523
|
+
if kind is LifecycleBinding and "driver_type" in table:
|
|
524
|
+
driver = _reference(
|
|
525
|
+
table,
|
|
526
|
+
"driver_type",
|
|
527
|
+
path,
|
|
528
|
+
problems,
|
|
529
|
+
_subclass_of(LifecycleDriver, "a Driver knows one coordinator flavour and holds no state machine"),
|
|
530
|
+
)
|
|
531
|
+
if driver is None:
|
|
532
|
+
return None
|
|
533
|
+
table = {key: value for key, value in table.items() if key != "driver_type"}
|
|
534
|
+
declared = [each.name for each in fields(kind)]
|
|
535
|
+
unknown = [key for key in table if key not in declared]
|
|
536
|
+
for key in unknown:
|
|
537
|
+
problems.add(_join(path, key), f"unknown key; {kind.__name__} takes: {', '.join(sorted(declared))}")
|
|
538
|
+
if unknown:
|
|
539
|
+
return None
|
|
540
|
+
try:
|
|
541
|
+
binding = from_dict(kind, table)
|
|
542
|
+
except FieldError as error:
|
|
543
|
+
problems.add(_join(path, error.field), error.reason)
|
|
544
|
+
return None
|
|
545
|
+
except (DeclarationError, ValueError, TypeError) as error:
|
|
546
|
+
problems.add(path, str(error))
|
|
547
|
+
return None
|
|
548
|
+
if driver is not None:
|
|
549
|
+
problems.swaps.append(_Swap(binding, {"driver": driver}, driver.path))
|
|
550
|
+
return binding
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def _declare_all(tables: Mapping[str, Any], kinds: Iterable[str], path: str, problems: _Problems) -> list[Binding]:
|
|
554
|
+
"""Build the Bindings the kind tables of one component or machine declare, in file order."""
|
|
555
|
+
wanted = set(kinds)
|
|
556
|
+
declared: list[Binding] = []
|
|
557
|
+
for name, entries in tables.items():
|
|
558
|
+
if name not in wanted:
|
|
559
|
+
continue
|
|
560
|
+
here = _join(path, name)
|
|
561
|
+
if not isinstance(entries, list):
|
|
562
|
+
problems.add(here, f"expected an array of tables, written [[{name}]] once per entry")
|
|
563
|
+
continue
|
|
564
|
+
for index, entry in enumerate(entries):
|
|
565
|
+
binding = _declare(TOML_KINDS[name], entry, _join(here, index), problems)
|
|
566
|
+
if binding is not None:
|
|
567
|
+
declared.append(binding)
|
|
568
|
+
return declared
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _unique(declared: list[Binding], path: str, problems: _Problems) -> tuple[Binding, ...]:
|
|
572
|
+
"""Check no two Bindings share a name, with the rule a Component applies at init."""
|
|
573
|
+
try:
|
|
574
|
+
return resolve_bindings(declared)
|
|
575
|
+
except DeclarationError as error:
|
|
576
|
+
problems.add(path, str(error))
|
|
577
|
+
return tuple(declared)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _recipe_keys(recipe: type[Projection]) -> tuple[str, ...]:
|
|
581
|
+
"""Return the keys a recipe's table takes; a callable field is spelled as an import path."""
|
|
582
|
+
keys = (*declarable_keys(recipe), *python_keys(recipe))
|
|
583
|
+
return tuple(_TYPE_KEY if key == "type_name" else key for key in keys)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _required_keys(recipe: type[Projection]) -> tuple[str, ...]:
|
|
587
|
+
"""Return the keys a recipe's table must carry: its fields that have no default."""
|
|
588
|
+
return tuple(
|
|
589
|
+
_TYPE_KEY if each.name == "type_name" else each.name
|
|
590
|
+
for each in fields(recipe)
|
|
591
|
+
if each.default is MISSING and each.default_factory is MISSING
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _recipe_table_fits(table: Mapping[str, Any], name: str, path: str, problems: _Problems) -> bool:
|
|
596
|
+
"""Report each key the recipe does not take and each it needs and lacks, and say whether none."""
|
|
597
|
+
recipe = RECIPES[name]
|
|
598
|
+
keys = _recipe_keys(recipe)
|
|
599
|
+
before = len(problems.found)
|
|
600
|
+
for key in table:
|
|
601
|
+
if key != "recipe" and key not in keys:
|
|
602
|
+
problems.add(_join(path, key), f"unknown key; the {name} recipe takes: recipe, {', '.join(sorted(keys))}")
|
|
603
|
+
for key in _required_keys(recipe):
|
|
604
|
+
if key not in table:
|
|
605
|
+
problems.add(_join(path, key), f"missing; the {name} recipe needs it")
|
|
606
|
+
return len(problems.found) == before
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _projection(raw: Any, path: str, problems: _Problems) -> Projection | None:
|
|
610
|
+
"""Build one Projection from its table, through the recipe's own dataclass."""
|
|
611
|
+
table = _table(raw, path, problems)
|
|
612
|
+
if table is None:
|
|
613
|
+
return None
|
|
614
|
+
name = table.get("recipe")
|
|
615
|
+
if name not in RECIPES:
|
|
616
|
+
known = ", ".join(sorted(RECIPES))
|
|
617
|
+
said = f"unknown recipe {name!r}" if "recipe" in table else "missing"
|
|
618
|
+
problems.add(_join(path, "recipe"), f"{said}; the recipes are: {known}")
|
|
619
|
+
return None
|
|
620
|
+
recipe = RECIPES[name]
|
|
621
|
+
if not _recipe_table_fits(table, name, path, problems) or _string(table, _TYPE_KEY, path, problems) is None:
|
|
622
|
+
return None
|
|
623
|
+
callables = {key: _reference(table, key, path, problems, _callable) for key in python_keys(recipe) if key in table}
|
|
624
|
+
if None in callables.values():
|
|
625
|
+
return None
|
|
626
|
+
given = {
|
|
627
|
+
("type_name" if key == _TYPE_KEY else key): value
|
|
628
|
+
for key, value in table.items()
|
|
629
|
+
if key != "recipe" and key not in callables
|
|
630
|
+
}
|
|
631
|
+
# The stand-in lets the entry be registered and checked for duplicates before the real callable is imported.
|
|
632
|
+
try:
|
|
633
|
+
projection = from_dict(recipe, given, supplied=dict.fromkeys(callables, _stand_in))
|
|
634
|
+
except FieldError as error:
|
|
635
|
+
key = _TYPE_KEY if error.field == "type_name" else error.field.replace("type_name", _TYPE_KEY, 1)
|
|
636
|
+
problems.add(_join(path, key), error.reason)
|
|
637
|
+
return None
|
|
638
|
+
except (DeclarationError, ValueError, TypeError) as error:
|
|
639
|
+
problems.add(path, str(error))
|
|
640
|
+
return None
|
|
641
|
+
refs = {key: ref for key, ref in callables.items() if ref is not None}
|
|
642
|
+
if refs:
|
|
643
|
+
problems.swaps.append(_Swap(projection, refs, path))
|
|
644
|
+
return projection
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _stand_in(*_args: object, **_kwargs: object) -> Any:
|
|
648
|
+
"""Stand for a callable a file names until it is imported."""
|
|
649
|
+
message = "a callable named in a machine file was used before it was imported"
|
|
650
|
+
raise RuntimeError(message)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _layered(
|
|
654
|
+
raw: Mapping[str, Any], path: str, below: ProjectionRegistry, problems: _Problems
|
|
655
|
+
) -> tuple[tuple[Projection, ...], ProjectionRegistry]:
|
|
656
|
+
"""Read the ``projection`` tables of a Machine or Component and register them over a registry.
|
|
657
|
+
|
|
658
|
+
:return: The entries that registered, and the registry they extend.
|
|
659
|
+
"""
|
|
660
|
+
entries = raw.get("projection")
|
|
661
|
+
if entries is None:
|
|
662
|
+
return (), below
|
|
663
|
+
here = _join(path, "projection")
|
|
664
|
+
if not isinstance(entries, list):
|
|
665
|
+
problems.add(here, "expected an array of tables, written [[projection]] once per entry")
|
|
666
|
+
return (), below
|
|
667
|
+
kept: list[Projection] = []
|
|
668
|
+
registry = below
|
|
669
|
+
for index, entry in enumerate(entries):
|
|
670
|
+
where = _join(here, index)
|
|
671
|
+
projection = _projection(entry, where, problems)
|
|
672
|
+
if projection is None:
|
|
673
|
+
continue
|
|
674
|
+
try:
|
|
675
|
+
registry = registry.extended([projection])
|
|
676
|
+
except DuplicateProjectionError as error:
|
|
677
|
+
problems.add(_join(where, _TYPE_KEY), str(error))
|
|
678
|
+
continue
|
|
679
|
+
kept.append(projection)
|
|
680
|
+
return tuple(kept), registry
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
class _MachineTable(NamedTuple):
|
|
684
|
+
"""What the ``[machine]`` table declares."""
|
|
685
|
+
|
|
686
|
+
name: str
|
|
687
|
+
identification: Identification
|
|
688
|
+
bindings: tuple[Binding, ...]
|
|
689
|
+
projections: tuple[Projection, ...]
|
|
690
|
+
registry: ProjectionRegistry
|
|
691
|
+
"""The shipped catalogue extended by the Machine's entries; Components register over it."""
|
|
692
|
+
machine_class: _Ref | None = None
|
|
693
|
+
startup_skill_type: _Ref | None = None
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _machine(raw: Any, problems: _Problems) -> _MachineTable:
|
|
697
|
+
"""Read the ``[machine]`` table."""
|
|
698
|
+
table = _table(raw, "machine", problems) if raw is not None else None
|
|
699
|
+
if table is None:
|
|
700
|
+
if raw is None:
|
|
701
|
+
problems.add("machine", "missing; a file declares the Machine it serves")
|
|
702
|
+
return _MachineTable("", Identification(), (), (), DEFAULT_REGISTRY)
|
|
703
|
+
_check_keys(table, _MACHINE_KEYS, "machine", problems)
|
|
704
|
+
name = _string(table, "name", "machine", problems)
|
|
705
|
+
if name is None and "name" not in table:
|
|
706
|
+
problems.add("machine.name", "missing; the Machine needs a name")
|
|
707
|
+
identification = _identification(table.get("identification"), "machine.identification", problems, machine=True)
|
|
708
|
+
bindings = _unique(_declare_all(table, ("tf",), "machine", problems), "machine", problems)
|
|
709
|
+
projections, registry = _layered(table, "machine", DEFAULT_REGISTRY, problems)
|
|
710
|
+
machine_class = _reference(
|
|
711
|
+
table,
|
|
712
|
+
"machine_class",
|
|
713
|
+
"machine",
|
|
714
|
+
problems,
|
|
715
|
+
_subclass_of(ConfiguredMachine, "it receives the file's declarations through ConfiguredMachine's constructor"),
|
|
716
|
+
)
|
|
717
|
+
skill = _reference(
|
|
718
|
+
table,
|
|
719
|
+
"startup_skill_type",
|
|
720
|
+
"machine",
|
|
721
|
+
problems,
|
|
722
|
+
_subclass_of(ROS2StartupSkill, "a custom class adds behaviour to the stock StartupSkill"),
|
|
723
|
+
)
|
|
724
|
+
return _MachineTable(name or "", identification, bindings, projections, registry, machine_class, skill)
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def _ros2(raw: Any, problems: _Problems) -> ROS2Config:
|
|
728
|
+
"""Read the ``[ros2]`` table into the settings the Runtime and the Machine share."""
|
|
729
|
+
table = _table(raw, "ros2", problems) if raw is not None else {}
|
|
730
|
+
if table is None:
|
|
731
|
+
return ROS2Config()
|
|
732
|
+
known = [each.name for each in fields(ROS2Config)]
|
|
733
|
+
_check_keys(table, known, "ros2", problems)
|
|
734
|
+
nested = table.get("transforms")
|
|
735
|
+
if isinstance(nested, dict):
|
|
736
|
+
_check_keys(nested, [each.name for each in fields(TransformConfig)], "ros2.transforms", problems)
|
|
737
|
+
if any(path.startswith("ros2") for path, _ in problems.found):
|
|
738
|
+
return ROS2Config()
|
|
739
|
+
try:
|
|
740
|
+
return from_dict(ROS2Config, table)
|
|
741
|
+
except FieldError as error:
|
|
742
|
+
problems.add(_join("ros2", error.field), error.reason)
|
|
743
|
+
except (DeclarationError, ValueError, TypeError) as error:
|
|
744
|
+
problems.add("ros2", str(error))
|
|
745
|
+
return ROS2Config()
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _server(raw: Any, base: Path, problems: _Problems) -> Path | None:
|
|
749
|
+
"""Read the ``[server]`` table: the opensmi server configuration the file points at, which must exist."""
|
|
750
|
+
if raw is None:
|
|
751
|
+
return None
|
|
752
|
+
table = _table(raw, "server", problems)
|
|
753
|
+
if table is None:
|
|
754
|
+
return None
|
|
755
|
+
_check_keys(table, ("config",), "server", problems)
|
|
756
|
+
given = _string(table, "config", "server", problems)
|
|
757
|
+
if given is None:
|
|
758
|
+
return None
|
|
759
|
+
resolved = base / given
|
|
760
|
+
if not resolved.is_file():
|
|
761
|
+
problems.add("server.config", f"{given!r} is not a file (looked for {str(resolved)!r})")
|
|
762
|
+
return None
|
|
763
|
+
return resolved.resolve()
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def _component(index: int, raw: Any, base: Path, machine: ProjectionRegistry, problems: _Problems) -> _Spec | None:
|
|
767
|
+
"""Read one ``[[component]]`` table. Where it sits in the tree is decided afterwards."""
|
|
768
|
+
path = _join("component", index)
|
|
769
|
+
table = _table(raw, path, problems)
|
|
770
|
+
if table is None:
|
|
771
|
+
return None
|
|
772
|
+
_check_keys(table, _COMPONENT_KEYS, path, problems)
|
|
773
|
+
name = _string(table, "name", path, problems)
|
|
774
|
+
if name is None and "name" not in table:
|
|
775
|
+
problems.add(_join(path, "name"), "missing; every Component needs a name")
|
|
776
|
+
parent = _string(table, "parent", path, problems)
|
|
777
|
+
identification = _identification(
|
|
778
|
+
table.get("identification"), _join(path, "identification"), problems, machine=False
|
|
779
|
+
)
|
|
780
|
+
declared = _declare_all(table, TOML_KINDS, path, problems)
|
|
781
|
+
declared.extend(_include(table, path, base, problems))
|
|
782
|
+
bindings = _unique(declared, path, problems)
|
|
783
|
+
projections, _ = _layered(table, path, machine, problems)
|
|
784
|
+
component_class = _reference(
|
|
785
|
+
table,
|
|
786
|
+
"component_class",
|
|
787
|
+
path,
|
|
788
|
+
problems,
|
|
789
|
+
_subclass_of(
|
|
790
|
+
ConfiguredComponent, "it receives the file's declarations through ConfiguredComponent's constructor"
|
|
791
|
+
),
|
|
792
|
+
)
|
|
793
|
+
stock = (
|
|
794
|
+
ROS2LifecycleStartupSkill if any(isinstance(each, LifecycleBinding) for each in bindings) else ROS2StartupSkill
|
|
795
|
+
)
|
|
796
|
+
skill = _reference(
|
|
797
|
+
table,
|
|
798
|
+
"startup_skill_type",
|
|
799
|
+
path,
|
|
800
|
+
problems,
|
|
801
|
+
_subclass_of(stock, "a custom class adds behaviour to the stock StartupSkill its Bindings ask for"),
|
|
802
|
+
)
|
|
803
|
+
if name is None:
|
|
804
|
+
return None
|
|
805
|
+
return _Spec(
|
|
806
|
+
name=name,
|
|
807
|
+
parent=parent,
|
|
808
|
+
identification=identification,
|
|
809
|
+
bindings=bindings,
|
|
810
|
+
projections=projections,
|
|
811
|
+
component_class=component_class,
|
|
812
|
+
startup_skill_type=skill,
|
|
813
|
+
)
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def _include(table: Mapping[str, Any], path: str, base: Path, problems: _Problems) -> list[Binding]:
|
|
817
|
+
"""Read the Binding file a component includes, relative to the machine file."""
|
|
818
|
+
given = _string(table, "bindings_toml", path, problems)
|
|
819
|
+
if given is None:
|
|
820
|
+
return []
|
|
821
|
+
here = _join(path, "bindings_toml")
|
|
822
|
+
try:
|
|
823
|
+
return list(load_bindings(base / given))
|
|
824
|
+
except OSError as error:
|
|
825
|
+
problems.add(here, f"cannot read {given!r}: {error.strerror or error}")
|
|
826
|
+
except tomllib.TOMLDecodeError as error:
|
|
827
|
+
problems.add(here, f"{given!r} is not valid TOML: {error}")
|
|
828
|
+
except (DeclarationError, ValueError, TypeError) as error: # includes FieldError
|
|
829
|
+
problems.add(here, f"{given!r}: {error}")
|
|
830
|
+
return []
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def _misplaced(spec: _Spec, index_of: Mapping[str, int]) -> str:
|
|
834
|
+
"""Say why a Component's parent is not a place it can go."""
|
|
835
|
+
if spec.parent == spec.name:
|
|
836
|
+
return "a Component cannot be its own parent"
|
|
837
|
+
if spec.parent is not None and spec.parent in index_of:
|
|
838
|
+
return (
|
|
839
|
+
f"{spec.parent!r} is declared after its child (component[{index_of[spec.parent]}]); "
|
|
840
|
+
f"a parent comes before the Components under it"
|
|
841
|
+
)
|
|
842
|
+
return f"{spec.parent!r} is not a Component of this file; leave parent out to put it under the Machine"
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _arrange(specs: list[_Spec | None], problems: _Problems) -> list[_Spec]:
|
|
846
|
+
"""Place each Component under its parent, or report why it cannot be."""
|
|
847
|
+
index_of: dict[str, int] = {}
|
|
848
|
+
for index, spec in enumerate(specs):
|
|
849
|
+
if spec is not None:
|
|
850
|
+
index_of.setdefault(spec.name, index)
|
|
851
|
+
placed: dict[str, _Spec] = {}
|
|
852
|
+
refused: set[str] = set()
|
|
853
|
+
roots: list[_Spec] = []
|
|
854
|
+
for index, spec in enumerate(specs):
|
|
855
|
+
if spec is None:
|
|
856
|
+
continue
|
|
857
|
+
path = _join("component", index)
|
|
858
|
+
if spec.name == INTROSPECTION_NAME:
|
|
859
|
+
problems.add(
|
|
860
|
+
_join(path, "name"), f"{INTROSPECTION_NAME!r} is the introspection Component every Machine carries"
|
|
861
|
+
)
|
|
862
|
+
refused.add(spec.name)
|
|
863
|
+
continue
|
|
864
|
+
if index_of[spec.name] != index:
|
|
865
|
+
problems.add(_join(path, "name"), f"{spec.name!r} is already the name of component[{index_of[spec.name]}]")
|
|
866
|
+
continue
|
|
867
|
+
placed[spec.name] = spec
|
|
868
|
+
if spec.parent is None:
|
|
869
|
+
roots.append(spec)
|
|
870
|
+
continue
|
|
871
|
+
if spec.parent in refused:
|
|
872
|
+
continue # the mistake is the parent's, already reported
|
|
873
|
+
if spec.parent in placed and spec.parent != spec.name:
|
|
874
|
+
placed[spec.parent].children.append(spec)
|
|
875
|
+
else:
|
|
876
|
+
problems.add(_join(path, "parent"), _misplaced(spec, index_of))
|
|
877
|
+
return roots
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def _validate(source: Path) -> _Model:
|
|
881
|
+
"""Read and check the whole file, and raise every mistake in it at once."""
|
|
882
|
+
problems = _Problems()
|
|
883
|
+
try:
|
|
884
|
+
with source.open("rb") as handle:
|
|
885
|
+
data = tomllib.load(handle)
|
|
886
|
+
except tomllib.TOMLDecodeError as error:
|
|
887
|
+
raise FileDeclarationError([("", f"not valid TOML: {error}")], source=str(source)) from error
|
|
888
|
+
_check_keys(data, _TOP_KEYS, "", problems)
|
|
889
|
+
machine = _machine(data.get("machine"), problems)
|
|
890
|
+
ros2 = _ros2(data.get("ros2"), problems)
|
|
891
|
+
server_config = _server(data.get("server"), source.parent, problems)
|
|
892
|
+
raw = data.get("component", [])
|
|
893
|
+
roots: list[_Spec] = []
|
|
894
|
+
if isinstance(raw, list):
|
|
895
|
+
specs = [_component(index, each, source.parent, machine.registry, problems) for index, each in enumerate(raw)]
|
|
896
|
+
roots = _arrange(specs, problems)
|
|
897
|
+
else:
|
|
898
|
+
problems.add("component", "expected an array of tables, written [[component]]")
|
|
899
|
+
if problems.found:
|
|
900
|
+
raise FileDeclarationError(problems.found, source=str(source))
|
|
901
|
+
swaps = _resolve(problems)
|
|
902
|
+
if problems.found:
|
|
903
|
+
raise FileDeclarationError(problems.found, source=str(source))
|
|
904
|
+
return _Model(
|
|
905
|
+
name=machine.name,
|
|
906
|
+
identification=machine.identification,
|
|
907
|
+
bindings=machine.bindings,
|
|
908
|
+
projections=machine.projections,
|
|
909
|
+
ros2=ros2,
|
|
910
|
+
server_config=server_config,
|
|
911
|
+
roots=roots,
|
|
912
|
+
machine_class=machine.machine_class,
|
|
913
|
+
startup_skill_type=machine.startup_skill_type,
|
|
914
|
+
swaps=swaps,
|
|
915
|
+
)
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
def _swapped(items: Iterable[_T], swaps: Mapping[int, Any]) -> tuple[_T, ...]:
|
|
919
|
+
"""Replace each stand-in declaration by its real one."""
|
|
920
|
+
return tuple(swaps.get(id(each), each) for each in items)
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def _build(spec: _Spec, swaps: Mapping[int, Any]) -> ConfiguredComponent:
|
|
924
|
+
"""Construct a Component with its children, which are constructed first."""
|
|
925
|
+
component_class = spec.component_class.value if spec.component_class is not None else ConfiguredComponent
|
|
926
|
+
return component_class(
|
|
927
|
+
name=spec.name,
|
|
928
|
+
bindings=_swapped(spec.bindings, swaps),
|
|
929
|
+
projections=_swapped(spec.projections, swaps),
|
|
930
|
+
identification=spec.identification,
|
|
931
|
+
children=[_build(each, swaps) for each in spec.children],
|
|
932
|
+
startup_skill_type=spec.startup_skill_type.value if spec.startup_skill_type is not None else None,
|
|
933
|
+
)
|
|
934
|
+
|
|
935
|
+
|
|
936
|
+
def _real_runtime(config: ROS2Config) -> RuntimeInterface:
|
|
937
|
+
"""Build the real Runtime. Imported here, as ``rclpy`` is needed to import it."""
|
|
938
|
+
from opensmi.ros2.runtime import Runtime
|
|
939
|
+
|
|
940
|
+
return Runtime(
|
|
941
|
+
domain_id=config.domain_id,
|
|
942
|
+
node_name=config.node_name,
|
|
943
|
+
namespace=config.namespace,
|
|
944
|
+
stop_timeout=config.stop_timeout,
|
|
945
|
+
)
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def load_machine(
|
|
949
|
+
path: str | Path,
|
|
950
|
+
*,
|
|
951
|
+
runtime_factory: Callable[[ROS2Config], RuntimeInterface] | None = None,
|
|
952
|
+
) -> ConfiguredMachine:
|
|
953
|
+
"""Read a machine file and return the Machine it declares, ready for ``Server.add_machine``.
|
|
954
|
+
|
|
955
|
+
:param path: The TOML file. A relative ``bindings_toml`` or ``[server] config`` in it is
|
|
956
|
+
relative to this file.
|
|
957
|
+
:param runtime_factory: How to make the Runtime from the file's ``[ros2]`` settings, called
|
|
958
|
+
once and only after the file has passed. ``None`` builds the real Runtime, which needs
|
|
959
|
+
``rclpy``; a test passes a function returning its fake.
|
|
960
|
+
:raises FileDeclarationError: When the file has any mistake, with all of them and the path to
|
|
961
|
+
each. Nothing has been constructed by then.
|
|
962
|
+
:raises OSError: When the file cannot be read.
|
|
963
|
+
"""
|
|
964
|
+
model = _validate(Path(path))
|
|
965
|
+
runtime = (runtime_factory or _real_runtime)(model.ros2)
|
|
966
|
+
machine_class = model.machine_class.value if model.machine_class is not None else ConfiguredMachine
|
|
967
|
+
return machine_class(
|
|
968
|
+
name=model.name,
|
|
969
|
+
runtime=runtime,
|
|
970
|
+
ros2_config=model.ros2,
|
|
971
|
+
identification=model.identification,
|
|
972
|
+
bindings=model.bindings,
|
|
973
|
+
projections=_swapped(model.projections, model.swaps),
|
|
974
|
+
components=[_build(each, model.swaps) for each in model.roots],
|
|
975
|
+
server_config=model.server_config,
|
|
976
|
+
startup_skill_type=model.startup_skill_type.value if model.startup_skill_type is not None else None,
|
|
977
|
+
)
|