OpenSMI-ROS2 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. opensmi/ros2/__init__.py +89 -0
  2. opensmi/ros2/__main__.py +11 -0
  3. opensmi/ros2/cli.py +143 -0
  4. opensmi/ros2/py.typed +0 -0
  5. opensmi/ros2/runtime/__init__.py +67 -0
  6. opensmi/ros2/runtime/_decode.py +101 -0
  7. opensmi/ros2/runtime/_encode.py +102 -0
  8. opensmi/ros2/runtime/_parser.py +147 -0
  9. opensmi/ros2/runtime/errors.py +141 -0
  10. opensmi/ros2/runtime/goal.py +232 -0
  11. opensmi/ros2/runtime/graph.py +288 -0
  12. opensmi/ros2/runtime/guard.py +213 -0
  13. opensmi/ros2/runtime/interface.py +140 -0
  14. opensmi/ros2/runtime/messages/__init__.py +503 -0
  15. opensmi/ros2/runtime/messages/industrial_msgs.py +62 -0
  16. opensmi/ros2/runtime/messages/industrial_msgs.pyi +159 -0
  17. opensmi/ros2/runtime/messages/motoros2_interfaces.py +79 -0
  18. opensmi/ros2/runtime/messages/motoros2_interfaces.pyi +307 -0
  19. opensmi/ros2/runtime/messages/neo_msgs2.py +55 -0
  20. opensmi/ros2/runtime/messages/neo_msgs2.pyi +138 -0
  21. opensmi/ros2/runtime/messages/neo_srvs2.py +72 -0
  22. opensmi/ros2/runtime/messages/neo_srvs2.pyi +224 -0
  23. opensmi/ros2/runtime/outcomes.py +103 -0
  24. opensmi/ros2/runtime/parameters.py +723 -0
  25. opensmi/ros2/runtime/publisher.py +125 -0
  26. opensmi/ros2/runtime/qos.py +394 -0
  27. opensmi/ros2/runtime/runtime.py +1171 -0
  28. opensmi/ros2/runtime/selection.py +150 -0
  29. opensmi/ros2/runtime/stamp.py +100 -0
  30. opensmi/ros2/runtime/subscription.py +354 -0
  31. opensmi/ros2/runtime/tf.py +714 -0
  32. opensmi/ros2/server/__init__.py +148 -0
  33. opensmi/ros2/server/access.py +109 -0
  34. opensmi/ros2/server/bindings/__init__.py +92 -0
  35. opensmi/ros2/server/bindings/_base.py +154 -0
  36. opensmi/ros2/server/bindings/action.py +133 -0
  37. opensmi/ros2/server/bindings/keyed.py +127 -0
  38. opensmi/ros2/server/bindings/lifecycle.py +131 -0
  39. opensmi/ros2/server/bindings/method.py +130 -0
  40. opensmi/ros2/server/bindings/monitoring.py +109 -0
  41. opensmi/ros2/server/bindings/parameter.py +133 -0
  42. opensmi/ros2/server/bindings/publisher.py +192 -0
  43. opensmi/ros2/server/bindings/registry.py +95 -0
  44. opensmi/ros2/server/bindings/tf.py +256 -0
  45. opensmi/ros2/server/browse_names.py +94 -0
  46. opensmi/ros2/server/component.py +334 -0
  47. opensmi/ros2/server/config.py +493 -0
  48. opensmi/ros2/server/containers.py +191 -0
  49. opensmi/ros2/server/drivers.py +421 -0
  50. opensmi/ros2/server/errors.py +159 -0
  51. opensmi/ros2/server/events.py +406 -0
  52. opensmi/ros2/server/introspection.py +850 -0
  53. opensmi/ros2/server/keyed.py +749 -0
  54. opensmi/ros2/server/lifecycle.py +238 -0
  55. opensmi/ros2/server/limits.py +66 -0
  56. opensmi/ros2/server/loader.py +977 -0
  57. opensmi/ros2/server/machine.py +225 -0
  58. opensmi/ros2/server/method.py +307 -0
  59. opensmi/ros2/server/mirror.py +582 -0
  60. opensmi/ros2/server/mutation.py +992 -0
  61. opensmi/ros2/server/nodesets/Opc.Ua.SmartFactory.ROS2.NodeSet2.xml +85 -0
  62. opensmi/ros2/server/nodesets/__init__.py +18 -0
  63. opensmi/ros2/server/nodesets/smart_factory_ros2.py +26 -0
  64. opensmi/ros2/server/parameters.py +704 -0
  65. opensmi/ros2/server/projection.py +1176 -0
  66. opensmi/ros2/server/projections/__init__.py +41 -0
  67. opensmi/ros2/server/projections/scope.py +222 -0
  68. opensmi/ros2/server/provenance.py +121 -0
  69. opensmi/ros2/server/publisher.py +781 -0
  70. opensmi/ros2/server/recipes.py +514 -0
  71. opensmi/ros2/server/required.py +633 -0
  72. opensmi/ros2/server/skill.py +363 -0
  73. opensmi/ros2/server/spatial.py +283 -0
  74. opensmi/ros2/server/startup.py +626 -0
  75. opensmi/ros2/server/status.py +107 -0
  76. opensmi/ros2/server/structures.py +135 -0
  77. opensmi/ros2/server/transforms/__init__.py +39 -0
  78. opensmi/ros2/server/transforms/conversions.py +58 -0
  79. opensmi/ros2/server/transforms/filing.py +340 -0
  80. opensmi/ros2/server/transforms/mirror.py +462 -0
  81. opensmi/ros2/server/transforms/outward.py +180 -0
  82. opensmi/ros2/server/transforms/records.py +195 -0
  83. opensmi/ros2/server/transforms/spatial.py +154 -0
  84. opensmi_ros2-0.1.0.dist-info/METADATA +183 -0
  85. opensmi_ros2-0.1.0.dist-info/RECORD +89 -0
  86. opensmi_ros2-0.1.0.dist-info/WHEEL +5 -0
  87. opensmi_ros2-0.1.0.dist-info/entry_points.txt +2 -0
  88. opensmi_ros2-0.1.0.dist-info/licenses/LICENSES/MIT.txt +18 -0
  89. opensmi_ros2-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,992 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The mutation chokepoint: the one place a Binding's nodes are made.
6
+
7
+ Declared Bindings create their nodes once at init and never move them. The three cases where the
8
+ address space grows at run time (graph-driven, client-driven and content-driven) all go
9
+ through here. This module renders a Projection's plan under an opensmi container
10
+ (:meth:`ROS2MutationMixin.render_plan`) and announces each batch as one ``GeneralModelChangeEvent``
11
+ (nothing is announced at init). Nodes are created and added to, never removed.
12
+
13
+ Structure is nesting. A message becomes one complex Variable whose value is the whole
14
+ structure, with a child Variable per field and a nested complex Variable per nested message, and a
15
+ group (a Binding, a ROS2 parameter namespace, a Keyed member) is a variable group. A message is
16
+ written once, at the root of its complex Variable, and opensmi brings the children in step. A plan
17
+ with a leaf no structure field can carry (a DateTime, say) renders its levels as variable groups of
18
+ plain Variables instead. Growth is capped, per Binding (:attr:`ROS2MutationMixin.mutation_node_cap`)
19
+ and per Machine (:attr:`ROS2MutationMixin.machine_mutation_node_cap`). Reaching a cap refuses the
20
+ whole addition and reports it as a BindingEvent. Caps count mutations only, not what a declaration
21
+ asks for at init.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ from dataclasses import dataclass
28
+ from datetime import UTC
29
+ from typing import TYPE_CHECKING, Any, Final
30
+
31
+ from asyncua import ua
32
+ from asyncua.common.structures104 import new_enum_field
33
+ from asyncua.ua.attribute_ids import AttributeIds
34
+ from asyncua.ua.object_ids import ObjectIds
35
+ from asyncua.ua.status_codes import StatusCodes
36
+ from asyncua.ua.uaerrors import BadNoMatch
37
+ from opensmi.core.nodesets import MachineryNodeIds
38
+ from opensmi.server import UaVariable
39
+ from opensmi.server.errors import TypeConflictError
40
+ from opensmi.server.mixins import MonitoringMixin
41
+ from opensmi.server.ua_variable_containers import UaVariableContainer
42
+
43
+ from opensmi.ros2.server.browse_names import pascal_case
44
+ from opensmi.ros2.server.errors import (
45
+ DeclarationError,
46
+ DuplicateProjectionError,
47
+ DuplicateVariableNameError,
48
+ UnprojectableFieldError,
49
+ )
50
+ from opensmi.ros2.server.events import ROS2EventsMixin, Severity
51
+ from opensmi.ros2.server.projection import (
52
+ EnumDataType,
53
+ NodeLevel,
54
+ PlanObject,
55
+ PlanVariable,
56
+ ProjectDataType,
57
+ StandardDataType,
58
+ curated_naming,
59
+ inner_levels,
60
+ level_datatypes,
61
+ level_value,
62
+ )
63
+ from opensmi.ros2.server.status import GOOD, status_value
64
+ from opensmi.ros2.server.structures import (
65
+ DuplicateStructureError,
66
+ structure_elements,
67
+ structure_instance,
68
+ )
69
+
70
+ if TYPE_CHECKING:
71
+ from collections.abc import Awaitable, Callable, Container, Iterable, Mapping, Sequence
72
+
73
+ from asyncua.common.node import Node
74
+
75
+ from opensmi.ros2.runtime.messages import Message
76
+ from opensmi.ros2.server.projection import NodePath, PlanDataType, PlanEntry
77
+
78
+ __all__ = [
79
+ "CAP_REACHED",
80
+ "NodeAddition",
81
+ "ROS2MutationMixin",
82
+ "RenderedPlan",
83
+ "add_plan_variable",
84
+ "ended",
85
+ "ensure_groups",
86
+ "require_unused_name",
87
+ ]
88
+
89
+ CAP_REACHED: Final = "NODE_CAP_REACHED"
90
+ """The BindingEvent code a refused addition carries, for a client that wants to know why."""
91
+
92
+ _NODE_ADDED: Final = ua.Byte(1)
93
+ """``ModelChangeStructureVerb.NodeAdded``, announced for every creation here."""
94
+
95
+ _UNKNOWN_LENGTH: Final = ua.UInt32(0)
96
+ """The ArrayDimensions entry every array variable publishes: length unknown."""
97
+
98
+ _ENUM_NAMESPACE: Final = 1
99
+ """The namespace enumeration DataTypes are minted into: the server's own."""
100
+
101
+ _STATUS: Final = "Status"
102
+ """The Machinery Monitoring sub-structure that references the item's state machines (OPC 40001-1 section 16.1)."""
103
+
104
+ _MACHINERY_STATE: Final = ("MachineryItemState", "MachineryOperationMode")
105
+ """The AddIns a ``Status`` group references, by their browse names below MachineryBuildingBlocks."""
106
+
107
+
108
+ @dataclass(frozen=True, slots=True, kw_only=True)
109
+ class NodeAddition:
110
+ """One plan's nodes to create in one container, on behalf of one Binding.
111
+
112
+ :ivar binding: The Binding these nodes belong to. The cap counts against it and a refusal's
113
+ BindingEvent names it.
114
+ :ivar path: The ROS2 topic, service, action or node path of that Binding.
115
+ :ivar container: The opensmi container the nodes are added to.
116
+ :ivar plan: What to create, as the Projection shaped it.
117
+ :ivar message_type: The ROS2 type the plan was shaped from, which names the root's DataType.
118
+ :ivar root: The name of the complex Variable the whole plan is rendered as, for a Binding's
119
+ message. Without it the plan's top-level fields are the container's own children.
120
+ :ivar member: A Keyed Binding's member as its browse name and DisplayName. The plan is then
121
+ rendered inside a new group of that name, a child of the container.
122
+ :ivar group: The Machinery Monitoring sub-structure the nodes go in, a FolderType Object in the
123
+ container that the first addition naming it creates. ``None`` adds to the container.
124
+ """
125
+
126
+ binding: str
127
+ path: str
128
+ container: UaVariableContainer
129
+ plan: tuple[PlanEntry, ...]
130
+ message_type: type[Message]
131
+ root: str | None = None
132
+ member: tuple[str, str] | None = None
133
+ group: str | None = None
134
+
135
+
136
+ def wire_value(entry: PlanVariable, value: object) -> object:
137
+ """Return a plan value in the form its variable stores.
138
+
139
+ An array of structures stores instances of the structure's dataclass. Other variables store
140
+ the value as is.
141
+
142
+ :raises ValueError: When the value for an array of structures is not a list.
143
+ """
144
+ if not isinstance(entry.datatype, type):
145
+ return value
146
+ structure = entry.datatype
147
+ if not isinstance(value, (list, tuple)):
148
+ message = f"{type(value).__name__} is not an array of {structure.__name__}"
149
+ raise ValueError(message) # noqa: TRY004
150
+ return [structure_instance(structure, each) for each in value] # pyright: ignore[reportArgumentType]
151
+
152
+
153
+ def plan_value(entry: PlanVariable, stored: object) -> object:
154
+ """Return what a variable stores in the form a projection builds a message from.
155
+
156
+ The inverse of :func:`wire_value`: an array of structures comes back as maps.
157
+
158
+ :raises ValueError: When an array of structures holds something else, which the write check
159
+ normally refuses first.
160
+ """
161
+ return structure_elements(entry.datatype, stored) if isinstance(entry.datatype, type) else stored
162
+
163
+
164
+ async def ensure_groups(container: UaVariableContainer, levels: Iterable[NodeLevel]) -> UaVariableContainer:
165
+ """Return the variable group at the end of a chain of levels, creating those that do not exist yet.
166
+
167
+ A level's name is its browse name and its display name the raw ROS2 name. A group two plans
168
+ share (a ROS2 parameter namespace) is created by the first and found by the second.
169
+ """
170
+ for level in levels:
171
+ if level.name in container.groups:
172
+ container = container.groups[level.name]
173
+ else:
174
+ display = None if level.display_name == level.name else level.display_name
175
+ container = await container.add_group(level.name, display_name=display)
176
+ return container
177
+
178
+
179
+ @dataclass(slots=True)
180
+ class _Plain:
181
+ """A plan entry rendered as a Variable of its own."""
182
+
183
+ variable: UaVariable[Any]
184
+ entry: PlanVariable
185
+
186
+
187
+ @dataclass(slots=True)
188
+ class _Complex:
189
+ """The leaves below one path rendered as a complex Variable, which holds their whole structure."""
190
+
191
+ variable: UaVariable[Any]
192
+ leaves: list[PlanVariable]
193
+ classes: Mapping[NodePath, type]
194
+ path: NodePath
195
+
196
+
197
+ class RenderedPlan:
198
+ """The nodes one plan became, written and read by the names the plan gave its entries.
199
+
200
+ A complex Variable takes all the values below it in one write, a plain one takes its own. The
201
+ values are the Projection's: a map from the plan's flat names (``PlanVariable.full_name``) to
202
+ the value of that entry, whole, since the structure is built from all of them.
203
+
204
+ :ivar entries: The plan entry behind each name.
205
+ """
206
+
207
+ def __init__(self, entries: Mapping[str, PlanVariable], parts: Sequence[_Plain | _Complex]) -> None:
208
+ """Remember what was created."""
209
+ self.entries = dict(entries)
210
+ self._parts = list(parts)
211
+
212
+ @property
213
+ def initial(self) -> dict[str, object]:
214
+ """Return the value each entry was created holding."""
215
+ return {name: entry.initial for name, entry in self.entries.items()}
216
+
217
+ async def write(self, values: Mapping[str, object], status: ua.StatusCode = GOOD) -> None:
218
+ """Write every node of the plan in one call, each with the status, from a map of all the values.
219
+
220
+ The value always travels with the status, because a status alone leaves the variant null.
221
+ The call is the server's own write service, so each node still goes through its access
222
+ control and write check, and all carry one SourceTimestamp. A node that refuses does not
223
+ keep the others from being written; the first refusal is raised once the call is done.
224
+
225
+ :raises KeyError: When an entry has no value.
226
+ :raises UaStatusCodeError: When a node refuses its value, with the first refusal's status.
227
+ """
228
+ if not self._parts:
229
+ return
230
+ stamp = ua.DateTime.now(UTC)
231
+ writes: list[ua.WriteValue] = []
232
+ for part in self._parts:
233
+ if isinstance(part, _Plain):
234
+ value = wire_value(part.entry, values[part.entry.full_name])
235
+ data = status_value(value, part.entry.variant_type, status)
236
+ else:
237
+ structure = level_value(part.leaves, part.classes, values, part.path)
238
+ data = status_value(structure, ua.VariantType.ExtensionObject, status)
239
+ data.SourceTimestamp = stamp
240
+ write = ua.WriteValue()
241
+ write.NodeId = part.variable.ua_node.nodeid
242
+ write.AttributeId = AttributeIds.Value
243
+ write.Value = data
244
+ writes.append(write)
245
+ results = await self._parts[0].variable.ua_node.session.write(ua.WriteParameters(writes))
246
+ for result in results:
247
+ result.check()
248
+
249
+ async def read(self) -> dict[str, object]:
250
+ """Return what the nodes hold, by the plan's names, in the form a projection builds a message from.
251
+
252
+ :raises ValueError: When an array of structures holds something that is not one.
253
+ """
254
+ values: dict[str, object] = {}
255
+ for part in self._parts:
256
+ if isinstance(part, _Plain):
257
+ values[part.entry.full_name] = plan_value(part.entry, await part.variable.read())
258
+ continue
259
+ structure = await part.variable.read()
260
+ for leaf in part.leaves:
261
+ value: Any = structure
262
+ for field_name in leaf.display_names[len(part.path) :]:
263
+ value = getattr(value, field_name)
264
+ values[leaf.full_name] = plan_value(leaf, value)
265
+ return values
266
+
267
+
268
+ async def _add(container: UaVariableContainer, name: str, variable: UaVariable[Any]) -> None:
269
+ """Add a variable to a container, leaving nothing registered when that fails.
270
+
271
+ opensmi files a variable before creating its node, so a failed add would leave a node-less
272
+ variable that breaks later iteration, and would replace what the name held. Both are undone.
273
+ """
274
+ # Not a dict.get: an opensmi container answers [] and `in`, and has no get.
275
+ previous = container[name] if name in container else None # noqa: SIM401
276
+ try:
277
+ await container.add(variable)
278
+ except BaseException:
279
+ if previous is None:
280
+ delattr(container, name)
281
+ else:
282
+ setattr(container, name, previous)
283
+ raise
284
+
285
+
286
+ async def add_plan_variable(
287
+ container: UaVariableContainer,
288
+ name: str,
289
+ entry: PlanVariable,
290
+ datatype: ua.NodeId | None,
291
+ *,
292
+ writable: bool = False,
293
+ write_check: Callable[[Any], Awaitable[None]] | None = None,
294
+ unit: str | None = None,
295
+ value_range: tuple[float, float] | None = None,
296
+ ) -> UaVariable[Any]:
297
+ """Turn one plan entry into an opensmi ``UaVariable``, add it to a container, and type it.
298
+
299
+ This is the one place DataType, ValueRank and ArrayDimensions of a plain Variable are decided.
300
+ The variable is created with an explicit ``Variant`` (an empty sequence implies no type, and
301
+ opensmi writes later values with the initial ``VariantType``) and with these attributes:
302
+
303
+ * ValueRank ``OneDimension`` for an array, ``Scalar`` otherwise.
304
+ * ArrayDimensions ``[0]`` for an array (length unknown), written after the add since opensmi
305
+ has no parameter for it. A bounded ROS2 sequence publishes no bound.
306
+ * DataType: the plan's own, else the built-in type of the variant type. opensmi refuses one
307
+ on a variable with a unit (an ``AnalogUnitRangeType``), so that one is written after the add.
308
+
309
+ An array of structures (plan DataType a structure class) is created empty, with the
310
+ resolved DataType. Its write check refuses with ``BadTypeMismatch`` a value that is not an
311
+ array of that structure, then runs the caller's ``write_check``.
312
+
313
+ A failed add leaves nothing registered: the variable is removed from the container again and
314
+ any variable it replaced is put back. The attribute writes pass no write check.
315
+
316
+ :param container: The opensmi container to add the variable to.
317
+ :param name: The variable's BrowseName.
318
+ :param entry: The plan entry it is made from. Its DisplayName is the raw ROS2 name.
319
+ :param datatype: The DataType the plan names, resolved on this server, or ``None``. Required
320
+ for an array of structures; its namespace index is the structure's encoding namespace.
321
+ :param writable: Whether a client may write it.
322
+ :param write_check: An async check opensmi awaits before storing a written value.
323
+ :param unit: The engineering unit's symbol, for a variable that is not a ROS2 field. opensmi
324
+ requires a range with it.
325
+ :param value_range: The bounds opensmi publishes as an ``EURange`` and refuses a write outside.
326
+
327
+ :raises DeclarationError: When the plan names a structure for something that is not an array,
328
+ or no resolved DataType comes with it.
329
+ """
330
+ structure = entry.datatype if isinstance(entry.datatype, type) else None
331
+ builtin = ua.NodeId(ua.Int32(entry.variant_type.value))
332
+ if structure is not None:
333
+ if datatype is None or not entry.is_array:
334
+ message = (
335
+ f"the variable {name!r} names the structure {structure.__name__} and must be an array "
336
+ f"of it with the DataType resolved; a repeated message is rendered that way"
337
+ )
338
+ raise DeclarationError(message)
339
+ write_check = _structure_write_check(lambda: variable, name, structure, write_check)
340
+ options: dict[str, Any] = {
341
+ "name": name,
342
+ "display_name": entry.display if entry.display not in ("", name) else None,
343
+ "writable": writable,
344
+ "write_check_callback": write_check,
345
+ "unit": unit,
346
+ "range": value_range,
347
+ "ua_value_rank": ua.ValueRank.OneDimension if entry.is_array else ua.ValueRank.Scalar,
348
+ "ua_data_type": None if unit is not None else datatype or builtin,
349
+ # The ROS2 path, so a client can trace a node back to its field.
350
+ "description": entry.source or name,
351
+ }
352
+ variable: UaVariable[Any]
353
+ if structure is None:
354
+ variable = UaVariable(ua.Variant(entry.initial, entry.variant_type), **options)
355
+ else:
356
+ variable = UaVariable([], variable_type=structure, **options)
357
+ await _add(container, name, variable)
358
+ node = variable.ua_node
359
+ if entry.is_array:
360
+ await _write_unbounded(node)
361
+ if unit is not None:
362
+ await node.write_attribute(
363
+ AttributeIds.DataType,
364
+ ua.DataValue(ua.Variant(datatype or builtin, ua.VariantType.NodeId)),
365
+ )
366
+ return variable
367
+
368
+
369
+ async def _write_unbounded(node: Node) -> None:
370
+ """Publish an array's length as unknown. Through write_attribute, as asyncua types it as one int."""
371
+ await node.write_attribute(
372
+ AttributeIds.ArrayDimensions,
373
+ ua.DataValue(ua.Variant([_UNKNOWN_LENGTH], ua.VariantType.UInt32)),
374
+ )
375
+
376
+
377
+ async def _write_display_name(node: Node, text: str) -> None:
378
+ """Write a node's DisplayName, which is where the raw ROS2 name, key or frame id goes."""
379
+ await node.write_attribute(
380
+ AttributeIds.DisplayName,
381
+ ua.DataValue(ua.Variant(ua.LocalizedText(text), ua.VariantType.LocalizedText)),
382
+ )
383
+
384
+
385
+ def _structure_write_check(
386
+ variable: Callable[[], UaVariable[Any]],
387
+ name: str,
388
+ structure: type,
389
+ then: Callable[[Any], Awaitable[None]] | None,
390
+ *,
391
+ array: bool = True,
392
+ ) -> Callable[[Any], Awaitable[None]]:
393
+ """Return the write check of a structure, or of an array of one: the codec's, then the caller's.
394
+
395
+ It refuses with ``BadTypeMismatch`` a value that is not one (or an array of them), a null field,
396
+ or a fixed-size array of the wrong length, which the encoding does not publish.
397
+
398
+ :param variable: The variable the check belongs to, resolved lazily since the check is made
399
+ first.
400
+ :param array: Whether the variable holds an array of the structure and not one.
401
+ :param then: The caller's check, awaited when the value passed.
402
+ """
403
+
404
+ async def check(value: object) -> None:
405
+ try:
406
+ structure_elements(structure, value if array else [value])
407
+ except ValueError as error:
408
+ # A status code is all the client gets, so the reason is logged.
409
+ variable().logger.warning("Refused a write that is not the structure", variable=name, reason=str(error))
410
+ raise ua.UaStatusCodeError(StatusCodes.BadTypeMismatch) from error
411
+ if then is not None:
412
+ await then(value)
413
+
414
+ return check
415
+
416
+
417
+ class ROS2MutationMixin(MonitoringMixin, ROS2EventsMixin):
418
+ """The one door through which a machinery item's Monitoring may grow.
419
+
420
+ Mixed in ahead of opensmi's class. It brings opensmi's Monitoring container, where the
421
+ variables go, and extends the events mixin because a refused mutation is a BindingEvent.
422
+
423
+ :cvar mutation_node_cap: How many nodes one Binding may gain by mutation. A Component with a
424
+ larger Binding overrides it.
425
+ :cvar machine_mutation_node_cap: How many nodes one Machine may gain by mutation, across
426
+ every machinery item on it.
427
+ """
428
+
429
+ mutation_node_cap: int = 200
430
+ machine_mutation_node_cap: int = 2000
431
+
432
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
433
+ """Start out having mutated nothing, and pass every argument to opensmi."""
434
+ super().__init__(*args, **kwargs)
435
+ self._mutation_nodes: dict[str, int] = {}
436
+ self._machine_mutation_nodes = 0
437
+ # Read off the Machine: enumeration DataTypes live in the server's address space.
438
+ self._ros2_enum_datatypes: dict[str, tuple[EnumDataType, ua.NodeId]] = {}
439
+
440
+ @property
441
+ def mutation_node_counts(self) -> Mapping[str, int]:
442
+ """Return how many nodes each Binding on this item has gained by mutation."""
443
+ return dict(self._mutation_nodes)
444
+
445
+ @property
446
+ def ros2_enum_datatypes(self) -> dict[str, tuple[EnumDataType, ua.NodeId]]:
447
+ """Return the enumeration DataTypes minted on this Machine, by browse name.
448
+
449
+ Only the Machine's is read, by every item on it. Beside each NodeId is the definition it
450
+ was minted from, so one name asked for with two value sets is refused.
451
+ """
452
+ return self._ros2_enum_datatypes
453
+
454
+ async def mint_structure(self, datatype: type) -> ua.NodeId:
455
+ """Return the NodeId of a Structure DataType, creating it and what it names the first time.
456
+
457
+ Dependencies first, into the ROS2 nodeset's namespace, through
458
+ ``Server.ensure_structure`` of opensmi-server.
459
+
460
+ :raises DuplicateStructureError: When another description of the type is already on the
461
+ server. Nothing is created in that case.
462
+ """
463
+ try:
464
+ return await self.server.ensure_structure(datatype, namespace_index=self.ros2_namespace_index)
465
+ except TypeConflictError as conflict:
466
+ message = f"{self.name!r} describes {datatype.__name__} differently from another Component: {conflict}"
467
+ raise DuplicateStructureError(message) from conflict
468
+
469
+ @property
470
+ def machine_mutation_node_total(self) -> int:
471
+ """Return how many nodes this Machine has gained by mutation, across every item.
472
+
473
+ Only meaningful on a Machine, which is the item every other one reports to.
474
+ """
475
+ return self._machine_mutation_nodes
476
+
477
+ @property
478
+ def ros2_projection_qualifier(self) -> str:
479
+ """Return what distinguishes this item's minted DataTypes from another item's.
480
+
481
+ The Machine's name and the item's own, unique together in a server: two Machines in one
482
+ process may each have a Component called ``camera``, and DataTypes are server-wide.
483
+ """
484
+ item = self.name
485
+ machine = str(getattr(self.ros2_root_machine, "name", "") or "")
486
+ return item if machine in ("", item) else f"{machine}_{item}"
487
+
488
+ @property
489
+ def _byte_string_ceiling(self) -> int:
490
+ """Return how many bytes a bulk payload on this item may carry.
491
+
492
+ The Machine's. Zero (no ceiling) outside a Machine.
493
+ """
494
+ return int(getattr(self.ros2_root_machine, "ros2_byte_string_ceiling", 0))
495
+
496
+ def note_machine_mutation(self, nodes: int) -> None:
497
+ """Add to this Machine's mutation tally. Called by every item on it, including itself."""
498
+ self._machine_mutation_nodes += nodes
499
+
500
+ async def mutate_address_space(
501
+ self,
502
+ additions: Iterable[NodeAddition],
503
+ *,
504
+ at_init: bool = False,
505
+ ) -> list[RenderedPlan | None]:
506
+ """Create nodes, keep their names unique, and announce the change once for all.
507
+
508
+ :param additions: What to create.
509
+ :param at_init: Whether the address space is being built rather than changed. At init
510
+ nothing is announced and nothing counts against a cap.
511
+ :return: What each addition became, in order; ``None`` for one a cap refused, which created
512
+ nothing.
513
+ :raises DuplicateVariableNameError: When a name is already taken in its container.
514
+ :raises UnprojectableFieldError: When a plan carries an Object.
515
+ """
516
+ rendered: list[RenderedPlan | None] = []
517
+ changes: list[ua.ModelChangeStructureDataType] = []
518
+ for addition in additions:
519
+ planned = _planned_nodes(addition)
520
+ if not at_init and not await self._within_the_caps(
521
+ binding=addition.binding,
522
+ path=addition.path,
523
+ planned=planned,
524
+ ):
525
+ rendered.append(None)
526
+ continue
527
+ rendered.append(await self._create_addition(addition, changes))
528
+ if not at_init:
529
+ self._count(addition.binding, planned)
530
+ if not at_init:
531
+ await self.ros2_root_machine.emit_model_change(changes)
532
+ return rendered
533
+
534
+ async def _create_addition(
535
+ self,
536
+ addition: NodeAddition,
537
+ changes: list[ua.ModelChangeStructureDataType],
538
+ ) -> RenderedPlan:
539
+ """Create one addition: its Machinery group and member group if it has them, and the plan's nodes in it.
540
+
541
+ A Machinery group this addition created is removed again when the plan fails, so an unused
542
+ one never stays behind.
543
+ """
544
+ parent = addition.container
545
+ fresh = addition.group if addition.group is not None and addition.group not in parent.groups else None
546
+ if addition.group is not None:
547
+ parent = await self.machinery_group(parent, addition.group, changes)
548
+ container = parent
549
+ if addition.member is not None:
550
+ browse, display = addition.member
551
+ require_unused_name(browse, (parent,), "this Monitoring")
552
+ container = await parent.add_group(browse, display_name=display, runtime_keyed=True)
553
+ changes.append(_node_added(container.ua_node, ObjectIds.BaseObjectType))
554
+ try:
555
+ return await self.render_plan(
556
+ container,
557
+ addition.plan,
558
+ message_type=addition.message_type,
559
+ qualifier=f"{self.ros2_projection_qualifier}.{addition.binding}",
560
+ where="this Monitoring",
561
+ root=addition.root,
562
+ changes=changes,
563
+ )
564
+ except BaseException:
565
+ if addition.member is not None:
566
+ await parent.remove_group(addition.member[0])
567
+ if fresh is not None:
568
+ await self._drop_machinery_group(addition.container, fresh)
569
+ raise
570
+
571
+ async def machinery_group(
572
+ self,
573
+ container: UaVariableContainer,
574
+ name: str,
575
+ changes: list[ua.ModelChangeStructureDataType] | None = None,
576
+ ) -> UaVariableContainer:
577
+ """Return the Machinery Monitoring sub-structure of that name in a container, creating it the first time.
578
+
579
+ It is a FolderType Object shared by every Binding that names it. A ``Status`` group
580
+ references this item's MachineryItemState and MachineryOperationMode with HasComponent when
581
+ the item provides them, as OPC 40001-1 section 16.1 asks. A group is never removed once a
582
+ Binding is in it: nothing leaves the address space while the server runs.
583
+
584
+ :param changes: Where to record the group when it is made, for the model-change event.
585
+ """
586
+ if name in container.groups:
587
+ return container.groups[name]
588
+ group = await container.add_group(name, object_type=ua.NodeId(ua.Int32(ObjectIds.FolderType)))
589
+ if changes is not None:
590
+ changes.append(_node_added(group.ua_node, ObjectIds.FolderType))
591
+ if name == _STATUS:
592
+ for add_in in await self._machinery_state():
593
+ await group.ua_node.add_reference(add_in, ObjectIds.HasComponent)
594
+ return group
595
+
596
+ async def _drop_machinery_group(self, container: UaVariableContainer, name: str) -> None:
597
+ """Remove a Machinery group a failed addition made, keeping the AddIns a Status group references.
598
+
599
+ The removal is recursive and follows HasComponent, so the references go first.
600
+ """
601
+ if name == _STATUS:
602
+ status = container.groups[name].ua_node
603
+ for add_in in await self._machinery_state():
604
+ await status.delete_reference(add_in, ObjectIds.HasComponent)
605
+ await container.remove_group(name)
606
+
607
+ async def _machinery_state(self) -> list[Node]:
608
+ """Return the item's MachineryItemState and MachineryOperationMode, those it has.
609
+
610
+ opensmi files both AddIns under MachineryBuildingBlocks. An item without them has none.
611
+ """
612
+ machinery = self.server.ua_get_namespace_index(MachineryNodeIds)
613
+ try:
614
+ blocks = await self.ua_node.get_child(f"{machinery}:MachineryBuildingBlocks")
615
+ except BadNoMatch:
616
+ return []
617
+ found: list[Node] = []
618
+ for add_in in _MACHINERY_STATE:
619
+ try:
620
+ found.append(await blocks.get_child(f"{machinery}:{add_in}"))
621
+ except BadNoMatch:
622
+ continue
623
+ return found
624
+
625
+ async def mutate_address_space_with(
626
+ self,
627
+ *,
628
+ binding: str,
629
+ path: str,
630
+ nodes: int,
631
+ build: Callable[[], Awaitable[Sequence[tuple[Node, ua.NodeId | int]]]],
632
+ ) -> bool:
633
+ """Create nodes a caller builds itself, under the same caps and announcement.
634
+
635
+ Unlike :meth:`mutate_address_space`, the caller makes the nodes. This exists for OPC
636
+ 10000-210 Locations (opensmi's ``CartesianFrame``), which are not variables of a plan.
637
+
638
+ :param binding: The Binding these nodes belong to, which the cap counts against.
639
+ :param path: The ROS2 path of that Binding, for a refusal's BindingEvent.
640
+ :param nodes: How many nodes the build will create. The caller states it, since only the
641
+ caller knows.
642
+ :param build: What to create, answering each node made and the type it instantiated (what
643
+ a client filtering model changes by type reads).
644
+ :return: Whether it happened. ``False`` means a cap refused it and nothing was created.
645
+ """
646
+ if not await self._within_the_caps(binding=binding, path=path, planned=nodes):
647
+ return False
648
+ created = await build()
649
+ self._count(binding, nodes)
650
+ await self.ros2_root_machine.emit_model_change(
651
+ [_node_added(node, affected_type) for node, affected_type in created]
652
+ )
653
+ return True
654
+
655
+ async def _within_the_caps(self, *, binding: str, path: str, planned: int) -> bool:
656
+ """Return whether one addition fits, reporting it as a BindingEvent when it does not."""
657
+ machine = self.ros2_root_machine
658
+ on_binding = self._mutation_nodes.get(binding, 0) + planned
659
+ on_machine = machine.machine_mutation_node_total + planned
660
+ if on_binding <= self.mutation_node_cap and on_machine <= machine.machine_mutation_node_cap:
661
+ return True
662
+ limit = (
663
+ f"the Binding's cap of {self.mutation_node_cap}"
664
+ if on_binding > self.mutation_node_cap
665
+ else f"the Machine's cap of {machine.machine_mutation_node_cap}"
666
+ )
667
+ text = f"{binding} would grow the address space by {planned} nodes, past {limit}; none of them were created"
668
+ self.logger.error("Refused an address-space mutation at its cap", binding=binding, nodes=planned)
669
+ await self.emit_binding_event(
670
+ binding=binding,
671
+ path=path,
672
+ code=CAP_REACHED,
673
+ severity=Severity.ERROR,
674
+ text=text,
675
+ )
676
+ return False
677
+
678
+ def _count(self, binding: str, nodes: int) -> None:
679
+ """Add one addition's nodes to this Binding's tally and to the Machine's."""
680
+ self._mutation_nodes[binding] = self._mutation_nodes.get(binding, 0) + nodes
681
+ self.ros2_root_machine.note_machine_mutation(nodes)
682
+
683
+ async def render_plan(
684
+ self,
685
+ container: UaVariableContainer,
686
+ plan: Sequence[PlanEntry],
687
+ *,
688
+ message_type: type[Message],
689
+ qualifier: str,
690
+ where: str,
691
+ root: str | None = None,
692
+ writable: bool = False,
693
+ changes: list[ua.ModelChangeStructureDataType] | None = None,
694
+ ) -> RenderedPlan:
695
+ """Create the nodes of one plan in a container, and return how to write them.
696
+
697
+ With ``root`` the whole message is one complex Variable of that name. Without it, each
698
+ top-level field is a child of the container, and a nested message a complex Variable. A
699
+ complex Variable carries the structure of its level, minted here. A plan with a
700
+ leaf that no structure field can carry (a DateTime) is rendered with variable groups for
701
+ its levels and plain Variables for its leaves, so it keeps its names and loses only the
702
+ atomic read. Every name is checked before any node is made.
703
+
704
+ :param container: The opensmi container the nodes are added to.
705
+ :param plan: What to create.
706
+ :param message_type: The ROS2 type the plan was shaped from.
707
+ :param qualifier: What names the structures of curated levels, such as ``Platform.Odom``.
708
+ :param where: How a refusal names the container, from a reader's side.
709
+ :param root: The name of the complex Variable the whole plan is rendered as.
710
+ :param writable: Whether a client may write the Variables.
711
+ :param changes: Where to record each node made, for the model-change event.
712
+ :raises UnprojectableFieldError: When an entry is an Object or has no name.
713
+ :raises DuplicateVariableNameError: When a name is already taken in the container.
714
+ """
715
+ leaves, plains, subtrees = _split(plan, root, where)
716
+ naming = curated_naming(qualifier)
717
+ names = [name for name, _ in plains] + list(subtrees)
718
+ for name in names:
719
+ require_unused_name(name, (container,), where)
720
+ parts: list[_Plain | _Complex] = []
721
+ for name, entry in plains:
722
+ variable = await add_plan_variable(
723
+ container,
724
+ name,
725
+ entry,
726
+ await self.resolve_plan_datatype(entry.datatype),
727
+ writable=writable,
728
+ )
729
+ parts.append(_Plain(variable, entry))
730
+ _record(changes, variable)
731
+ for name, below in subtrees.items():
732
+ path: NodePath = () if root is not None else (name,)
733
+ try:
734
+ classes = level_datatypes(below, message_type, naming)
735
+ except UnprojectableFieldError:
736
+ parts += await self._render_groups(container, name, below, root=root, writable=writable)
737
+ continue
738
+ level = None if root is not None else below[0].above[0]
739
+ parts.append(
740
+ await self._render_structure(
741
+ container,
742
+ name,
743
+ below,
744
+ classes,
745
+ path,
746
+ display=name if level is None else level.display_name,
747
+ description=(message_type if level is None else level.message or message_type).ros2.type_name,
748
+ writable=writable,
749
+ changes=changes,
750
+ )
751
+ )
752
+ return RenderedPlan({entry.full_name: entry for entry in leaves}, parts)
753
+
754
+ async def _render_structure(
755
+ self,
756
+ container: UaVariableContainer,
757
+ name: str,
758
+ leaves: list[PlanVariable],
759
+ classes: Mapping[NodePath, type],
760
+ path: NodePath,
761
+ *,
762
+ display: str,
763
+ description: str,
764
+ writable: bool,
765
+ changes: list[ua.ModelChangeStructureDataType] | None,
766
+ ) -> _Complex:
767
+ """Create the complex Variable of the structure at one path, holding its initial value."""
768
+ _require_derived_names(name, leaves, path)
769
+ structure = classes[path]
770
+ datatype = await self.mint_structure(structure)
771
+ initial = level_value(leaves, classes, {leaf.full_name: leaf.initial for leaf in leaves}, path)
772
+ variable: UaVariable[Any] = UaVariable(
773
+ initial,
774
+ name=name,
775
+ display_name=None if display == name else display,
776
+ writable=writable,
777
+ write_check_callback=_structure_write_check(lambda: variable, name, structure, None, array=False),
778
+ ua_data_type=datatype,
779
+ description=description,
780
+ )
781
+ await _add(container, name, variable)
782
+ _record(changes, variable)
783
+ for leaf in leaves:
784
+ child = variable
785
+ for part in leaf.node_path[len(path) :]:
786
+ child = child[part]
787
+ # What opensmi cannot know about a field: the ROS2 path, and a DataType finer than its variant type.
788
+ if leaf.source:
789
+ await child.write_description(leaf.source)
790
+ if leaf.is_array:
791
+ await _write_unbounded(child.ua_node)
792
+ if leaf.datatype is not None and not isinstance(leaf.datatype, type):
793
+ await child.ua_node.write_attribute(
794
+ AttributeIds.DataType,
795
+ ua.DataValue(
796
+ ua.Variant(await self.resolve_plan_datatype(leaf.datatype), ua.VariantType.NodeId),
797
+ ),
798
+ )
799
+ return _Complex(variable, leaves, classes, path)
800
+
801
+ async def _render_groups(
802
+ self,
803
+ container: UaVariableContainer,
804
+ name: str,
805
+ leaves: list[PlanVariable],
806
+ *,
807
+ root: str | None,
808
+ writable: bool,
809
+ ) -> list[_Plain]:
810
+ """Render a subtree no DataType can describe: groups for its levels, plain Variables for its leaves."""
811
+ parts: list[_Plain] = []
812
+ top = [] if root is None else [NodeLevel(name=name, display_name=name, group=True)]
813
+ for leaf in leaves:
814
+ group = await ensure_groups(container, [*top, *leaf.above])
815
+ variable = await add_plan_variable(
816
+ group,
817
+ leaf.name,
818
+ leaf,
819
+ await self.resolve_plan_datatype(leaf.datatype),
820
+ writable=writable,
821
+ )
822
+ parts.append(_Plain(variable, leaf))
823
+ return parts
824
+
825
+ async def resolve_plan_datatype(self, datatype: PlanDataType | None) -> ua.NodeId | None:
826
+ """Return the NodeId a plan's DataType means on *this* server.
827
+
828
+ A plan is a pure value. The NodeId of this package's types depends on the namespace index
829
+ the server imported it at, and an enumeration has none until minted. Public because
830
+ Skills create their nodes outside the chokepoint but need their DataTypes minted here.
831
+ """
832
+ match datatype:
833
+ case None:
834
+ return None
835
+ case StandardDataType(identifier=identifier):
836
+ return ua.NodeId(ua.Int32(identifier))
837
+ case ProjectDataType(identifier=identifier):
838
+ return self.server.ua_get_node_id(identifier)
839
+ case EnumDataType():
840
+ return await self._minted_enum(datatype)
841
+ case type():
842
+ return await self.mint_structure(datatype)
843
+
844
+ async def _minted_enum(self, datatype: EnumDataType) -> ua.NodeId:
845
+ """Return the NodeId of an enumeration DataType, minting it the first time it is asked for.
846
+
847
+ Minted once per server and remembered on the Machine; the generated name is qualified by
848
+ its Component for that reason. It uses asyncua directly and not opensmi's
849
+ ``ensure_enum``, which needs an ``IntEnum`` numbered from zero, while ROS2 constants may
850
+ start at 1 or skip numbers.
851
+ """
852
+ minted: dict[str, tuple[EnumDataType, ua.NodeId]] = self.ros2_root_machine.ros2_enum_datatypes
853
+ known = minted.get(datatype.name)
854
+ if known is not None:
855
+ _require_one_definition_per_name(datatype, known[0])
856
+ return known[1]
857
+ definition = ua.EnumDefinition()
858
+ for value, label in datatype.values:
859
+ enum_field = new_enum_field(label)
860
+ enum_field.Value = ua.Int64(value)
861
+ definition.Fields.append(enum_field)
862
+ node = await self.server.ua_server.nodes.enum_data_type.add_data_type(_ENUM_NAMESPACE, datatype.name)
863
+ await node.write_data_type_definition(definition)
864
+ minted[datatype.name] = (datatype, node.nodeid)
865
+ return node.nodeid
866
+
867
+
868
+ def require_unused_name(name: str, taken: Iterable[Container[str]], where: str) -> None:
869
+ """Refuse a variable name something on this container has already claimed.
870
+
871
+ opensmi's container has no such check: it files a variable with ``setattr``, so a second one
872
+ would replace the first. Shared by the chokepoint and by Skills and Methods.
873
+
874
+ :param name: The browse name being claimed.
875
+ :param taken: Every place a name may already be recorded, tested in order.
876
+ :param where: What to call the container in the refusal, from a reader's point of view.
877
+ :raises DuplicateVariableNameError: When the name is taken.
878
+ """
879
+ # a container answers `in` for its variables only, its groups are in `groups`
880
+ if not any(name in each or name in getattr(each, "groups", ()) for each in taken):
881
+ return
882
+ message = f"the name {name!r} is already taken on {where}; the container would accept the collision silently"
883
+ raise DuplicateVariableNameError(message)
884
+
885
+
886
+ async def ended(task: asyncio.Task[None] | None) -> None:
887
+ """Cancel one task and wait for it, tolerating a task that has already finished."""
888
+ if task is None:
889
+ return
890
+ task.cancel()
891
+ await asyncio.gather(task, return_exceptions=True)
892
+
893
+
894
+ def _require_one_definition_per_name(wanted: EnumDataType, minted: EnumDataType) -> None:
895
+ """Refuse two value sets minted under one DataType name.
896
+
897
+ Reachable only when two ROS2 types with the same last name part are curated on one Component.
898
+ Sharing the first definition would give a client another type's labels.
899
+
900
+ :raises DuplicateProjectionError: When the two do not agree.
901
+ """
902
+ if wanted == minted:
903
+ return
904
+ message = (
905
+ f"two Projections mint the DataType {wanted.name!r} with different values; curate one "
906
+ f"of them on a Component of its own, or make their entries agree"
907
+ )
908
+ raise DuplicateProjectionError(message)
909
+
910
+
911
+ def _split(
912
+ plan: Sequence[PlanEntry],
913
+ root: str | None,
914
+ where: str,
915
+ ) -> tuple[list[PlanVariable], list[tuple[str, PlanVariable]], dict[str, list[PlanVariable]]]:
916
+ """Sort a plan into its leaves, the entries that are Variables of their own, and the structures.
917
+
918
+ The entries are listed with the name their Variable takes; a structure by its top-level name,
919
+ which is ``root`` when there is one.
920
+
921
+ :raises UnprojectableFieldError: When an entry is an Object or has no name.
922
+ """
923
+ leaves: list[PlanVariable] = []
924
+ for entry in plan:
925
+ if isinstance(entry, PlanObject) or not (entry.node_path or root):
926
+ message = (
927
+ f"{where} renders {entry.name!r} as an Object or without a name, and a message "
928
+ f"nests as complex Variables, not as Objects"
929
+ )
930
+ raise UnprojectableFieldError(message)
931
+ leaves.append(entry)
932
+ plains: list[tuple[str, PlanVariable]] = []
933
+ subtrees: dict[str, list[PlanVariable]] = {}
934
+ if root is not None:
935
+ if len(leaves) == 1 and not leaves[0].node_path:
936
+ plains.append((root, leaves[0]))
937
+ else:
938
+ subtrees[root] = leaves
939
+ return leaves, plains, subtrees
940
+ for entry in leaves:
941
+ if len(entry.node_path) == 1:
942
+ plains.append((entry.name, entry))
943
+ else:
944
+ subtrees.setdefault(entry.node_path[0], []).append(entry)
945
+ return leaves, plains, subtrees
946
+
947
+
948
+ def _require_derived_names(root: str, leaves: Sequence[PlanVariable], path: NodePath) -> None:
949
+ """Refuse a plan whose names opensmi would not derive from its field names.
950
+
951
+ The children of a complex Variable are named by opensmi from the field names of the structure,
952
+ which are the DisplayNames: ``child_frame_id`` is ``ChildFrameId``. A name that is not already
953
+ spelled that way (a Projection that names an entry ``data``) would browse as another name than
954
+ the plan says, so it is refused instead of renamed silently.
955
+
956
+ :raises DeclarationError: When a name on a node path differs from the one opensmi derives.
957
+ """
958
+ for leaf in leaves:
959
+ for name, display in zip(leaf.node_path[len(path) :], leaf.display_names[len(path) :], strict=True):
960
+ derived = pascal_case(display.split("_"))
961
+ if derived != name:
962
+ message = (
963
+ f"{root!r} renders {leaf.source or leaf.full_name!r} as {name!r}, and opensmi names the child "
964
+ f"Variable of the field {display!r} {derived!r}; name the entry {derived!r}, "
965
+ f"and keep {display!r} as its display name"
966
+ )
967
+ raise DeclarationError(message)
968
+
969
+
970
+ def _planned_nodes(addition: NodeAddition) -> int:
971
+ """Return how many nodes one addition creates: its member group, its levels and its leaves."""
972
+ plan = [entry for entry in addition.plan if isinstance(entry, PlanVariable)]
973
+ levels = len(inner_levels(plan)) + (addition.root is not None) + (addition.member is not None)
974
+ return len(addition.plan) + levels
975
+
976
+
977
+ def _record(changes: list[ua.ModelChangeStructureDataType] | None, variable: UaVariable[Any]) -> None:
978
+ """Note a node made and the fields below it, for the model-change event."""
979
+ if changes is None:
980
+ return
981
+ changes.append(_node_added(variable.ua_node, ObjectIds.BaseDataVariableType))
982
+ for child in variable.children.values():
983
+ _record(changes, child)
984
+
985
+
986
+ def _node_added(node: Node, affected_type: ua.NodeId | int) -> ua.ModelChangeStructureDataType:
987
+ """Return the model change one created node is, with the type it was instantiated as."""
988
+ return ua.ModelChangeStructureDataType(
989
+ Affected=node.nodeid,
990
+ AffectedType=affected_type if isinstance(affected_type, ua.NodeId) else ua.NodeId(ua.Int32(affected_type)),
991
+ Verb=_NODE_ADDED,
992
+ )