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,1176 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""The Projection engine: how one ROS2 type is rendered in OPC UA.
|
|
6
|
+
|
|
7
|
+
A Binding connects one ROS2 path to one OPC UA object. A Projection is about the type of what flows
|
|
8
|
+
through it, is reused by every Binding whose messages carry that type, and applies wherever the type
|
|
9
|
+
appears, at the root of a message or nested inside another. It has three pure functions:
|
|
10
|
+
|
|
11
|
+
* shape, run once at init, turns a message dataclass into a node plan of :class:`PlanObject` and
|
|
12
|
+
:class:`PlanVariable`. The generic walk emits only variables, which nest as complex
|
|
13
|
+
Variables; a repeated message becomes one variable holding an array of a structure derived from
|
|
14
|
+
its type, and a plan that asks for an Object is refused where its nodes are made.
|
|
15
|
+
* decode, run per message, turns a payload into a map from plan name to value.
|
|
16
|
+
* encode, run per write on the publishing side, turns that map back into a payload. An entry that
|
|
17
|
+
cannot run backwards has no :attr:`Projection.inverse`. That is derived from the recipe
|
|
18
|
+
and asked as :meth:`Projection.inverts`, of a type, because for some recipes it
|
|
19
|
+
depends on the message too.
|
|
20
|
+
|
|
21
|
+
The generic field-walk is an ordinary registry entry that matches last, so turning curation off for
|
|
22
|
+
one type means naming the generic entry for it. Authors write recipes
|
|
23
|
+
(:mod:`opensmi.ros2.server.recipes`), not these functions. No step sees an ``rclpy`` object.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from abc import ABC, abstractmethod
|
|
29
|
+
from collections.abc import Mapping
|
|
30
|
+
from dataclasses import dataclass, field, replace
|
|
31
|
+
from typing import TYPE_CHECKING, Any, Final, TypeAlias, cast
|
|
32
|
+
|
|
33
|
+
from asyncua import ua
|
|
34
|
+
from asyncua.ua.object_ids import ObjectIds
|
|
35
|
+
from opensmi.core.ua import NodeIdDefinition
|
|
36
|
+
|
|
37
|
+
from opensmi.ros2.runtime.guard import INTEGER_RANGES
|
|
38
|
+
from opensmi.ros2.runtime.messages import (
|
|
39
|
+
ArrayType,
|
|
40
|
+
NestedType,
|
|
41
|
+
PrimitiveType,
|
|
42
|
+
SequenceType,
|
|
43
|
+
StringType,
|
|
44
|
+
element_of,
|
|
45
|
+
is_byte_container,
|
|
46
|
+
)
|
|
47
|
+
from opensmi.ros2.runtime.selection import SEPARATOR, field_paths, resolve_selection
|
|
48
|
+
from opensmi.ros2.server.browse_names import browse_name, browse_names
|
|
49
|
+
from opensmi.ros2.server.errors import (
|
|
50
|
+
DeclarationError,
|
|
51
|
+
DuplicateProjectionError,
|
|
52
|
+
NotInvertibleError,
|
|
53
|
+
UnprojectableFieldError,
|
|
54
|
+
)
|
|
55
|
+
from opensmi.ros2.server.structures import NAME_SEPARATOR, StructureField, structure_class, structure_instance
|
|
56
|
+
|
|
57
|
+
if TYPE_CHECKING:
|
|
58
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
59
|
+
|
|
60
|
+
from opensmi.ros2.runtime.messages import (
|
|
61
|
+
ElementType,
|
|
62
|
+
FieldDescription,
|
|
63
|
+
FieldType,
|
|
64
|
+
Message,
|
|
65
|
+
PrimitiveName,
|
|
66
|
+
)
|
|
67
|
+
from opensmi.ros2.runtime.selection import FieldSelection
|
|
68
|
+
|
|
69
|
+
__all__ = [
|
|
70
|
+
"ANY_TYPE",
|
|
71
|
+
"NAME_SEPARATOR",
|
|
72
|
+
"DecodeFunction",
|
|
73
|
+
"EncodeFunction",
|
|
74
|
+
"EnumDataType",
|
|
75
|
+
"NodeLevel",
|
|
76
|
+
"NodeLevelNaming",
|
|
77
|
+
"NodePath",
|
|
78
|
+
"PlanDataType",
|
|
79
|
+
"PlanEntry",
|
|
80
|
+
"PlanObject",
|
|
81
|
+
"PlanVariable",
|
|
82
|
+
"ProjectDataType",
|
|
83
|
+
"Projection",
|
|
84
|
+
"ProjectionContext",
|
|
85
|
+
"ProjectionRegistry",
|
|
86
|
+
"ShapeFunction",
|
|
87
|
+
"StandardDataType",
|
|
88
|
+
"browse_name_of",
|
|
89
|
+
"curated_naming",
|
|
90
|
+
"element_structure",
|
|
91
|
+
"flat_name",
|
|
92
|
+
"generic_decode",
|
|
93
|
+
"generic_encode",
|
|
94
|
+
"generic_shape",
|
|
95
|
+
"inner_levels",
|
|
96
|
+
"join_path",
|
|
97
|
+
"level_datatypes",
|
|
98
|
+
"level_value",
|
|
99
|
+
"message_class",
|
|
100
|
+
"narrowed",
|
|
101
|
+
"require_invertible",
|
|
102
|
+
"ros2_value",
|
|
103
|
+
"shaped",
|
|
104
|
+
"ua_shape",
|
|
105
|
+
"ua_value",
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
ANY_TYPE: Final = "*"
|
|
109
|
+
"""The type name of an entry that answers for every type; the generic walk carries it."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
NodePath: TypeAlias = tuple[str, ...]
|
|
113
|
+
"""The browse names from the top of a plan down to one node, such as ``("Pose", "Position", "X")``."""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def flat_name(*parts: str) -> str:
|
|
117
|
+
"""Return node path parts as the one name a plan entry has in the decode and encode maps.
|
|
118
|
+
|
|
119
|
+
Empty parts are skipped: an entry named ``""`` takes the name of whatever contains it, so a
|
|
120
|
+
message rendered as one variable browses as the field it sits in. The decode and encode maps
|
|
121
|
+
are keyed the same way, so this is the one place that spells that name. It is a key and not a
|
|
122
|
+
BrowseName: the nodes nest.
|
|
123
|
+
"""
|
|
124
|
+
return NAME_SEPARATOR.join(part for part in parts if part)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def join_path(prefix: str, name: str) -> str:
|
|
128
|
+
"""Return one field path below another, spelled the way the selection spells it."""
|
|
129
|
+
return f"{prefix}{SEPARATOR}{name}" if prefix else name
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
133
|
+
class StandardDataType:
|
|
134
|
+
"""A DataType OPC UA itself defines, named by its numeric identifier in namespace 0.
|
|
135
|
+
|
|
136
|
+
``ObjectIds.ImagePNG`` is one. Naming it says what the bytes of a bulk payload are, without
|
|
137
|
+
transforming them.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
identifier: int
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
144
|
+
class ProjectDataType:
|
|
145
|
+
"""A DataType this project's own nodeset defines, named by its generated NodeId definition.
|
|
146
|
+
|
|
147
|
+
:data:`opensmi.ros2.server.events.SIGNED_BYTE_STRING_TYPE` is the only one so far. The
|
|
148
|
+
definition is resolved to a NodeId where the nodes are made, because the namespace index is
|
|
149
|
+
specific to one server.
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
identifier: NodeIdDefinition
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
156
|
+
class EnumDataType:
|
|
157
|
+
"""An enumeration DataType to mint into the server, and the values it lists.
|
|
158
|
+
|
|
159
|
+
:ivar name: The DataType's browse name, qualified per Component because the server's address
|
|
160
|
+
space is shared while two Components may hold different value sets for one ROS2 field. The
|
|
161
|
+
qualifier is generated.
|
|
162
|
+
:ivar values: The ROS2 value of each label, in the order a client should see them. The ROS2
|
|
163
|
+
value is kept, not the position, because a constant set need not start at zero or be
|
|
164
|
+
contiguous.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
name: str
|
|
168
|
+
values: tuple[tuple[int, str], ...]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
PlanDataType: TypeAlias = "StandardDataType | ProjectDataType | EnumDataType | type"
|
|
172
|
+
"""What a plan may say about a variable's DataType, resolved to a NodeId where the nodes are made.
|
|
173
|
+
|
|
174
|
+
A plan is a pure value, and the NodeId of one of our types depends on the server, while an
|
|
175
|
+
enumeration or a structure has no NodeId until it is minted (:mod:`opensmi.ros2.server.mutation`).
|
|
176
|
+
A ``type`` is the structure class that is the element type of an array of structures, which the
|
|
177
|
+
generic walk emits for a repeated message.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
182
|
+
class NodeLevel:
|
|
183
|
+
"""One inner level of a node path: a structure, or a group, that holds the nodes below it.
|
|
184
|
+
|
|
185
|
+
:ivar name: Its browse name.
|
|
186
|
+
:ivar display_name: The raw ROS2 name, or the new name a ``rename`` gave it.
|
|
187
|
+
:ivar message: The ROS2 message type of the structure; ``None`` for a group.
|
|
188
|
+
:ivar group: Whether it only gathers the nodes below it, such as a Binding or a ROS2 parameter
|
|
189
|
+
namespace. A group becomes a grouping Object, a structure a complex Variable.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
name: str
|
|
193
|
+
display_name: str
|
|
194
|
+
message: type[Message] | None = None
|
|
195
|
+
group: bool = False
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def ros2_type(self) -> str:
|
|
199
|
+
"""Return the name of the ROS2 message type of the structure, empty for a group."""
|
|
200
|
+
return "" if self.message is None else self.message.ros2.type_name
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
204
|
+
class PlanVariable:
|
|
205
|
+
"""One OPC UA Variable to create, and the ROS2 field it reads.
|
|
206
|
+
|
|
207
|
+
Its place is a node path: the :attr:`above` levels, then :attr:`name`.
|
|
208
|
+
|
|
209
|
+
:ivar name: The browse name of the leaf, relative to the Projection that emitted it. Empty
|
|
210
|
+
means the node takes the name of whatever contains it.
|
|
211
|
+
:ivar display_name: The raw ROS2 name of the leaf, or its new name from a ``rename``; ``None``
|
|
212
|
+
when it is :attr:`name` itself.
|
|
213
|
+
:ivar above: The levels this leaf sits in, outermost first. A parent adds its own field to the
|
|
214
|
+
front of whatever its nested type emitted.
|
|
215
|
+
:ivar source: The ROS2 field path this variable reads, so a node can be traced back.
|
|
216
|
+
:ivar initial: The typed value written at boot. It is typed rather than null so that a status
|
|
217
|
+
code written over it does not leave a client with an empty value.
|
|
218
|
+
:ivar variant_type: The OPC UA type, explicit because an empty sequence cannot imply one and
|
|
219
|
+
``float32`` and ``float64`` are both Python ``float``.
|
|
220
|
+
:ivar datatype: The semantic DataType where the variant type does not say enough (a signed
|
|
221
|
+
bulk payload, an enumeration), else ``None``.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
name: str
|
|
225
|
+
source: str
|
|
226
|
+
initial: object
|
|
227
|
+
variant_type: ua.VariantType
|
|
228
|
+
datatype: PlanDataType | None = None
|
|
229
|
+
display_name: str | None = None
|
|
230
|
+
above: tuple[NodeLevel, ...] = ()
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def node_path(self) -> NodePath:
|
|
234
|
+
"""Return the browse names from the top of the plan down to this leaf."""
|
|
235
|
+
return (*(level.name for level in self.above), *((self.name,) if self.name else ()))
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def display_names(self) -> tuple[str, ...]:
|
|
239
|
+
"""Return the display name of each node on :attr:`node_path`."""
|
|
240
|
+
leaf = (self.display_name or self.name,) if self.name else ()
|
|
241
|
+
return (*(level.display_name for level in self.above), *leaf)
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def full_name(self) -> str:
|
|
245
|
+
"""Return the flat name this variable is rendered under, relative to the plan."""
|
|
246
|
+
return flat_name(*self.node_path)
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def display(self) -> str:
|
|
250
|
+
"""Return the display name of the leaf node, or ``""`` when it takes its container's."""
|
|
251
|
+
return self.display_names[-1] if self.display_names else ""
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def inner_levels(self) -> dict[NodePath, NodeLevel]:
|
|
255
|
+
"""Return the structures above this leaf by their node path.
|
|
256
|
+
|
|
257
|
+
A message collapsed to one value is the leaf itself, not a level.
|
|
258
|
+
"""
|
|
259
|
+
levels = self.above if self.name else self.above[:-1]
|
|
260
|
+
return {
|
|
261
|
+
tuple(level.name for level in self.above[: index + 1]): level
|
|
262
|
+
for index, level in enumerate(levels)
|
|
263
|
+
if not level.group
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
@property
|
|
267
|
+
def is_array(self) -> bool:
|
|
268
|
+
"""Return whether this variable carries many values rather than one.
|
|
269
|
+
|
|
270
|
+
Read off the boot value, which :func:`ua_shape` makes a list for any array.
|
|
271
|
+
"""
|
|
272
|
+
return isinstance(self.initial, list)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
276
|
+
class PlanObject:
|
|
277
|
+
"""One OPC UA Object to create, with its own entries below it.
|
|
278
|
+
|
|
279
|
+
The generic walk emits none, and a plan that carries one is refused where the nodes are made:
|
|
280
|
+
a message nests as complex Variables.
|
|
281
|
+
|
|
282
|
+
:ivar name: As :class:`PlanVariable`'s, empty included.
|
|
283
|
+
:ivar children: What hangs below it, each named relative to it.
|
|
284
|
+
:ivar display_name: The raw name of the Object, or ``None`` when it is :attr:`name` itself.
|
|
285
|
+
:ivar object_type: The ObjectType to instantiate, for a recipe naming one out of a nodeset.
|
|
286
|
+
A plain folder otherwise, which is what a structure rendered for browsing wants.
|
|
287
|
+
"""
|
|
288
|
+
|
|
289
|
+
name: str
|
|
290
|
+
children: tuple[PlanEntry, ...]
|
|
291
|
+
display_name: str | None = None
|
|
292
|
+
object_type: ua.NodeId | int = ObjectIds.FolderType
|
|
293
|
+
|
|
294
|
+
@property
|
|
295
|
+
def full_name(self) -> str:
|
|
296
|
+
"""Return the flat name of this Object, which is its :attr:`name`."""
|
|
297
|
+
return self.name
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
PlanEntry: TypeAlias = "PlanVariable | PlanObject"
|
|
301
|
+
"""The two verbs, and there is no third."""
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def inner_levels(plan: Iterable[PlanEntry]) -> dict[NodePath, NodeLevel]:
|
|
305
|
+
"""Return every structure a plan's variables sit in, by node path.
|
|
306
|
+
|
|
307
|
+
These are the nodes that become complex Variables.
|
|
308
|
+
"""
|
|
309
|
+
levels: dict[NodePath, NodeLevel] = {}
|
|
310
|
+
for entry in plan:
|
|
311
|
+
if isinstance(entry, PlanVariable):
|
|
312
|
+
levels.update(entry.inner_levels)
|
|
313
|
+
return levels
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
317
|
+
class ProjectionContext:
|
|
318
|
+
"""What a Projection needs besides the message in front of it.
|
|
319
|
+
|
|
320
|
+
:ivar registry: How a nested type finds its own Projection.
|
|
321
|
+
:ivar selected: The ROS2 field paths that survived the Binding's selection, absolute from the
|
|
322
|
+
root of the declared message. Selection is applied before projection, so a Projection is
|
|
323
|
+
never asked about a field the declaration removed.
|
|
324
|
+
:ivar path: The absolute ROS2 path of the message being shaped or decoded. Empty at the root.
|
|
325
|
+
:ivar qualifier: What distinguishes this Component's minted DataTypes from another's. Empty
|
|
326
|
+
outside a Component.
|
|
327
|
+
:ivar rename: The new browse name of a field, by its absolute ROS2 field path, from the
|
|
328
|
+
Binding's selection.
|
|
329
|
+
:ivar raw_names: Whether fields keep their ROS2 names. The fields of a structure array's
|
|
330
|
+
element do: they are field names of a DataType, not browse names.
|
|
331
|
+
:ivar byte_string_ceiling: How many bytes a bulk payload may carry, or ``0`` for no ceiling.
|
|
332
|
+
It is the server's own, published in its capability variable
|
|
333
|
+
(:mod:`opensmi.ros2.server.limits`), and the Projection applies it because the send path
|
|
334
|
+
has no check of its own.
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
registry: ProjectionRegistry
|
|
338
|
+
selected: frozenset[str]
|
|
339
|
+
path: str = ""
|
|
340
|
+
qualifier: str = ""
|
|
341
|
+
rename: Mapping[str, str] = field(default_factory=dict)
|
|
342
|
+
raw_names: bool = False
|
|
343
|
+
byte_string_ceiling: int = 0
|
|
344
|
+
|
|
345
|
+
def child(self, field_name: str) -> ProjectionContext:
|
|
346
|
+
"""Return the context of one field of the message this context is on."""
|
|
347
|
+
return replace(self, path=join_path(self.path, field_name))
|
|
348
|
+
|
|
349
|
+
@property
|
|
350
|
+
def included(self) -> bool:
|
|
351
|
+
"""Return whether the selection kept the path this context is on."""
|
|
352
|
+
return self.path in self.selected
|
|
353
|
+
|
|
354
|
+
def without(self, field_paths: Iterable[str]) -> ProjectionContext:
|
|
355
|
+
"""Return this context with some paths below it removed, subtrees and all.
|
|
356
|
+
|
|
357
|
+
This is what the drop recipe uses. A dropped field is as invisible as an excluded one.
|
|
358
|
+
"""
|
|
359
|
+
dropped: set[str] = set()
|
|
360
|
+
for field_path in field_paths:
|
|
361
|
+
full = join_path(self.path, field_path)
|
|
362
|
+
dropped.update(path for path in self.selected if path == full or path.startswith(f"{full}{SEPARATOR}"))
|
|
363
|
+
return replace(self, selected=self.selected - dropped)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
ShapeFunction: TypeAlias = "Callable[[type[Message], ProjectionContext], tuple[PlanEntry, ...]]"
|
|
367
|
+
"""Run once at init: a message dataclass becomes a node plan."""
|
|
368
|
+
|
|
369
|
+
DecodeFunction: TypeAlias = "Callable[[Message, ProjectionContext], Mapping[str, object]]"
|
|
370
|
+
"""Run per message: a payload becomes a map from plan name to the value to write."""
|
|
371
|
+
|
|
372
|
+
EncodeFunction: TypeAlias = "Callable[[type[Message], Mapping[str, object], ProjectionContext], Message]"
|
|
373
|
+
"""Run per publish: that same map becomes a payload again, where the recipe has an inverse."""
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@dataclass(frozen=True, slots=True)
|
|
377
|
+
class Projection(ABC):
|
|
378
|
+
"""How one ROS2 type is rendered, as the steps and the type they answer for.
|
|
379
|
+
|
|
380
|
+
Abstract: an author writes one of the classes in :mod:`opensmi.ros2.server.recipes`.
|
|
381
|
+
|
|
382
|
+
:ivar type_name: The ROS2 type this entry answers for, or :data:`ANY_TYPE` for the entry that
|
|
383
|
+
answers for every one. Keying is by type name alone.
|
|
384
|
+
:ivar override: Whether this entry may shadow one already registered for its type. A duplicate
|
|
385
|
+
is fatal without it, so the address space never depends on registration order.
|
|
386
|
+
:ivar type_hash: The RIHS01 hash of the definition this entry was authored against, or
|
|
387
|
+
``None``. It lets CI report that a type moved under a curated entry. It never selects an
|
|
388
|
+
entry, since that would render different address spaces for different vendor builds.
|
|
389
|
+
"""
|
|
390
|
+
|
|
391
|
+
type_name: str
|
|
392
|
+
override: bool = field(default=False, kw_only=True)
|
|
393
|
+
type_hash: str | None = field(default=None, kw_only=True)
|
|
394
|
+
|
|
395
|
+
@abstractmethod
|
|
396
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
397
|
+
"""Return the nodes this type becomes, named relative to whatever contains them."""
|
|
398
|
+
|
|
399
|
+
@abstractmethod
|
|
400
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
401
|
+
"""Return what one payload writes, keyed by the names :meth:`shape` created."""
|
|
402
|
+
|
|
403
|
+
@property
|
|
404
|
+
def inverse(self) -> EncodeFunction | None:
|
|
405
|
+
"""Return the function that runs this entry backwards, or ``None`` when it has none.
|
|
406
|
+
|
|
407
|
+
Each recipe derives it from what it is. ``None`` means nothing can be published through
|
|
408
|
+
the entry, and a publishing Binding that reaches one fails at init.
|
|
409
|
+
"""
|
|
410
|
+
return None
|
|
411
|
+
|
|
412
|
+
def inverts(self, message_type: type[Message]) -> bool:
|
|
413
|
+
"""Return whether this entry runs backwards for one ROS2 type.
|
|
414
|
+
|
|
415
|
+
It takes a type because an Object inverts only if its field plan is total, which
|
|
416
|
+
depends on the message as well as the recipe. That lets the check run at init.
|
|
417
|
+
"""
|
|
418
|
+
return self.inverse is not None
|
|
419
|
+
|
|
420
|
+
def matches(self, type_name: str) -> bool:
|
|
421
|
+
"""Return whether this entry answers for a ROS2 type."""
|
|
422
|
+
return self.type_name in (type_name, ANY_TYPE)
|
|
423
|
+
|
|
424
|
+
def inverse_of(
|
|
425
|
+
self,
|
|
426
|
+
message_type: type[Message],
|
|
427
|
+
values: Mapping[str, object],
|
|
428
|
+
context: ProjectionContext,
|
|
429
|
+
) -> Message:
|
|
430
|
+
"""Run this entry backwards, refusing rather than inventing when it has no inverse.
|
|
431
|
+
|
|
432
|
+
:raises NotInvertibleError: When this entry has no inverse, which is a declaration fault
|
|
433
|
+
wherever it is reached.
|
|
434
|
+
"""
|
|
435
|
+
encode = self.inverse
|
|
436
|
+
if encode is None:
|
|
437
|
+
message = (
|
|
438
|
+
f"the {type(self).__name__} Projection of {self.type_name!r} cannot run "
|
|
439
|
+
f"backwards, so nothing can be published through it"
|
|
440
|
+
)
|
|
441
|
+
raise NotInvertibleError(message)
|
|
442
|
+
return encode(message_type, values, context)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
446
|
+
class ProjectionRegistry:
|
|
447
|
+
"""The ordered entries a Component renders its types through.
|
|
448
|
+
|
|
449
|
+
The first entry that matches wins, so an entry placed ahead of another shadows it, and the
|
|
450
|
+
generic walk sits last because it matches everything. A registry is grown with :meth:`extended`
|
|
451
|
+
and its entries are never edited, so one Machine's default can start several Components. Only
|
|
452
|
+
:attr:`element_structures`, a memo, changes.
|
|
453
|
+
"""
|
|
454
|
+
|
|
455
|
+
entries: tuple[Projection, ...]
|
|
456
|
+
|
|
457
|
+
element_structures: dict[tuple[type[Message], str], type] = field(
|
|
458
|
+
default_factory=dict,
|
|
459
|
+
init=False,
|
|
460
|
+
compare=False,
|
|
461
|
+
repr=False,
|
|
462
|
+
)
|
|
463
|
+
"""The structure each repeated element type renders as, by type and qualifier.
|
|
464
|
+
|
|
465
|
+
A memo, on the registry because the shipped registry is shared by several Components: a global
|
|
466
|
+
cache keyed on the type alone would hand one Component another's enumeration names.
|
|
467
|
+
"""
|
|
468
|
+
|
|
469
|
+
def find(self, type_name: str) -> Projection:
|
|
470
|
+
"""Return the first entry answering for a ROS2 type.
|
|
471
|
+
|
|
472
|
+
:raises DeclarationError: When no entry does, which means the registry was
|
|
473
|
+
assembled without the entry that matches last.
|
|
474
|
+
"""
|
|
475
|
+
for entry in self.entries:
|
|
476
|
+
if entry.matches(type_name):
|
|
477
|
+
return entry
|
|
478
|
+
message = (
|
|
479
|
+
f"no Projection covers {type_name!r}; a registry has to end with an entry whose type "
|
|
480
|
+
f"is {ANY_TYPE!r}, the generic field-walk being the one that does"
|
|
481
|
+
)
|
|
482
|
+
raise DeclarationError(message)
|
|
483
|
+
|
|
484
|
+
def extended(self, entries: Iterable[Projection]) -> ProjectionRegistry:
|
|
485
|
+
"""Return this registry with entries ahead of it, refusing an unannounced duplicate.
|
|
486
|
+
|
|
487
|
+
Ahead, so a Component's entry is found before the Machine's, and the Machine's before the
|
|
488
|
+
shipped one.
|
|
489
|
+
|
|
490
|
+
:raises DuplicateProjectionError: When an entry covers a type another already covers and
|
|
491
|
+
does not say ``override=True``.
|
|
492
|
+
"""
|
|
493
|
+
added: list[Projection] = []
|
|
494
|
+
for entry in entries:
|
|
495
|
+
_require_no_silent_shadowing(entry, (*added, *self.entries))
|
|
496
|
+
added.append(entry)
|
|
497
|
+
return ProjectionRegistry(entries=(*added, *self.entries))
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _require_no_silent_shadowing(entry: Projection, covered: Iterable[Projection]) -> None:
|
|
501
|
+
"""Refuse a second entry for one type unless it says it is replacing the first."""
|
|
502
|
+
if entry.override:
|
|
503
|
+
return
|
|
504
|
+
shadowed = next((each for each in covered if each.type_name == entry.type_name), None)
|
|
505
|
+
if shadowed is None:
|
|
506
|
+
return
|
|
507
|
+
message = (
|
|
508
|
+
f"a {type(shadowed).__name__} Projection already covers {entry.type_name!r}, and this "
|
|
509
|
+
f"{type(entry).__name__} one would shadow it; say override=True where you mean to "
|
|
510
|
+
f"replace it, so that precedence is something a reader can see"
|
|
511
|
+
)
|
|
512
|
+
raise DuplicateProjectionError(message)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def require_invertible(message_type: type[Message], context: ProjectionContext) -> None:
|
|
516
|
+
"""Refuse a declaration that writes a type into ROS2 through a Projection with no inverse.
|
|
517
|
+
|
|
518
|
+
A Binding that publishes is declarable only if every Projection reachable in its message type
|
|
519
|
+
inverts. The error names the ROS2 type, the field path and the entry. An action's
|
|
520
|
+
goal type is checked like a published topic's. Reachable means through the selection, so an
|
|
521
|
+
excluded field is never asked.
|
|
522
|
+
|
|
523
|
+
:raises NotInvertibleError: When any reachable entry cannot run backwards.
|
|
524
|
+
"""
|
|
525
|
+
projection = context.registry.find(message_type.ros2.type_name)
|
|
526
|
+
if not projection.inverts(message_type):
|
|
527
|
+
message = (
|
|
528
|
+
f"the {type(projection).__name__} Projection of {projection.type_name!r} cannot run "
|
|
529
|
+
f"backwards, so nothing written at {context.path or 'the root of the message'!r} "
|
|
530
|
+
f"could be published through it; exclude the field, or curate the type with an "
|
|
531
|
+
f"entry that inverts"
|
|
532
|
+
)
|
|
533
|
+
raise NotInvertibleError(message)
|
|
534
|
+
for described, child, nested in _selected_fields(message_type, context):
|
|
535
|
+
if nested is None:
|
|
536
|
+
continue
|
|
537
|
+
if _repeats(described.field_type):
|
|
538
|
+
require_invertible(nested, _element_context(nested, child))
|
|
539
|
+
continue
|
|
540
|
+
require_invertible(nested, child)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def narrowed(
|
|
544
|
+
context: ProjectionContext,
|
|
545
|
+
message_type: type[Message],
|
|
546
|
+
selection: FieldSelection,
|
|
547
|
+
) -> ProjectionContext:
|
|
548
|
+
"""Return a Component's context narrowed to what one surface's selection kept.
|
|
549
|
+
|
|
550
|
+
A Binding with several surfaces (an action's goal, feedback and result; a service's request and
|
|
551
|
+
response) narrows its context once per surface.
|
|
552
|
+
|
|
553
|
+
A type with no fields at all (a bare trigger goal, a ping request) skips the selector, since
|
|
554
|
+
nothing was removed. A pattern written against such a type still reaches the selector and is
|
|
555
|
+
refused by name.
|
|
556
|
+
|
|
557
|
+
:raises FieldSelectionError: When a pattern matches nothing, or the two leave no field.
|
|
558
|
+
"""
|
|
559
|
+
if not message_type.ros2.fields and not selection.patterns and not selection.rename:
|
|
560
|
+
return replace(context, selected=frozenset())
|
|
561
|
+
return replace(context, selected=resolve_selection(message_type, selection), rename=selection.rename)
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def shaped(message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
565
|
+
"""Return the nodes one message type becomes, through the context's registry."""
|
|
566
|
+
return context.registry.find(message_type.ros2.type_name).shape(message_type, context)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def generic_shape(
|
|
570
|
+
message_type: type[Message],
|
|
571
|
+
context: ProjectionContext,
|
|
572
|
+
overrides: Mapping[str, PlanEntry] | None = None,
|
|
573
|
+
) -> tuple[PlanEntry, ...]:
|
|
574
|
+
"""Render a message type field by field, one flat variable per leaf.
|
|
575
|
+
|
|
576
|
+
Recursion runs through the registry, so a nested type with a curated Projection is rendered by
|
|
577
|
+
that entry and its names are carried up under this field's name. A field that repeats a message
|
|
578
|
+
is one variable holding an array of a structure.
|
|
579
|
+
|
|
580
|
+
:param overrides: What to emit for a field instead of walking it, by ROS2 field name. The blob
|
|
581
|
+
and enum recipes are overrides and nothing else. An override of a field the selection
|
|
582
|
+
removed is never reached.
|
|
583
|
+
:raises UnprojectableFieldError: When a repeated message's element cannot render as a
|
|
584
|
+
structure: its Projection emits an Object, or a field of it has a type no structure
|
|
585
|
+
field can carry.
|
|
586
|
+
"""
|
|
587
|
+
given = overrides or {}
|
|
588
|
+
selected = list(_selected_fields(message_type, context))
|
|
589
|
+
names = _siblings(context, [described.name for described, _, _ in selected])
|
|
590
|
+
entries: list[PlanEntry] = []
|
|
591
|
+
for described, child, nested in selected:
|
|
592
|
+
name = names[described.name]
|
|
593
|
+
display = _display_name(context, described.name)
|
|
594
|
+
override = given.get(described.name)
|
|
595
|
+
if override is not None:
|
|
596
|
+
entries.append(replace(override, name=name, display_name=display))
|
|
597
|
+
elif nested is None:
|
|
598
|
+
entries.append(_plan_variable(described, child, name, display))
|
|
599
|
+
elif _repeats(described.field_type):
|
|
600
|
+
entries.append(_plan_structures(described, child, nested, name, display))
|
|
601
|
+
else:
|
|
602
|
+
level = NodeLevel(name=name, display_name=display, message=nested)
|
|
603
|
+
projection = context.registry.find(nested.ros2.type_name)
|
|
604
|
+
entries.extend(_below(level, entry) for entry in projection.shape(nested, child))
|
|
605
|
+
return tuple(entries)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def generic_decode(
|
|
609
|
+
message: Message,
|
|
610
|
+
context: ProjectionContext,
|
|
611
|
+
overrides: Mapping[str, object] | None = None,
|
|
612
|
+
) -> Mapping[str, object]:
|
|
613
|
+
"""Read one payload into the names :func:`generic_shape` created for its type.
|
|
614
|
+
|
|
615
|
+
:param overrides: What a field's variable reads instead of the field itself, by ROS2 field
|
|
616
|
+
name. It pairs with the shape override of the same name.
|
|
617
|
+
"""
|
|
618
|
+
given = overrides or {}
|
|
619
|
+
values: dict[str, object] = {}
|
|
620
|
+
for described, child, nested in _selected_fields(type(message), context):
|
|
621
|
+
name = described.name
|
|
622
|
+
key = browse_name_of(context, name)
|
|
623
|
+
if name in given:
|
|
624
|
+
values[key] = given[name]
|
|
625
|
+
continue
|
|
626
|
+
value = getattr(message, name)
|
|
627
|
+
if nested is None:
|
|
628
|
+
values[key] = ua_value(value)
|
|
629
|
+
continue
|
|
630
|
+
if _repeats(described.field_type):
|
|
631
|
+
values[key] = _decoded_elements(value, nested, child)
|
|
632
|
+
continue
|
|
633
|
+
projection = context.registry.find(nested.ros2.type_name)
|
|
634
|
+
for below, decoded in projection.decode(value, child).items():
|
|
635
|
+
values[flat_name(key, below)] = decoded
|
|
636
|
+
return values
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _decoded_elements(
|
|
640
|
+
value: object,
|
|
641
|
+
element_type: type[Message],
|
|
642
|
+
context: ProjectionContext,
|
|
643
|
+
) -> list[Mapping[str, object]]:
|
|
644
|
+
"""Return one repeated message field as the array of elements its variable carries.
|
|
645
|
+
|
|
646
|
+
Each element is decoded by the Projection covering its type into a map from its structure's
|
|
647
|
+
field names to values. An empty sequence decodes to an empty list, which is a value.
|
|
648
|
+
|
|
649
|
+
The elements are plain maps, not ExtensionObjects: encoding one needs the server's namespace
|
|
650
|
+
and belongs to the variable being written (:mod:`opensmi.ros2.server.mutation`).
|
|
651
|
+
"""
|
|
652
|
+
projection = context.registry.find(element_type.ros2.type_name)
|
|
653
|
+
element_context = _element_context(element_type, context)
|
|
654
|
+
# A payload holds containers as tuples; anything else is not from the walk and decodes as empty.
|
|
655
|
+
elements = value if isinstance(value, (list, tuple)) else ()
|
|
656
|
+
return [projection.decode(element, element_context) for element in elements]
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def generic_encode(
|
|
660
|
+
message_type: type[Message],
|
|
661
|
+
values: Mapping[str, object],
|
|
662
|
+
context: ProjectionContext,
|
|
663
|
+
overrides: Mapping[str, object] | None = None,
|
|
664
|
+
) -> Message:
|
|
665
|
+
"""Build one payload out of the names :func:`generic_shape` created, and nothing else.
|
|
666
|
+
|
|
667
|
+
The inverse of :func:`generic_decode`. A field the selection removed is not filled from a
|
|
668
|
+
default: a covariance of zeros means perfectly certain in ROS2, not unknown.
|
|
669
|
+
|
|
670
|
+
:param overrides: The ROS2 value of a field the caller has already worked out, by field name.
|
|
671
|
+
:raises NotInvertibleError: When a field of the message has no value, whether because the
|
|
672
|
+
selection removed it or because the caller supplied none.
|
|
673
|
+
"""
|
|
674
|
+
given = overrides or {}
|
|
675
|
+
built: dict[str, object] = {}
|
|
676
|
+
for described in message_type.ros2.fields:
|
|
677
|
+
name = described.name
|
|
678
|
+
child = context.child(name)
|
|
679
|
+
if name in given:
|
|
680
|
+
built[name] = given[name]
|
|
681
|
+
continue
|
|
682
|
+
nested = message_type.ros2_nested.get(name)
|
|
683
|
+
if nested is not None and not nested.ros2.fields:
|
|
684
|
+
# A nested type with no fields (`std_msgs/Empty`, the request of every no-argument
|
|
685
|
+
# service) is never selected. There is no value to invent, so build it empty.
|
|
686
|
+
built[name] = nested()
|
|
687
|
+
continue
|
|
688
|
+
if not child.included:
|
|
689
|
+
_refuse_a_partial_payload(message_type, child.path, "the selection removed it")
|
|
690
|
+
key = browse_name_of(context, name)
|
|
691
|
+
if nested is None:
|
|
692
|
+
if key not in values:
|
|
693
|
+
_refuse_a_partial_payload(message_type, child.path, "no value was supplied for it")
|
|
694
|
+
built[name] = ros2_value(values[key], described.field_type)
|
|
695
|
+
continue
|
|
696
|
+
if _repeats(described.field_type):
|
|
697
|
+
if key not in values:
|
|
698
|
+
_refuse_a_partial_payload(message_type, child.path, "no value was supplied for it")
|
|
699
|
+
built[name] = _encoded_elements(values[key], nested, child)
|
|
700
|
+
continue
|
|
701
|
+
projection = context.registry.find(nested.ros2.type_name)
|
|
702
|
+
built[name] = projection.inverse_of(nested, _below_values(values, key), child)
|
|
703
|
+
return message_type(**built)
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _encoded_elements(
|
|
707
|
+
value: object,
|
|
708
|
+
element_type: type[Message],
|
|
709
|
+
context: ProjectionContext,
|
|
710
|
+
) -> tuple[Message, ...]:
|
|
711
|
+
"""Return the ROS2 sequence that the array of elements of one repeated message field describes.
|
|
712
|
+
|
|
713
|
+
Each element is a map from the names its Projection knows to values, rebuilt by that
|
|
714
|
+
Projection's own inverse. An element that lacks a field is refused by name, and an
|
|
715
|
+
empty list builds an empty sequence.
|
|
716
|
+
|
|
717
|
+
:raises NotInvertibleError: When an element has no value for a field of its type.
|
|
718
|
+
:raises ValueError: When the value is not a list, or an element of it is not a map. This is a
|
|
719
|
+
client's write, not a declaration fault.
|
|
720
|
+
"""
|
|
721
|
+
if not isinstance(value, (list, tuple)):
|
|
722
|
+
message = (
|
|
723
|
+
f"{context.path!r} was written as {type(value).__name__} rather than as an array; it "
|
|
724
|
+
f"carries an array of {element_type.ros2.type_name}, of any length"
|
|
725
|
+
)
|
|
726
|
+
# ValueError, not TypeError: a client wrote this to a node, no caller passed a bad argument.
|
|
727
|
+
raise ValueError(message) # noqa: TRY004
|
|
728
|
+
projection = context.registry.find(element_type.ros2.type_name)
|
|
729
|
+
element_context = _element_context(element_type, context)
|
|
730
|
+
elements: list[Message] = []
|
|
731
|
+
for index, each in enumerate(value):
|
|
732
|
+
if not isinstance(each, Mapping):
|
|
733
|
+
message = (
|
|
734
|
+
f"element {index} of {context.path!r} is {type(each).__name__} rather than a map "
|
|
735
|
+
f"from field names to values; it carries an array of {element_type.ros2.type_name}"
|
|
736
|
+
)
|
|
737
|
+
raise ValueError(message) # noqa: TRY004
|
|
738
|
+
elements.append(projection.inverse_of(element_type, each, element_context))
|
|
739
|
+
return tuple(elements)
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _refuse_a_partial_payload(message_type: type[Message], path: str, why: str) -> None:
|
|
743
|
+
"""Refuse to build a message with a hole in it, naming the field and the reason."""
|
|
744
|
+
message = (
|
|
745
|
+
f"{message_type.ros2.type_name} cannot be built without {path!r}, and {why}; a field "
|
|
746
|
+
f"filled from a default is a value nobody sent"
|
|
747
|
+
)
|
|
748
|
+
raise NotInvertibleError(message)
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def _below_values(values: Mapping[str, object], name: str) -> Mapping[str, object]:
|
|
752
|
+
"""Return the values belonging to one nested field, with its own name taken off the front."""
|
|
753
|
+
prefix = f"{name}{NAME_SEPARATOR}"
|
|
754
|
+
below = {key[len(prefix) :]: value for key, value in values.items() if key.startswith(prefix)}
|
|
755
|
+
if name in values:
|
|
756
|
+
# A collapsing recipe answers under the empty name, which up here is the field itself.
|
|
757
|
+
below[""] = values[name]
|
|
758
|
+
return below
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _plan_variable(described: FieldDescription, context: ProjectionContext, name: str, display: str) -> PlanVariable:
|
|
762
|
+
"""Return the variable one modelled ROS2 field becomes under the generic walk."""
|
|
763
|
+
initial, variant_type = ua_shape(described.field_type)
|
|
764
|
+
return PlanVariable(
|
|
765
|
+
name=name,
|
|
766
|
+
display_name=display,
|
|
767
|
+
source=context.path,
|
|
768
|
+
initial=initial,
|
|
769
|
+
variant_type=variant_type,
|
|
770
|
+
)
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def browse_name_of(context: ProjectionContext, field_name: str) -> str:
|
|
774
|
+
"""Return the browse name of one field of the message the context is on.
|
|
775
|
+
|
|
776
|
+
The key a field has in the decode and encode maps, for a recipe that works one field out itself.
|
|
777
|
+
"""
|
|
778
|
+
if context.raw_names:
|
|
779
|
+
return field_name
|
|
780
|
+
return context.rename.get(join_path(context.path, field_name)) or browse_name(field_name)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def _display_name(context: ProjectionContext, field_name: str) -> str:
|
|
784
|
+
"""Return what a client is told the field is called: the new name, else the raw ROS2 name."""
|
|
785
|
+
return context.rename.get(join_path(context.path, field_name), field_name)
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _siblings(context: ProjectionContext, field_names: list[str]) -> dict[str, str]:
|
|
789
|
+
"""Return the browse name of each of these sibling fields, refusing two that share one.
|
|
790
|
+
|
|
791
|
+
:raises DuplicateVariableNameError: When two give one browse name, whether by conversion or by
|
|
792
|
+
a rename. The error names both ROS2 names.
|
|
793
|
+
"""
|
|
794
|
+
if context.raw_names:
|
|
795
|
+
return {name: name for name in field_names}
|
|
796
|
+
renamed = {name: new for name in field_names if (new := context.rename.get(join_path(context.path, name)))}
|
|
797
|
+
return browse_names(field_names, renamed)
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def _selected_fields(
|
|
801
|
+
message_type: type[Message],
|
|
802
|
+
context: ProjectionContext,
|
|
803
|
+
) -> Iterator[tuple[FieldDescription, ProjectionContext, type[Message] | None]]:
|
|
804
|
+
"""Yield each field the selection kept, with its context and the message type it nests.
|
|
805
|
+
|
|
806
|
+
The generic walk's steps share this route and differ only in what they do at each stop.
|
|
807
|
+
"""
|
|
808
|
+
for described in message_type.ros2.fields:
|
|
809
|
+
child = context.child(described.name)
|
|
810
|
+
if not child.included:
|
|
811
|
+
continue
|
|
812
|
+
yield described, child, message_type.ros2_nested.get(described.name)
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
def _below(level: NodeLevel, entry: PlanEntry) -> PlanEntry:
|
|
816
|
+
"""Carry one entry up under the field that produced it, which becomes a level above it."""
|
|
817
|
+
if isinstance(entry, PlanObject):
|
|
818
|
+
return replace(entry, name=flat_name(level.name, entry.name))
|
|
819
|
+
return replace(entry, above=(level, *entry.above))
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def _repeats(field_type: FieldType) -> bool:
|
|
823
|
+
"""Return whether a field holds many of its type rather than one."""
|
|
824
|
+
return not isinstance(field_type, NestedType)
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def _element_context(element_type: type[Message], context: ProjectionContext) -> ProjectionContext:
|
|
828
|
+
"""Return the context the elements of a repeated message field are rendered in.
|
|
829
|
+
|
|
830
|
+
The path goes back to empty, because an element's leaves are named from its own root. The
|
|
831
|
+
selection becomes the element type's whole field set: the selector treats a repeated message as
|
|
832
|
+
one leaf and never walks inside it (:mod:`opensmi.ros2.runtime.selection`), so an element is
|
|
833
|
+
never partial and can be rebuilt exactly. Fields keep their ROS2 names and no rename
|
|
834
|
+
applies, because they are the field names of a DataType. The registry is kept, so curated
|
|
835
|
+
Projections still apply to elements.
|
|
836
|
+
"""
|
|
837
|
+
return replace(context, path="", selected=frozenset(field_paths(element_type)), rename={}, raw_names=True)
|
|
838
|
+
|
|
839
|
+
|
|
840
|
+
def _plan_structures(
|
|
841
|
+
described: FieldDescription,
|
|
842
|
+
context: ProjectionContext,
|
|
843
|
+
element_type: type[Message],
|
|
844
|
+
name: str,
|
|
845
|
+
display: str,
|
|
846
|
+
) -> PlanVariable:
|
|
847
|
+
"""Return the variable a repeated message field becomes: one array of the element's structure.
|
|
848
|
+
|
|
849
|
+
It boots as an empty array, a legal ROS2 value, so "nobody has written this yet" is told by the
|
|
850
|
+
StatusCode, ``BadWaitingForInitialData`` (:mod:`opensmi.ros2.server.status`).
|
|
851
|
+
|
|
852
|
+
:raises UnprojectableFieldError: When the element cannot render as a structure.
|
|
853
|
+
"""
|
|
854
|
+
return PlanVariable(
|
|
855
|
+
name=name,
|
|
856
|
+
display_name=display,
|
|
857
|
+
source=context.path,
|
|
858
|
+
initial=[],
|
|
859
|
+
# A structure travels in a Variant as an ExtensionObject; the DataType says which one.
|
|
860
|
+
variant_type=ua.VariantType.ExtensionObject,
|
|
861
|
+
datatype=element_structure(element_type, context),
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def element_structure(element_type: type[Message], context: ProjectionContext) -> type:
|
|
866
|
+
"""Return the structure one element of a repeated message renders as.
|
|
867
|
+
|
|
868
|
+
Public because a recipe that repeats a message of its own needs it too. Its fields are the
|
|
869
|
+
element's plan, nested like the message. Memoised on the registry
|
|
870
|
+
(:attr:`ProjectionRegistry.element_structures`).
|
|
871
|
+
|
|
872
|
+
:raises UnprojectableFieldError: When the element's Projection emits an Object, or a field of
|
|
873
|
+
it is of a type that has no place in a structure.
|
|
874
|
+
"""
|
|
875
|
+
known = context.registry.element_structures.get((element_type, context.qualifier))
|
|
876
|
+
if known is not None:
|
|
877
|
+
return known
|
|
878
|
+
structure = _element_structure(element_type, context)
|
|
879
|
+
context.registry.element_structures[element_type, context.qualifier] = structure
|
|
880
|
+
return structure
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def _element_structure(element_type: type[Message], context: ProjectionContext) -> type:
|
|
884
|
+
"""Work out the structure of one element, which :func:`element_structure` remembers."""
|
|
885
|
+
shaped_element = shaped(element_type, _element_context(element_type, context))
|
|
886
|
+
objects = [entry.name for entry in shaped_element if isinstance(entry, PlanObject)]
|
|
887
|
+
if objects:
|
|
888
|
+
listed = ", ".join(repr(name) for name in objects)
|
|
889
|
+
message = (
|
|
890
|
+
f"the Projection of {element_type.ros2.type_name} renders {listed} as a browsable "
|
|
891
|
+
f"Object, and {context.path!r} repeats it, so its elements have to render as the "
|
|
892
|
+
f"fields of one structure: there are no nodes inside an array. Register "
|
|
893
|
+
f"Default({element_type.ros2.type_name!r}, override=True) for the Component that "
|
|
894
|
+
f"repeats it, or exclude the repeated field"
|
|
895
|
+
)
|
|
896
|
+
raise UnprojectableFieldError(message)
|
|
897
|
+
plan = [entry for entry in shaped_element if isinstance(entry, PlanVariable)]
|
|
898
|
+
# A curated element keeps the name of its ROS2 type: a type curated differently in two
|
|
899
|
+
# Components is refused where the DataType is made.
|
|
900
|
+
return level_datatypes(plan, element_type, lambda _, message_type: message_type.ros2.type_name)[()]
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
NodeLevelNaming: TypeAlias = "Callable[[NodePath, type[Message]], str]"
|
|
904
|
+
"""How a level whose subtree is curated is named: from its node path and its ROS2 type."""
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def curated_naming(qualifier: str) -> NodeLevelNaming:
|
|
908
|
+
"""Return the naming of curated levels: the qualifier and the node path, joined with dots.
|
|
909
|
+
|
|
910
|
+
``Platform.Odom`` names the root and ``Platform.Odom.Pose`` the level below it. The qualifier
|
|
911
|
+
is the Component and the Binding, so a name does not depend on what else is declared.
|
|
912
|
+
"""
|
|
913
|
+
return lambda path, _: flat_name(qualifier, *path)
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
_PACKABLE: Final = frozenset(
|
|
917
|
+
getattr(ua.VariantType, name)
|
|
918
|
+
for name in (
|
|
919
|
+
"Boolean",
|
|
920
|
+
"SByte",
|
|
921
|
+
"Byte",
|
|
922
|
+
"Int16",
|
|
923
|
+
"UInt16",
|
|
924
|
+
"Int32",
|
|
925
|
+
"UInt32",
|
|
926
|
+
"Int64",
|
|
927
|
+
"UInt64",
|
|
928
|
+
"Float",
|
|
929
|
+
"Double",
|
|
930
|
+
"String",
|
|
931
|
+
"ByteString",
|
|
932
|
+
)
|
|
933
|
+
)
|
|
934
|
+
"""The OPC UA types a field of a structure can carry."""
|
|
935
|
+
|
|
936
|
+
|
|
937
|
+
def _annotated(element: Any, initial: object) -> tuple[Any, int]:
|
|
938
|
+
"""Return the annotation of a field and the length of its fixed-size array, from its boot value."""
|
|
939
|
+
if isinstance(initial, list):
|
|
940
|
+
return list[element], len(initial)
|
|
941
|
+
return element, 0
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def _signature(message_type: type[Message]) -> tuple[StructureField, ...]:
|
|
945
|
+
"""Return the fields of the structure of a ROS2 message type, as its definition has them."""
|
|
946
|
+
fields: list[StructureField] = []
|
|
947
|
+
for described in message_type.ros2.fields:
|
|
948
|
+
nested = message_type.ros2_nested.get(described.name)
|
|
949
|
+
if nested is None:
|
|
950
|
+
initial, variant_type = ua_shape(described.field_type)
|
|
951
|
+
fields.append((described.name, *_annotated(getattr(ua, variant_type.name), initial)))
|
|
952
|
+
else:
|
|
953
|
+
length = described.field_type.length if isinstance(described.field_type, ArrayType) else 0
|
|
954
|
+
element = message_class(nested)
|
|
955
|
+
fields.append((described.name, list[element] if _repeats(described.field_type) else element, length))
|
|
956
|
+
return tuple(fields)
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def message_class(message_type: type[Message]) -> type:
|
|
960
|
+
"""Return the structure of a ROS2 message type, named by it, with the fields of its definition.
|
|
961
|
+
|
|
962
|
+
It is the DataType of a level whose subtree is not curated. Equal for equal types.
|
|
963
|
+
"""
|
|
964
|
+
return structure_class(message_type.ros2.type_name, _signature(message_type))
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def level_datatypes(
|
|
968
|
+
plan: Iterable[PlanVariable],
|
|
969
|
+
root: type[Message],
|
|
970
|
+
naming: NodeLevelNaming,
|
|
971
|
+
) -> dict[NodePath, type]:
|
|
972
|
+
"""Return the structure DataType of every level of a plan and of its root, by node path.
|
|
973
|
+
|
|
974
|
+
A level whose rendered subtree is the one its ROS2 type has (no field excluded or renamed, no
|
|
975
|
+
leaf of another type) gets the class of that type, :func:`message_class`. Any other gets a class
|
|
976
|
+
of the rendered shape, named by ``naming``. A level is curated when anything below it is,
|
|
977
|
+
since its fields differ then. The root is ``()``.
|
|
978
|
+
|
|
979
|
+
:param plan: The variables of one message, as :func:`shaped` returns them.
|
|
980
|
+
:param root: The ROS2 type of the message.
|
|
981
|
+
:raises UnprojectableFieldError: When a leaf has a type no structure field can carry.
|
|
982
|
+
"""
|
|
983
|
+
leaves = list(plan)
|
|
984
|
+
tree: dict[str, Any] = {}
|
|
985
|
+
for leaf in leaves:
|
|
986
|
+
node = tree
|
|
987
|
+
for name in leaf.node_path[:-1]:
|
|
988
|
+
node = node.setdefault(name, {})
|
|
989
|
+
node[leaf.node_path[-1]] = leaf
|
|
990
|
+
levels = inner_levels(leaves)
|
|
991
|
+
classes: dict[NodePath, type] = {}
|
|
992
|
+
|
|
993
|
+
def build(node: dict[str, Any], path: NodePath, message_type: type[Message]) -> None:
|
|
994
|
+
fields: list[StructureField] = []
|
|
995
|
+
for name, child in node.items():
|
|
996
|
+
if isinstance(child, dict):
|
|
997
|
+
below = (*path, name)
|
|
998
|
+
build(child, below, cast("type[Message]", levels[below].message))
|
|
999
|
+
fields.append((levels[below].display_name, classes[below], 0))
|
|
1000
|
+
else:
|
|
1001
|
+
fields.append((child.display, *_leaf_annotation(child)))
|
|
1002
|
+
kept = tuple(fields)
|
|
1003
|
+
name = naming(path, message_type) if kept != _signature(message_type) else message_type.ros2.type_name
|
|
1004
|
+
classes[path] = structure_class(name, kept)
|
|
1005
|
+
|
|
1006
|
+
build(tree, (), root)
|
|
1007
|
+
return classes
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def _leaf_annotation(leaf: PlanVariable) -> tuple[Any, int]:
|
|
1011
|
+
"""Return the field annotation of a leaf, and the length of its fixed-size array.
|
|
1012
|
+
|
|
1013
|
+
Only a structure class and a plain value can be a field. Any other DataType (an enumeration, a
|
|
1014
|
+
type from the nodeset or one OPC UA defines) is left to the built-in type, so Components that
|
|
1015
|
+
curate such a field differently still share one structure.
|
|
1016
|
+
|
|
1017
|
+
:raises UnprojectableFieldError: When the leaf is of a type no structure field can carry.
|
|
1018
|
+
"""
|
|
1019
|
+
if isinstance(leaf.datatype, type):
|
|
1020
|
+
element = leaf.datatype
|
|
1021
|
+
elif leaf.variant_type in _PACKABLE:
|
|
1022
|
+
element = getattr(ua, leaf.variant_type.name)
|
|
1023
|
+
else:
|
|
1024
|
+
message = (
|
|
1025
|
+
f"{leaf.full_name!r} is a {leaf.variant_type.name}, which no field of a structure can "
|
|
1026
|
+
f"carry; curate its type so that the field is a plain value, or exclude it"
|
|
1027
|
+
)
|
|
1028
|
+
raise UnprojectableFieldError(message)
|
|
1029
|
+
return _annotated(element, leaf.initial)
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def level_value(
|
|
1033
|
+
plan: Iterable[PlanVariable],
|
|
1034
|
+
classes: Mapping[NodePath, type],
|
|
1035
|
+
values: Mapping[str, object],
|
|
1036
|
+
path: NodePath = (),
|
|
1037
|
+
) -> Any:
|
|
1038
|
+
"""Return the instance of the structure of one level, from what a message decoded to.
|
|
1039
|
+
|
|
1040
|
+
This is the value a level's complex Variable holds. ``values`` is what the Projection's decode
|
|
1041
|
+
returns for the message, keyed by flat name.
|
|
1042
|
+
|
|
1043
|
+
:param classes: The result of :func:`level_datatypes` for the plan.
|
|
1044
|
+
:param path: The level to build. The root by default.
|
|
1045
|
+
:raises KeyError: When a leaf below the level has no value.
|
|
1046
|
+
"""
|
|
1047
|
+
leaves = [leaf for leaf in plan if leaf.node_path[: len(path)] == path]
|
|
1048
|
+
return _instance(leaves, classes, values, path)
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def _instance(
|
|
1052
|
+
leaves: list[PlanVariable],
|
|
1053
|
+
classes: Mapping[NodePath, type],
|
|
1054
|
+
values: Mapping[str, object],
|
|
1055
|
+
path: NodePath,
|
|
1056
|
+
) -> Any:
|
|
1057
|
+
built: dict[str, object] = {}
|
|
1058
|
+
for name in dict.fromkeys(leaf.node_path[len(path)] for leaf in leaves):
|
|
1059
|
+
below = [leaf for leaf in leaves if leaf.node_path[len(path)] == name]
|
|
1060
|
+
here = (*path, name)
|
|
1061
|
+
if len(below) == 1 and below[0].node_path == here:
|
|
1062
|
+
leaf = below[0]
|
|
1063
|
+
value = values[leaf.full_name]
|
|
1064
|
+
if isinstance(leaf.datatype, type):
|
|
1065
|
+
value = [structure_instance(leaf.datatype, each) for each in value] # pyright: ignore[reportGeneralTypeIssues]
|
|
1066
|
+
built[leaf.display] = value
|
|
1067
|
+
else:
|
|
1068
|
+
built[inner_levels(below)[here].display_name] = _instance(below, classes, values, here)
|
|
1069
|
+
return classes[path](**built)
|
|
1070
|
+
|
|
1071
|
+
|
|
1072
|
+
def ua_value(value: object) -> object:
|
|
1073
|
+
"""Return a decoded field value in the shape an OPC UA write wants.
|
|
1074
|
+
|
|
1075
|
+
A payload holds a ``tuple`` and the library builds an array from a ``list``, so that is the one
|
|
1076
|
+
conversion.
|
|
1077
|
+
"""
|
|
1078
|
+
return list(value) if isinstance(value, tuple) else value
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def ros2_value(value: object, field_type: FieldType) -> object:
|
|
1082
|
+
"""Return a value a client wrote in the shape a payload holds.
|
|
1083
|
+
|
|
1084
|
+
The mirror image of :func:`ua_value`. It reads the modelled field, since ``[]`` alone does not
|
|
1085
|
+
say whether a tuple or a list is wanted.
|
|
1086
|
+
|
|
1087
|
+
It also narrows a number to the exact Python type of its ROS2 field, because the guard that runs
|
|
1088
|
+
next (:mod:`opensmi.ros2.runtime.guard`) tests exact types, and OPC UA's scalar types subclass
|
|
1089
|
+
``int``, ``float`` and ``str`` (a Double node written with ``1`` hands back an integer). The
|
|
1090
|
+
field decides the type. A value the field cannot hold is left as it came, for the guard to
|
|
1091
|
+
refuse by name.
|
|
1092
|
+
"""
|
|
1093
|
+
if is_byte_container(field_type):
|
|
1094
|
+
return bytes(value) if isinstance(value, (bytes, bytearray, list)) else value
|
|
1095
|
+
if isinstance(field_type, (ArrayType, SequenceType)):
|
|
1096
|
+
if not isinstance(value, (list, tuple)):
|
|
1097
|
+
return value
|
|
1098
|
+
return tuple(_narrowed_scalar(each, field_type.element) for each in value)
|
|
1099
|
+
return _narrowed_scalar(value, field_type)
|
|
1100
|
+
|
|
1101
|
+
|
|
1102
|
+
def _narrowed_scalar(value: object, element: ElementType) -> object:
|
|
1103
|
+
"""Return one scalar as exactly the Python type its ROS2 element type is, where it can be."""
|
|
1104
|
+
match element:
|
|
1105
|
+
case PrimitiveType(name=name) if name in _INTEGERS:
|
|
1106
|
+
return int(value) if isinstance(value, int) and not isinstance(value, bool) else value # type: ignore[arg-type]
|
|
1107
|
+
case PrimitiveType(name="bool"):
|
|
1108
|
+
return bool(value) if isinstance(value, (bool, int)) else value
|
|
1109
|
+
case PrimitiveType(name="float32" | "float64"):
|
|
1110
|
+
return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else value
|
|
1111
|
+
case PrimitiveType() | StringType():
|
|
1112
|
+
return str(value) if isinstance(value, str) else value
|
|
1113
|
+
case _:
|
|
1114
|
+
return value
|
|
1115
|
+
|
|
1116
|
+
|
|
1117
|
+
_VARIANT_TYPES: Final[Mapping[PrimitiveName, ua.VariantType]] = {
|
|
1118
|
+
"bool": ua.VariantType.Boolean,
|
|
1119
|
+
"byte": ua.VariantType.Byte,
|
|
1120
|
+
# ROS2 `char` and `wchar` arrive as Python `str`.
|
|
1121
|
+
"char": ua.VariantType.String,
|
|
1122
|
+
"wchar": ua.VariantType.String,
|
|
1123
|
+
"float32": ua.VariantType.Float,
|
|
1124
|
+
"float64": ua.VariantType.Double,
|
|
1125
|
+
"int8": ua.VariantType.SByte,
|
|
1126
|
+
"int16": ua.VariantType.Int16,
|
|
1127
|
+
"int32": ua.VariantType.Int32,
|
|
1128
|
+
"int64": ua.VariantType.Int64,
|
|
1129
|
+
"uint8": ua.VariantType.Byte,
|
|
1130
|
+
"uint16": ua.VariantType.UInt16,
|
|
1131
|
+
"uint32": ua.VariantType.UInt32,
|
|
1132
|
+
"uint64": ua.VariantType.UInt64,
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
_INTEGERS: Final[frozenset[str]] = frozenset(INTEGER_RANGES)
|
|
1136
|
+
"""The primitive names whose Python type is ``int``, taken from the guard's table."""
|
|
1137
|
+
|
|
1138
|
+
_ZEROS: Final[Mapping[ua.VariantType, object]] = {
|
|
1139
|
+
ua.VariantType.Boolean: False,
|
|
1140
|
+
ua.VariantType.String: "",
|
|
1141
|
+
ua.VariantType.Float: 0.0,
|
|
1142
|
+
ua.VariantType.Double: 0.0,
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def ua_shape(field_type: FieldType) -> tuple[object, ua.VariantType]:
|
|
1147
|
+
"""Return the value one modelled ROS2 field boots with, and the OPC UA type it carries.
|
|
1148
|
+
|
|
1149
|
+
Public because a declared ROS2 parameter type is shaped here too
|
|
1150
|
+
(:attr:`opensmi.ros2.runtime.parameters.ParameterType.field_type`,
|
|
1151
|
+
:func:`opensmi.ros2.server.parameters.ua_parameter_shape`), so one table decides the mapping.
|
|
1152
|
+
"""
|
|
1153
|
+
if is_byte_container(field_type):
|
|
1154
|
+
return b"", ua.VariantType.ByteString
|
|
1155
|
+
variant_type = _element_variant_type(element_of(field_type))
|
|
1156
|
+
zero = _ZEROS.get(variant_type, 0)
|
|
1157
|
+
match field_type:
|
|
1158
|
+
case ArrayType(length=length):
|
|
1159
|
+
# A fixed-size array arrives with its elements, so it boots with as many.
|
|
1160
|
+
return [zero] * length, variant_type
|
|
1161
|
+
case SequenceType():
|
|
1162
|
+
return [], variant_type
|
|
1163
|
+
case _:
|
|
1164
|
+
return zero, variant_type
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
def _element_variant_type(element: ElementType) -> ua.VariantType:
|
|
1168
|
+
"""Return the OPC UA type of a scalar, or of what a container holds."""
|
|
1169
|
+
match element:
|
|
1170
|
+
case PrimitiveType(name=name):
|
|
1171
|
+
return _VARIANT_TYPES[name]
|
|
1172
|
+
case StringType():
|
|
1173
|
+
return ua.VariantType.String
|
|
1174
|
+
case NestedType(): # pragma: no cover - refused before it is reached
|
|
1175
|
+
message = f"a message field cannot render as a variable: {element.type_name}"
|
|
1176
|
+
raise UnprojectableFieldError(message)
|