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,514 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""The recipes: curating a ROS2 type is writing data, not code.
|
|
6
|
+
|
|
7
|
+
A Projection is three pure functions (:mod:`opensmi.ros2.server.projection`). A curation is a plain
|
|
8
|
+
data literal from a closed set, so which Projections exist is a list somebody reads:
|
|
9
|
+
|
|
10
|
+
.. code-block:: python
|
|
11
|
+
|
|
12
|
+
Default("nav_msgs/msg/Odometry") # walk it; curate nothing
|
|
13
|
+
Scalar("std_msgs/msg/Float64") # one value, one variable
|
|
14
|
+
Enum("sensor_msgs/msg/BatteryState", fields={"power_supply_status": {0: "Unknown"}})
|
|
15
|
+
Blob("nav_msgs/msg/OccupancyGrid", field="data") # one bulk byte string
|
|
16
|
+
Drop("nav_msgs/msg/Odometry", fields=("pose/covariance",), override=True)
|
|
17
|
+
|
|
18
|
+
:class:`Functions` is the escape hatch for a type that fits none of them. There is no Object recipe:
|
|
19
|
+
a message is already a browsable complex Variable, and the mutation chokepoint refuses
|
|
20
|
+
the Object verb by name.
|
|
21
|
+
|
|
22
|
+
Three rules hold for every class. Entries are keyed by type name alone: ``type_hash=`` records the
|
|
23
|
+
RIHS01 the entry was authored against so CI can report that a type moved, but it never selects an
|
|
24
|
+
entry. Registration is explicit, through
|
|
25
|
+
:meth:`~opensmi.ros2.server.projection.ProjectionRegistry.extended`, and a second entry for one
|
|
26
|
+
type is fatal unless it says ``override=True``. There is no entry-point discovery. Invertibility is
|
|
27
|
+
derived from the recipe, never a keyword: the walk always inverts, and the escape hatch
|
|
28
|
+
inverts only if given ``encode=``. ``Default(type_name, override=True)`` turns curation off for
|
|
29
|
+
that type only; a Projection nested inside still applies.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import struct
|
|
35
|
+
from collections.abc import Collection, Mapping
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
from typing import TYPE_CHECKING, Final
|
|
38
|
+
|
|
39
|
+
from asyncua import ua
|
|
40
|
+
|
|
41
|
+
from opensmi.ros2.runtime.guard import INTEGER_RANGES
|
|
42
|
+
from opensmi.ros2.runtime.messages import ArrayType, PrimitiveType, SequenceType, is_byte_container
|
|
43
|
+
from opensmi.ros2.runtime.selection import field_paths
|
|
44
|
+
from opensmi.ros2.server.errors import NotInvertibleError, UnprojectableFieldError
|
|
45
|
+
from opensmi.ros2.server.events import SIGNED_BYTE_STRING_TYPE
|
|
46
|
+
from opensmi.ros2.server.projection import (
|
|
47
|
+
ANY_TYPE,
|
|
48
|
+
EnumDataType,
|
|
49
|
+
PlanEntry,
|
|
50
|
+
PlanVariable,
|
|
51
|
+
ProjectDataType,
|
|
52
|
+
Projection,
|
|
53
|
+
ProjectionContext,
|
|
54
|
+
ProjectionRegistry,
|
|
55
|
+
StandardDataType,
|
|
56
|
+
browse_name_of,
|
|
57
|
+
generic_decode,
|
|
58
|
+
generic_encode,
|
|
59
|
+
generic_shape,
|
|
60
|
+
ros2_value,
|
|
61
|
+
ua_value,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if TYPE_CHECKING:
|
|
65
|
+
from opensmi.ros2.runtime.messages import FieldDescription, FieldType, Message
|
|
66
|
+
from opensmi.ros2.server.projection import DecodeFunction, EncodeFunction, ShapeFunction
|
|
67
|
+
|
|
68
|
+
__all__ = ["GENERIC", "GENERIC_REGISTRY", "Blob", "Default", "Drop", "Enum", "Functions", "Scalar"]
|
|
69
|
+
|
|
70
|
+
_PACKED: Final[Mapping[str, str]] = {
|
|
71
|
+
"bool": "?",
|
|
72
|
+
"byte": "B",
|
|
73
|
+
"uint8": "B",
|
|
74
|
+
"int8": "b",
|
|
75
|
+
"int16": "h",
|
|
76
|
+
"uint16": "H",
|
|
77
|
+
"int32": "i",
|
|
78
|
+
"uint32": "I",
|
|
79
|
+
"int64": "q",
|
|
80
|
+
"uint64": "Q",
|
|
81
|
+
"float32": "f",
|
|
82
|
+
"float64": "d",
|
|
83
|
+
}
|
|
84
|
+
"""The ``struct`` code of each fixed-width ROS2 primitive.
|
|
85
|
+
|
|
86
|
+
``char`` and ``wchar`` are absent: they cross as Python ``str`` and have no packable width.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
_SIGNED: Final[frozenset[str]] = frozenset({"int8", "int16", "int32", "int64"})
|
|
90
|
+
"""Which element types make a packed buffer a ``SignedByteString`` rather than a ``ByteString``.
|
|
91
|
+
|
|
92
|
+
Two's-complement integers only. A float buffer keeps the plain ``ByteString``.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
_INTEGERS: Final = frozenset(INTEGER_RANGES)
|
|
96
|
+
"""Which field types can carry an enumeration: one whole number, of any ROS2 width."""
|
|
97
|
+
|
|
98
|
+
_LITTLE_ENDIAN: Final = "<"
|
|
99
|
+
"""Byte order, fixed because a client is not necessarily on this host."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
103
|
+
class Default(Projection):
|
|
104
|
+
"""The generic field-walk, as an ordinary entry.
|
|
105
|
+
|
|
106
|
+
Registered for one type, it disables curation for that type only. Registered for
|
|
107
|
+
:data:`~opensmi.ros2.server.projection.ANY_TYPE` it is :data:`GENERIC`, the entry that matches
|
|
108
|
+
last, so the engine needs no fallback branch.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
112
|
+
"""Render the type field by field, one flat variable per leaf."""
|
|
113
|
+
return generic_shape(message_type, context)
|
|
114
|
+
|
|
115
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
116
|
+
"""Read one payload into the names the walk created."""
|
|
117
|
+
return generic_decode(message, context)
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def inverse(self) -> EncodeFunction | None:
|
|
121
|
+
"""Return the walk's inverse, which it always has."""
|
|
122
|
+
return generic_encode
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
GENERIC: Final = Default(ANY_TYPE)
|
|
126
|
+
"""The generic field-walk, as the entry that matches last."""
|
|
127
|
+
|
|
128
|
+
GENERIC_REGISTRY: Final = ProjectionRegistry(entries=(GENERIC,))
|
|
129
|
+
"""A registry that curates nothing. :data:`opensmi.ros2.server.projections.DEFAULT_REGISTRY` extends it."""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
133
|
+
class Scalar(Projection):
|
|
134
|
+
"""A message that carries one value, rendered as that one variable.
|
|
135
|
+
|
|
136
|
+
``std_msgs/msg/Float64`` on ``/battery_voltage`` browses as ``battery_voltage`` instead of
|
|
137
|
+
``battery_voltage_data``. The message must have exactly one leaf field, and anything else is
|
|
138
|
+
refused at init: a second field would have to be filled from a default on the way back, which
|
|
139
|
+
is refused.
|
|
140
|
+
|
|
141
|
+
:ivar variant_type: The OPC UA type to carry, where the field's own is not the one wanted.
|
|
142
|
+
:ivar datatype: What the value is, as a DataType identifier in namespace 0, or ``None``.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
variant_type: ua.VariantType | None = None
|
|
146
|
+
datatype: int | None = None
|
|
147
|
+
|
|
148
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
149
|
+
"""Return the one variable this message is, named for whatever contains it.
|
|
150
|
+
|
|
151
|
+
:raises UnprojectableFieldError: When the message does not carry exactly one value.
|
|
152
|
+
"""
|
|
153
|
+
self._only_field(message_type)
|
|
154
|
+
# Take the walk's variable and rename it, so the boot value and variant type stay in one place.
|
|
155
|
+
walked = [entry for entry in generic_shape(message_type, context) if isinstance(entry, PlanVariable)]
|
|
156
|
+
if not walked: # pragma: no cover (the parent skips a subtree the selection emptied)
|
|
157
|
+
return ()
|
|
158
|
+
(entry,) = walked
|
|
159
|
+
return (
|
|
160
|
+
PlanVariable(
|
|
161
|
+
name="",
|
|
162
|
+
source=entry.source,
|
|
163
|
+
initial=entry.initial,
|
|
164
|
+
variant_type=self.variant_type or entry.variant_type,
|
|
165
|
+
datatype=None if self.datatype is None else StandardDataType(identifier=self.datatype),
|
|
166
|
+
),
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
170
|
+
"""Return the one value, under the empty name the shape gave it."""
|
|
171
|
+
described = self._only_field(type(message))
|
|
172
|
+
return {"": ua_value(getattr(message, described.name))}
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def inverse(self) -> EncodeFunction | None:
|
|
176
|
+
"""Return the inverse, which a one-field message always has."""
|
|
177
|
+
return self._encode
|
|
178
|
+
|
|
179
|
+
def _encode(
|
|
180
|
+
self,
|
|
181
|
+
message_type: type[Message],
|
|
182
|
+
values: Mapping[str, object],
|
|
183
|
+
context: ProjectionContext,
|
|
184
|
+
) -> Message:
|
|
185
|
+
"""Put the one value back into the one field."""
|
|
186
|
+
described = self._only_field(message_type)
|
|
187
|
+
value = ros2_value(values[""], described.field_type)
|
|
188
|
+
return generic_encode(message_type, {}, context, {described.name: value})
|
|
189
|
+
|
|
190
|
+
def _only_field(self, message_type: type[Message]) -> FieldDescription:
|
|
191
|
+
"""Return the message's single leaf field.
|
|
192
|
+
|
|
193
|
+
:raises UnprojectableFieldError: When the message has more than one field, or when its
|
|
194
|
+
one field is another message.
|
|
195
|
+
"""
|
|
196
|
+
fields = message_type.ros2.fields
|
|
197
|
+
nested = message_type.ros2_nested
|
|
198
|
+
if len(fields) == 1 and fields[0].name not in nested:
|
|
199
|
+
return fields[0]
|
|
200
|
+
listed = ", ".join(described.name for described in fields) or "nothing"
|
|
201
|
+
message = (
|
|
202
|
+
f"Scalar renders a message that carries one value, and {message_type.ros2.type_name} "
|
|
203
|
+
f"carries {listed}; curate it with Drop, or let the walk have it"
|
|
204
|
+
)
|
|
205
|
+
raise UnprojectableFieldError(message)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
209
|
+
class Enum(Projection):
|
|
210
|
+
"""A message walked as usual, with named integer fields rendered as enumerations.
|
|
211
|
+
|
|
212
|
+
Naming the values of a ROS2 constant set mints a DataType the client can browse, instead of
|
|
213
|
+
leaving it a bare number whose meaning lives in a ``.msg`` file. The rest of the message is the
|
|
214
|
+
generic walk, and the number is what goes back on a write, so the recipe inverts.
|
|
215
|
+
|
|
216
|
+
:ivar fields: For each ROS2 field name, the label of each value it may carry. The keys are the
|
|
217
|
+
ROS2 constants themselves, so a set that starts at ``1`` or skips a number stays correct.
|
|
218
|
+
"""
|
|
219
|
+
|
|
220
|
+
fields: Mapping[str, Mapping[int, str]]
|
|
221
|
+
|
|
222
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
223
|
+
"""Walk the message, with an enumeration variable where a field was named."""
|
|
224
|
+
return generic_shape(message_type, context, self._overrides(message_type, context))
|
|
225
|
+
|
|
226
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
227
|
+
"""Read the payload as usual: an enumeration's value is the integer that was sent."""
|
|
228
|
+
return generic_decode(message, context)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def inverse(self) -> EncodeFunction | None:
|
|
232
|
+
"""Return the walk's inverse, which naming values does not take away."""
|
|
233
|
+
return generic_encode
|
|
234
|
+
|
|
235
|
+
def _overrides(self, message_type: type[Message], context: ProjectionContext) -> Mapping[str, PlanEntry]:
|
|
236
|
+
"""Return the enumeration variable of each named field."""
|
|
237
|
+
return {
|
|
238
|
+
name: PlanVariable(
|
|
239
|
+
name=name,
|
|
240
|
+
source=context.child(name).path,
|
|
241
|
+
initial=next(iter(values), 0),
|
|
242
|
+
# An OPC UA enumeration is an Int32 whatever the ROS2 width is.
|
|
243
|
+
variant_type=ua.VariantType.Int32,
|
|
244
|
+
datatype=EnumDataType(
|
|
245
|
+
name=self._datatype_name(context, name),
|
|
246
|
+
values=tuple(values.items()),
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
for name, values in self.fields.items()
|
|
250
|
+
if self._require_an_integer_field(message_type, name)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
def _datatype_name(self, context: ProjectionContext, field_name: str) -> str:
|
|
254
|
+
"""Return the DataType's browse name, qualified by the Component.
|
|
255
|
+
|
|
256
|
+
DataTypes live in the server-wide address space, while registries are per Component.
|
|
257
|
+
"""
|
|
258
|
+
local = self.type_name.rpartition("/")[2]
|
|
259
|
+
parts = (context.qualifier, local, field_name)
|
|
260
|
+
return "_".join(part for part in parts if part)
|
|
261
|
+
|
|
262
|
+
def _require_an_integer_field(self, message_type: type[Message], field_name: str) -> bool:
|
|
263
|
+
"""Return ``True`` for a field that can carry an enumeration, and refuse one that cannot.
|
|
264
|
+
|
|
265
|
+
:raises UnprojectableFieldError: When the field is absent, or is not a single integer.
|
|
266
|
+
"""
|
|
267
|
+
described = next((each for each in message_type.ros2.fields if each.name == field_name), None)
|
|
268
|
+
if described is not None and _scalar_name(described.field_type) in _INTEGERS:
|
|
269
|
+
return True
|
|
270
|
+
message = (
|
|
271
|
+
f"Enum names {field_name!r} on {message_type.ros2.type_name}, which is not a single "
|
|
272
|
+
f"integer field; an enumeration renders one number as one label"
|
|
273
|
+
)
|
|
274
|
+
raise UnprojectableFieldError(message)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
278
|
+
class Blob(Projection):
|
|
279
|
+
"""One fixed-width primitive array carried as a single byte string.
|
|
280
|
+
|
|
281
|
+
A million-cell grid as one UA array is a million Variants on the wire, and as one
|
|
282
|
+
``ByteString`` it is one buffer copy. The rest of the message is the generic walk. The element
|
|
283
|
+
type comes from the ROS2 definition, so ``int8[]``, ``uint8[]`` and ``float32[]`` need no
|
|
284
|
+
keyword. Signedness is published as a DataType, because a ``-1`` would otherwise reach a plain
|
|
285
|
+
``ByteString`` as ``0xFF``.
|
|
286
|
+
|
|
287
|
+
The recipe never transforms the bytes. Naming a ``datatype`` says what they are (a
|
|
288
|
+
``CompressedImage``'s ``data`` really is a JPEG), and then the round trip can no longer be
|
|
289
|
+
claimed for the author, so the Blob inverts only if an ``encode`` is supplied.
|
|
290
|
+
|
|
291
|
+
:ivar field: The ROS2 field to carry as bytes.
|
|
292
|
+
:ivar datatype: What the bytes are, as a DataType identifier in namespace 0
|
|
293
|
+
(``ua.ObjectIds.ImagePNG``), or ``None`` to publish the signedness derived from the
|
|
294
|
+
element type.
|
|
295
|
+
:ivar encode: A codec whose round trip the author claims. Supplying it is that claim.
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
field: str
|
|
299
|
+
datatype: int | None = None
|
|
300
|
+
encode: EncodeFunction | None = None
|
|
301
|
+
|
|
302
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
303
|
+
"""Walk the message, with the named field rendered as one byte string."""
|
|
304
|
+
described = self._packed_field(message_type)
|
|
305
|
+
return generic_shape(
|
|
306
|
+
message_type,
|
|
307
|
+
context,
|
|
308
|
+
{
|
|
309
|
+
self.field: PlanVariable(
|
|
310
|
+
name=self.field,
|
|
311
|
+
source=context.child(self.field).path,
|
|
312
|
+
initial=b"",
|
|
313
|
+
variant_type=ua.VariantType.ByteString,
|
|
314
|
+
datatype=self._datatype_of(described.field_type),
|
|
315
|
+
)
|
|
316
|
+
},
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
320
|
+
"""Read the payload as usual, with the named field packed into bytes and capped."""
|
|
321
|
+
described = self._packed_field(type(message))
|
|
322
|
+
if not context.child(self.field).included:
|
|
323
|
+
# Packing a buffer the selection removed would cost a copy per message for nothing.
|
|
324
|
+
return generic_decode(message, context)
|
|
325
|
+
packed = _pack(getattr(message, self.field), described.field_type)
|
|
326
|
+
return generic_decode(message, context, {self.field: _capped(packed, context.byte_string_ceiling)})
|
|
327
|
+
|
|
328
|
+
@property
|
|
329
|
+
def inverse(self) -> EncodeFunction | None:
|
|
330
|
+
"""Return the supplied codec, else byte identity; ``None`` when a ``datatype`` is named without a codec."""
|
|
331
|
+
if self.encode is not None:
|
|
332
|
+
return self.encode
|
|
333
|
+
return None if self.datatype is not None else self._encode
|
|
334
|
+
|
|
335
|
+
def _encode(
|
|
336
|
+
self,
|
|
337
|
+
message_type: type[Message],
|
|
338
|
+
values: Mapping[str, object],
|
|
339
|
+
context: ProjectionContext,
|
|
340
|
+
) -> Message:
|
|
341
|
+
"""Unpack the byte string back into the elements the field holds."""
|
|
342
|
+
described = self._packed_field(message_type)
|
|
343
|
+
written = _written(values, browse_name_of(context, self.field), message_type)
|
|
344
|
+
unpacked = _unpack(bytes(written) if isinstance(written, (bytes, bytearray)) else b"", described.field_type)
|
|
345
|
+
return generic_encode(message_type, values, context, {self.field: unpacked})
|
|
346
|
+
|
|
347
|
+
def _datatype_of(self, field_type: FieldType) -> StandardDataType | ProjectDataType | None:
|
|
348
|
+
"""Return what the variable's bytes say they are."""
|
|
349
|
+
if self.datatype is not None:
|
|
350
|
+
return StandardDataType(identifier=self.datatype)
|
|
351
|
+
element = _element_name(field_type)
|
|
352
|
+
return ProjectDataType(identifier=SIGNED_BYTE_STRING_TYPE) if element in _SIGNED else None
|
|
353
|
+
|
|
354
|
+
def _packed_field(self, message_type: type[Message]) -> FieldDescription:
|
|
355
|
+
"""Return the named field, having checked that it is a fixed-width primitive array.
|
|
356
|
+
|
|
357
|
+
:raises UnprojectableFieldError: When the field is absent, is not repeated, or holds
|
|
358
|
+
something with no fixed width (a string, or another message).
|
|
359
|
+
"""
|
|
360
|
+
described = next((each for each in message_type.ros2.fields if each.name == self.field), None)
|
|
361
|
+
if described is not None and _element_name(described.field_type) in _PACKED:
|
|
362
|
+
return described
|
|
363
|
+
message = (
|
|
364
|
+
f"Blob names {self.field!r} on {message_type.ros2.type_name}, which is not an array "
|
|
365
|
+
f"of a fixed-width primitive; only those have a byte string to be carried as"
|
|
366
|
+
)
|
|
367
|
+
raise UnprojectableFieldError(message)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
371
|
+
class Drop(Projection):
|
|
372
|
+
"""The generic walk with some fields taken out of it.
|
|
373
|
+
|
|
374
|
+
Dropping a path takes its whole subtree with it, as the declaration's own ``exclude`` does.
|
|
375
|
+
|
|
376
|
+
A Drop never inverts: its only inverse would fill the dropped fields with defaults,
|
|
377
|
+
and a covariance of zeros means perfectly certain in ROS2, not unknown.
|
|
378
|
+
|
|
379
|
+
:ivar fields: The ROS2 field paths to remove, relative to this type.
|
|
380
|
+
"""
|
|
381
|
+
|
|
382
|
+
fields: Collection[str]
|
|
383
|
+
|
|
384
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
385
|
+
"""Walk what is left of the message."""
|
|
386
|
+
return generic_shape(message_type, self._without(message_type, context))
|
|
387
|
+
|
|
388
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
389
|
+
"""Read what is left of the payload."""
|
|
390
|
+
return generic_decode(message, self._without(type(message), context))
|
|
391
|
+
|
|
392
|
+
def _without(self, message_type: type[Message], context: ProjectionContext) -> ProjectionContext:
|
|
393
|
+
"""Return the context with the dropped paths gone.
|
|
394
|
+
|
|
395
|
+
:raises UnprojectableFieldError: When a dropped path is not a path of this type.
|
|
396
|
+
"""
|
|
397
|
+
_require_known_paths("Drop", message_type, self.fields)
|
|
398
|
+
return context.without(self.fields)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
402
|
+
class Functions(Projection):
|
|
403
|
+
"""The escape hatch: a Projection written as the functions themselves.
|
|
404
|
+
|
|
405
|
+
For a type that fits no recipe. It is still keyed by type name and registered explicitly, and
|
|
406
|
+
it inverts only if given ``encode``.
|
|
407
|
+
|
|
408
|
+
:ivar shaped_by: What this type becomes at init.
|
|
409
|
+
:ivar decoded_by: What one payload writes.
|
|
410
|
+
:ivar encode: How a written value becomes a payload again, or ``None`` for a rendering that
|
|
411
|
+
cannot be published through.
|
|
412
|
+
"""
|
|
413
|
+
|
|
414
|
+
shaped_by: ShapeFunction
|
|
415
|
+
decoded_by: DecodeFunction
|
|
416
|
+
encode: EncodeFunction | None = None
|
|
417
|
+
|
|
418
|
+
def shape(self, message_type: type[Message], context: ProjectionContext) -> tuple[PlanEntry, ...]:
|
|
419
|
+
"""Return what the supplied shape function makes of this type."""
|
|
420
|
+
return self.shaped_by(message_type, context)
|
|
421
|
+
|
|
422
|
+
def decode(self, message: Message, context: ProjectionContext) -> Mapping[str, object]:
|
|
423
|
+
"""Return what the supplied decode function makes of one payload."""
|
|
424
|
+
return self.decoded_by(message, context)
|
|
425
|
+
|
|
426
|
+
@property
|
|
427
|
+
def inverse(self) -> EncodeFunction | None:
|
|
428
|
+
"""Return the inverse this entry was given."""
|
|
429
|
+
return self.encode
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _require_known_paths(recipe: str, message_type: type[Message], paths: Collection[str]) -> None:
|
|
433
|
+
"""Refuse a named path a type does not have, which is a typo rather than a choice.
|
|
434
|
+
|
|
435
|
+
:raises UnprojectableFieldError: When a named path is not a path of this type.
|
|
436
|
+
"""
|
|
437
|
+
known = set(field_paths(message_type))
|
|
438
|
+
unknown = [path for path in paths if path not in known]
|
|
439
|
+
if not unknown:
|
|
440
|
+
return
|
|
441
|
+
listed = ", ".join(repr(path) for path in sorted(unknown))
|
|
442
|
+
message = (
|
|
443
|
+
f"{recipe} names {listed} on {message_type.ros2.type_name}, which has no such field; "
|
|
444
|
+
f"its paths are {', '.join(sorted(known))}"
|
|
445
|
+
)
|
|
446
|
+
raise UnprojectableFieldError(message)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _written(values: Mapping[str, object], name: str, message_type: type[Message]) -> object:
|
|
450
|
+
"""Return what a client wrote to one variable of a plan, refusing a payload with a hole.
|
|
451
|
+
|
|
452
|
+
:raises NotInvertibleError: When the name carries no value, as in the walk: a field filled from
|
|
453
|
+
a default is a value nobody sent.
|
|
454
|
+
"""
|
|
455
|
+
if name not in values:
|
|
456
|
+
message = (
|
|
457
|
+
f"{message_type.ros2.type_name} cannot be built without a value for {name!r}; a "
|
|
458
|
+
f"field filled from a default is a value nobody sent"
|
|
459
|
+
)
|
|
460
|
+
raise NotInvertibleError(message)
|
|
461
|
+
return values[name]
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _element_name(field_type: FieldType) -> str:
|
|
465
|
+
"""Return the ``.msg`` spelling of what a container holds, or ``""`` for anything else."""
|
|
466
|
+
if isinstance(field_type, (ArrayType, SequenceType)) and isinstance(field_type.element, PrimitiveType):
|
|
467
|
+
return field_type.element.name
|
|
468
|
+
return ""
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _scalar_name(field_type: FieldType) -> str:
|
|
472
|
+
"""Return the ``.msg`` spelling of a single primitive field, or ``""`` for anything else."""
|
|
473
|
+
return field_type.name if isinstance(field_type, PrimitiveType) else ""
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _pack(value: object, field_type: FieldType) -> bytes:
|
|
477
|
+
"""Return one array field as the bytes its elements are.
|
|
478
|
+
|
|
479
|
+
A byte container already crossed as ``bytes``, so packing it is the identity.
|
|
480
|
+
"""
|
|
481
|
+
if isinstance(value, (bytes, bytearray)):
|
|
482
|
+
return bytes(value)
|
|
483
|
+
elements = tuple(value) if isinstance(value, (list, tuple)) else ()
|
|
484
|
+
code = _PACKED[_element_name(field_type)]
|
|
485
|
+
return struct.pack(f"{_LITTLE_ENDIAN}{len(elements)}{code}", *elements)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _unpack(data: bytes, field_type: FieldType) -> object:
|
|
489
|
+
"""Return the elements a byte string holds, in the shape the payload wants them.
|
|
490
|
+
|
|
491
|
+
:raises ValueError: When the byte string is not a whole number of elements. This is a client's
|
|
492
|
+
write, so it is refused per write and never fatal at init.
|
|
493
|
+
"""
|
|
494
|
+
if is_byte_container(field_type):
|
|
495
|
+
return data
|
|
496
|
+
code = _PACKED[_element_name(field_type)]
|
|
497
|
+
width = struct.calcsize(code)
|
|
498
|
+
if len(data) % width:
|
|
499
|
+
message = (
|
|
500
|
+
f"a byte string of {len(data)} bytes is not a whole number of "
|
|
501
|
+
f"{_element_name(field_type)} elements, which are {width} bytes each"
|
|
502
|
+
)
|
|
503
|
+
raise ValueError(message)
|
|
504
|
+
return struct.unpack(f"{_LITTLE_ENDIAN}{len(data) // width}{code}", data)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _capped(data: bytes, ceiling: int) -> bytes:
|
|
508
|
+
"""Return a bulk payload cut down to the transport's ceiling.
|
|
509
|
+
|
|
510
|
+
A byte string past the ceiling makes the write fail and the variable stop updating for every
|
|
511
|
+
client, so it is cut here instead. A client can compare the length against the capability
|
|
512
|
+
variable (:mod:`opensmi.ros2.server.limits`).
|
|
513
|
+
"""
|
|
514
|
+
return data if ceiling <= 0 or len(data) <= ceiling else data[:ceiling]
|