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,781 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""A published topic is a Skill: a client writes the fields, then starts the publishing.
|
|
6
|
+
|
|
7
|
+
The message fields are the Skill's Parameters, writable in any state, and nothing goes out while
|
|
8
|
+
they are written. ``Start`` reads them, builds the message and publishes it: the first tick of a
|
|
9
|
+
stream on a continuous Skill, the only publish on a finite one. ``Halt`` closes a stream. ``Reset``
|
|
10
|
+
clears the failure count and leaves the Parameters alone. There is no ``Suspend`` (opensmi keeps
|
|
11
|
+
running the handler through ``SUSPENDING``, so a paused stream would go on publishing) and no
|
|
12
|
+
Monitoring sibling: the echo of a topic we publish is our own message, so a readback would only
|
|
13
|
+
confirm the last value published. A consumer who wants to see the topic declares a
|
|
14
|
+
``MonitoringBinding`` on it. There is no FinalResultData either (it is optional in the SkillSet
|
|
15
|
+
model), since a publish has no result.
|
|
16
|
+
|
|
17
|
+
The trigger is the tick alone: there is no debounce, coalescing or dirty tracking. A finite push
|
|
18
|
+
has one publish, so any failure halts. A stream absorbs ``tolerated_failures`` consecutive ones, and
|
|
19
|
+
every failure fires a BindingEvent whether it was absorbed or not.
|
|
20
|
+
|
|
21
|
+
opensmi leaves a continuous Skill in ``Running`` when its handler returns, so the rate loop never
|
|
22
|
+
returns: every exit raises an ``OpenSmiRuntimeError``, which halts the Skill and reaches the
|
|
23
|
+
Component's Notification with its code. A stream exits when its tolerance for failed publishes is
|
|
24
|
+
spent, when the Lock it was started under ends (:data:`LOCK_ENDED`), and when a declared
|
|
25
|
+
``stale_after`` passes without a write (:data:`SETPOINT_STALE`), each with a BindingEvent of the same
|
|
26
|
+
code. ``Halt`` cancels the handler instead.
|
|
27
|
+
|
|
28
|
+
Access is a Skill's like any other: ``Start``, ``Halt`` and ``Reset`` need the Skill level
|
|
29
|
+
(``skill_access_level``) and the Machine's Lock, and ``Start`` also needs a completed startup. The
|
|
30
|
+
ParameterSet is built in :mod:`opensmi.ros2.server.containers`; the header stamp and the send-time
|
|
31
|
+
value guard are in :mod:`opensmi.ros2.runtime.publisher`.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import asyncio
|
|
37
|
+
import contextlib
|
|
38
|
+
import math
|
|
39
|
+
from collections.abc import Mapping
|
|
40
|
+
from dataclasses import replace
|
|
41
|
+
from datetime import UTC, datetime
|
|
42
|
+
from typing import TYPE_CHECKING, Any, ClassVar, Final, cast
|
|
43
|
+
|
|
44
|
+
from asyncua import ua
|
|
45
|
+
from asyncua.ua.attribute_ids import AttributeIds
|
|
46
|
+
from opensmi.core.errors import OpenSmiRuntimeError
|
|
47
|
+
from opensmi.core.nodesets import DiNodeIds
|
|
48
|
+
from opensmi.server import BaseMachineryItem, BaseSkill, ContinuousSkillLogicMixin, FiniteSkillLogicMixin
|
|
49
|
+
from opensmi.server.mixins import ParameterSetMixin, ParentMixin
|
|
50
|
+
|
|
51
|
+
from opensmi.ros2.runtime.errors import FieldValueError, PublishFailedError, ROS2RuntimeError
|
|
52
|
+
from opensmi.ros2.runtime.guard import require_sendable
|
|
53
|
+
from opensmi.ros2.runtime.messages import ArrayType, NestedType, PrimitiveType, SequenceType, is_byte_container
|
|
54
|
+
from opensmi.ros2.runtime.selection import SEPARATOR
|
|
55
|
+
from opensmi.ros2.server.access import SKILL_ACCESS_LEVEL
|
|
56
|
+
from opensmi.ros2.server.containers import ROS2ContainerMixin, VariableContainer
|
|
57
|
+
from opensmi.ros2.server.errors import DeclarationError
|
|
58
|
+
from opensmi.ros2.server.events import Severity
|
|
59
|
+
from opensmi.ros2.server.mutation import add_plan_variable, require_unused_name
|
|
60
|
+
from opensmi.ros2.server.projection import PlanVariable, narrowed, require_invertible, shaped
|
|
61
|
+
from opensmi.ros2.server.provenance import BindingQoS
|
|
62
|
+
|
|
63
|
+
if TYPE_CHECKING:
|
|
64
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
65
|
+
|
|
66
|
+
from opensmi.server.protocols import UserAuthorization
|
|
67
|
+
from opensmi.server.ua_variable import UaVariable
|
|
68
|
+
|
|
69
|
+
from opensmi.ros2.runtime.interface import RuntimeInterface
|
|
70
|
+
from opensmi.ros2.runtime.messages import ElementType, FieldType, Message
|
|
71
|
+
from opensmi.ros2.runtime.publisher import Publisher
|
|
72
|
+
from opensmi.ros2.server.bindings import PublisherBinding
|
|
73
|
+
from opensmi.ros2.server.projection import PlanEntry, ProjectionContext
|
|
74
|
+
|
|
75
|
+
__all__ = [
|
|
76
|
+
"LOCK_ENDED",
|
|
77
|
+
"MAXIMUM_RATE",
|
|
78
|
+
"MESSAGE_UNBUILDABLE",
|
|
79
|
+
"MINIMUM_RATE",
|
|
80
|
+
"PUBLISH_FAILED",
|
|
81
|
+
"PUBLISH_FAULTS",
|
|
82
|
+
"RATE_PARAMETER",
|
|
83
|
+
"SETPOINT_STALE",
|
|
84
|
+
"ROS2ContinuousPublisherSkill",
|
|
85
|
+
"ROS2FinitePublisherSkill",
|
|
86
|
+
"ROS2PublisherSkill",
|
|
87
|
+
"default_message_from",
|
|
88
|
+
"halt_message_from",
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
RATE_PARAMETER: Final = "Rate"
|
|
92
|
+
"""The browse name of the one Parameter of a continuous publishing Skill that is not a message field.
|
|
93
|
+
|
|
94
|
+
It is reserved: a message with a field that converts to it (``rate``) is refused at init. Its
|
|
95
|
+
DisplayName is ``rate``.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
MINIMUM_RATE: Final = 0.001
|
|
99
|
+
"""The slowest publish rate a declaration or a client may set, in hertz (one tick every 16 minutes).
|
|
100
|
+
|
|
101
|
+
The bound is published as an ``EURange`` on the Parameter, so a write of zero is refused before a
|
|
102
|
+
period is divided by it.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
MAXIMUM_RATE: Final = 1000.0
|
|
106
|
+
"""The fastest publish rate, in hertz: the 1 ms period is the floor ``asyncio.sleep`` can keep."""
|
|
107
|
+
|
|
108
|
+
PUBLISH_FAILED: Final = "PUBLISH_FAILED"
|
|
109
|
+
"""The BindingEvent ``Code`` of every failed publish, and the ``ErrorCode`` of the error that halts
|
|
110
|
+
the Skill once its tolerance is spent. A TF Binding's failed broadcast reports under it too.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
MESSAGE_UNBUILDABLE: Final = "MessageUnbuildable"
|
|
114
|
+
"""The ``ErrorCode`` of a tick whose Parameters could not be built into a message.
|
|
115
|
+
|
|
116
|
+
It halts the Skill and nothing is published; the error message names the field and the reason.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
LOCK_ENDED: Final = "LOCK_ENDED"
|
|
120
|
+
"""The BindingEvent ``Code`` and ``ErrorCode`` of a stream halted because the Lock it was started
|
|
121
|
+
under ended: released, broken, expired, or lost with the holder's session.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
SETPOINT_STALE: Final = "SETPOINT_STALE"
|
|
125
|
+
"""The BindingEvent ``Code`` and ``ErrorCode`` of a stream halted because no client wrote any of its
|
|
126
|
+
Parameters within the Binding's ``stale_after``.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
PUBLISH_FAULTS: Final = (PublishFailedError, FieldValueError)
|
|
130
|
+
"""The faults that mean this tick did not reach the topic: the middleware refused the message, or
|
|
131
|
+
the guard refused a field value. Any other Runtime error (a released publisher, a stopped Runtime)
|
|
132
|
+
cannot be mended by another tick and is not tolerated.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def default_message_from(
|
|
137
|
+
message_type: type[Message],
|
|
138
|
+
values: Mapping[str, object],
|
|
139
|
+
context: ProjectionContext,
|
|
140
|
+
) -> Message:
|
|
141
|
+
"""Build the message to publish out of what a client wrote into a Skill's Parameters.
|
|
142
|
+
|
|
143
|
+
This runs the Projection of the message type backwards, as an action's goal and a service's
|
|
144
|
+
request do. It is a pure function (no server, no ``rclpy``, no event loop). Values the message
|
|
145
|
+
has no field for, such as the reserved ``rate``, are ignored.
|
|
146
|
+
|
|
147
|
+
:raises NotInvertibleError: When a field of the message has no value, because the selection
|
|
148
|
+
removed it or no Parameter carries it. A default is never invented.
|
|
149
|
+
"""
|
|
150
|
+
return context.registry.find(message_type.ros2.type_name).inverse_of(message_type, values, context)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def halt_message_from(
|
|
154
|
+
binding: PublisherBinding, message_type: type[Message], runtime: RuntimeInterface
|
|
155
|
+
) -> Message | None:
|
|
156
|
+
"""Build the message a stream publishes once when it ends, or ``None`` when none is declared.
|
|
157
|
+
|
|
158
|
+
It starts from the message as the type's generated class constructs it, so a field the table
|
|
159
|
+
does not name keeps that class's default, and sets the named fields. A number goes
|
|
160
|
+
into a floating-point field as a float, so ``z = -1`` in a file is ``-1.0``. The result passes
|
|
161
|
+
the same send-time guard as every message the Skill publishes, so a value the field cannot hold
|
|
162
|
+
fails here, at init, and not on the robot.
|
|
163
|
+
|
|
164
|
+
:raises DeclarationError: When the table names a field the message type does not have, gives a
|
|
165
|
+
table where a value belongs or the reverse, or holds a value its field cannot carry.
|
|
166
|
+
"""
|
|
167
|
+
table = binding.halt_message
|
|
168
|
+
if table is None:
|
|
169
|
+
return None
|
|
170
|
+
try:
|
|
171
|
+
message = _overlaid(runtime.default_message(message_type), table, runtime, "")
|
|
172
|
+
require_sendable(message)
|
|
173
|
+
except (_HaltMessageRefusedError, FieldValueError) as refused:
|
|
174
|
+
text = (
|
|
175
|
+
f"the continuous publishing Binding {binding.name!r} declares a halt_message that "
|
|
176
|
+
f"{message_type.ros2.type_name} cannot hold: {refused}"
|
|
177
|
+
)
|
|
178
|
+
raise DeclarationError(text) from refused
|
|
179
|
+
return message
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class _HaltMessageRefusedError(ValueError):
|
|
183
|
+
"""A halt message table that does not fit its message type, with the field path at fault."""
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _overlaid(default: Message, table: Mapping[str, object], runtime: RuntimeInterface, where: str) -> Message:
|
|
187
|
+
"""Return a message with the fields a table names set to its values, the rest left as they are."""
|
|
188
|
+
if not isinstance(table, Mapping):
|
|
189
|
+
message = f"{where or 'the message'} is a {default.ros2.type_name}, so it takes a table of its fields"
|
|
190
|
+
raise _HaltMessageRefusedError(message)
|
|
191
|
+
fields = {field.name: field for field in default.ros2.fields}
|
|
192
|
+
changes: dict[str, object] = {}
|
|
193
|
+
for name, value in table.items():
|
|
194
|
+
path = f"{where}{SEPARATOR}{name}" if where else name
|
|
195
|
+
field = fields.get(name)
|
|
196
|
+
if field is None:
|
|
197
|
+
message = f"{path} is not a field of {default.ros2.type_name}, which has {', '.join(fields)}"
|
|
198
|
+
raise _HaltMessageRefusedError(message)
|
|
199
|
+
nested = default.ros2_nested.get(name)
|
|
200
|
+
changes[name] = _field_value(field.field_type, nested, getattr(default, name), value, runtime, path)
|
|
201
|
+
# A message dataclass is built at run time, so the checker sees only its base.
|
|
202
|
+
return replace(cast("Any", default), **changes)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _field_value(
|
|
206
|
+
field_type: FieldType,
|
|
207
|
+
nested: type[Message] | None,
|
|
208
|
+
current: object,
|
|
209
|
+
value: object,
|
|
210
|
+
runtime: RuntimeInterface,
|
|
211
|
+
path: str,
|
|
212
|
+
) -> object:
|
|
213
|
+
"""Return what one field of a halt message holds, given what the table says for it."""
|
|
214
|
+
if is_byte_container(field_type):
|
|
215
|
+
if not isinstance(value, (list, tuple)):
|
|
216
|
+
message = f"{path} holds bytes, so it takes an array of numbers from 0 to 255"
|
|
217
|
+
raise _HaltMessageRefusedError(message)
|
|
218
|
+
try:
|
|
219
|
+
return bytes(value) # pyright: ignore[reportUnknownArgumentType]
|
|
220
|
+
except (TypeError, ValueError) as error:
|
|
221
|
+
message = f"{path} holds bytes, so it takes an array of numbers from 0 to 255"
|
|
222
|
+
raise _HaltMessageRefusedError(message) from error
|
|
223
|
+
match field_type:
|
|
224
|
+
case NestedType():
|
|
225
|
+
return _overlaid(cast("Message", current), cast("Mapping[str, object]", value), runtime, path)
|
|
226
|
+
case ArrayType(element=element) | SequenceType(element=element):
|
|
227
|
+
if not isinstance(value, (list, tuple)):
|
|
228
|
+
message = f"{path} is a list, so it takes an array"
|
|
229
|
+
raise _HaltMessageRefusedError(message)
|
|
230
|
+
items = cast("list[object] | tuple[object, ...]", value)
|
|
231
|
+
return tuple(
|
|
232
|
+
_element_value(element, nested, each, runtime, f"{path}[{index}]") for index, each in enumerate(items)
|
|
233
|
+
)
|
|
234
|
+
case _:
|
|
235
|
+
return _element_value(field_type, nested, value, runtime, path)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _element_value(
|
|
239
|
+
element: ElementType,
|
|
240
|
+
nested: type[Message] | None,
|
|
241
|
+
value: object,
|
|
242
|
+
runtime: RuntimeInterface,
|
|
243
|
+
path: str,
|
|
244
|
+
) -> object:
|
|
245
|
+
"""Return one scalar or one element of a list, a nested element built from its own default."""
|
|
246
|
+
if isinstance(element, NestedType):
|
|
247
|
+
assert nested is not None
|
|
248
|
+
return _overlaid(runtime.default_message(nested), cast("Mapping[str, object]", value), runtime, path)
|
|
249
|
+
if isinstance(value, Mapping):
|
|
250
|
+
message = f"{path} is a single value, not a message, so it takes a value rather than a table"
|
|
251
|
+
raise _HaltMessageRefusedError(message)
|
|
252
|
+
if isinstance(element, PrimitiveType) and element.name in _FLOATING and type(value) is int:
|
|
253
|
+
return float(value)
|
|
254
|
+
return value
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
_FLOATING: Final = frozenset({"float32", "float64"})
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class ROS2PublisherSkill(
|
|
261
|
+
ROS2ContainerMixin,
|
|
262
|
+
ParentMixin[BaseMachineryItem],
|
|
263
|
+
ParameterSetMixin,
|
|
264
|
+
):
|
|
265
|
+
"""What both publishing Skills share, everything except the tick.
|
|
266
|
+
|
|
267
|
+
It is not a Skill on its own. The two subclasses below add opensmi's skill logic and differ
|
|
268
|
+
only in what ``Running`` does; the declaration's ``continuous`` picks one.
|
|
269
|
+
"""
|
|
270
|
+
|
|
271
|
+
callable_kind: ClassVar[str] = "Skill"
|
|
272
|
+
|
|
273
|
+
def __init__(
|
|
274
|
+
self,
|
|
275
|
+
*,
|
|
276
|
+
binding: PublisherBinding,
|
|
277
|
+
runtime: RuntimeInterface,
|
|
278
|
+
context: ProjectionContext,
|
|
279
|
+
minimum_access_level: int = SKILL_ACCESS_LEVEL,
|
|
280
|
+
) -> None:
|
|
281
|
+
"""Resolve everything about the declaration that can be wrong, before any node exists.
|
|
282
|
+
|
|
283
|
+
:param binding: What to build.
|
|
284
|
+
:param runtime: Where the message is published (the Machine's, reached through the
|
|
285
|
+
Component).
|
|
286
|
+
:param context: The Projection context this Component renders through, with nothing
|
|
287
|
+
selected yet.
|
|
288
|
+
:param minimum_access_level: The level ``Start``, ``Halt`` and ``Reset`` need.
|
|
289
|
+
:raises MessageTypeError: When the message type cannot be resolved.
|
|
290
|
+
:raises FieldSelectionError: When a selection pattern matches nothing.
|
|
291
|
+
:raises NotInvertibleError: When the message type reaches a Projection that cannot run
|
|
292
|
+
backwards, so no client could ever publish through it.
|
|
293
|
+
:raises DeclarationError: When a field of the message would claim the ``rate`` Parameter's
|
|
294
|
+
name on a continuous Skill.
|
|
295
|
+
"""
|
|
296
|
+
super().__init__(
|
|
297
|
+
name=binding.name,
|
|
298
|
+
minimum_access_level=minimum_access_level,
|
|
299
|
+
suspendable=False,
|
|
300
|
+
)
|
|
301
|
+
self._binding = binding
|
|
302
|
+
self._runtime = runtime
|
|
303
|
+
self._message_type: type[Message] = runtime.describe_message(binding.message_type)
|
|
304
|
+
self._context = narrowed(context, self._message_type, binding.selection)
|
|
305
|
+
require_invertible(self._message_type, self._context)
|
|
306
|
+
self._plan = shaped(self._message_type, self._context)
|
|
307
|
+
if binding.continuous:
|
|
308
|
+
_require_the_rate_name_is_free(self._plan, self._message_type, binding)
|
|
309
|
+
# opensmi's container exists from first use, so the record can be made here and filled as
|
|
310
|
+
# `_init` creates the variables.
|
|
311
|
+
self._parameters = VariableContainer(name="ParameterSet", container=self.parameter_set)
|
|
312
|
+
self._emit: Callable[..., Awaitable[None]] | None = None
|
|
313
|
+
self._publisher: Publisher | None = None
|
|
314
|
+
self._failures = 0
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def binding(self) -> PublisherBinding:
|
|
318
|
+
"""Return the declaration this Skill was built from."""
|
|
319
|
+
return self._binding
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def message_type(self) -> type[Message]:
|
|
323
|
+
"""Return the message dataclass this Skill publishes."""
|
|
324
|
+
return self._message_type
|
|
325
|
+
|
|
326
|
+
@property
|
|
327
|
+
def publisher(self) -> Publisher | None:
|
|
328
|
+
"""Return the ROS2 publisher this Skill owns, or ``None`` before init and after shutdown.
|
|
329
|
+
|
|
330
|
+
It is advertised at init and held, so subscribers discover it while a client is still
|
|
331
|
+
writing the fields and a one-shot push does not race their discovery.
|
|
332
|
+
"""
|
|
333
|
+
return self._publisher
|
|
334
|
+
|
|
335
|
+
@property
|
|
336
|
+
def ros2_qos_provenance(self) -> BindingQoS | None:
|
|
337
|
+
"""Return what this Skill's publisher offers and where that came from, or ``None``.
|
|
338
|
+
|
|
339
|
+
``None`` before ``_init`` has advertised. The QoS is declared or defaulted, never
|
|
340
|
+
discovered, so it cannot change.
|
|
341
|
+
"""
|
|
342
|
+
publisher = self._publisher
|
|
343
|
+
if publisher is None:
|
|
344
|
+
return None
|
|
345
|
+
return BindingQoS.of(self._binding.name, self._binding.path, publisher)
|
|
346
|
+
|
|
347
|
+
@property
|
|
348
|
+
def consecutive_failures(self) -> int:
|
|
349
|
+
"""Return how many publishes in a row have failed, as the tolerance counts them."""
|
|
350
|
+
return self._failures
|
|
351
|
+
|
|
352
|
+
async def _init(self) -> None:
|
|
353
|
+
"""Let opensmi build the Skill, create the ParameterSet variables, and prove them.
|
|
354
|
+
|
|
355
|
+
The Parameters a client has not written yet hold the plan's initial values, so building a
|
|
356
|
+
message from them is the message ``Start`` would publish now. A value ROS2 would abort the
|
|
357
|
+
process over is thus a traceback here, not a core dump on a robot. The publisher is
|
|
358
|
+
advertised last, so a declaration that cannot boot leaves no endpoint on the graph.
|
|
359
|
+
|
|
360
|
+
:raises DeclarationError: When the Component cannot raise a BindingEvent.
|
|
361
|
+
"""
|
|
362
|
+
# The mixin sits ahead of opensmi's Skill and is not a subclass of it, so the call resolves
|
|
363
|
+
# statically to `object`; the house spelling of that suppression is the one the Component uses.
|
|
364
|
+
await super()._init() # pyright: ignore[reportAttributeAccessIssue]
|
|
365
|
+
self._emit = binding_event_emitter(
|
|
366
|
+
self.parent,
|
|
367
|
+
f"the Binding {self._binding.name!r} publishes, and the Component it is on cannot raise a "
|
|
368
|
+
f"BindingEvent; a Component carrying ROS2 Bindings mixes in ROS2ComponentMixin",
|
|
369
|
+
)
|
|
370
|
+
await self._create(self._plan, self._parameters, message_type=self._message_type, writable=True)
|
|
371
|
+
await self._create_own_parameters()
|
|
372
|
+
require_sendable(await self.build_message(await self.read_parameters()))
|
|
373
|
+
self._publisher = await self._runtime.advertise(
|
|
374
|
+
topic=self._binding.path,
|
|
375
|
+
message_type=self._message_type,
|
|
376
|
+
depth=self._binding.depth,
|
|
377
|
+
qos=self._binding.qos,
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
async def read_parameters(self) -> Mapping[str, object]:
|
|
381
|
+
"""Return what the ParameterSet holds now, by variable name."""
|
|
382
|
+
return await self._read_values(self._parameters)
|
|
383
|
+
|
|
384
|
+
async def build_message(self, values: Mapping[str, object]) -> Message:
|
|
385
|
+
"""Return the message to publish, given what a client wrote into the Parameters.
|
|
386
|
+
|
|
387
|
+
Override this on a custom implementation class when building needs the instance (another
|
|
388
|
+
node's value, something injected into the Component). The declaration's ``message_from`` is
|
|
389
|
+
the pure-function form of the same hook, and :func:`default_message_from` is the default.
|
|
390
|
+
|
|
391
|
+
An override must work at init, which calls it once with the declaration's defaults. On a
|
|
392
|
+
continuous Skill the values include the reserved ``Rate``, which is not a message field.
|
|
393
|
+
"""
|
|
394
|
+
build = self._binding.message_from or default_message_from
|
|
395
|
+
return build(self._message_type, values, self._context)
|
|
396
|
+
|
|
397
|
+
async def close_publisher(self) -> None:
|
|
398
|
+
"""Release this Skill's ROS2 publisher. Idempotent.
|
|
399
|
+
|
|
400
|
+
The declaring Component's shutdown calls it, for a Component torn down while the process
|
|
401
|
+
goes on serving. Stopping the Runtime closes every publisher too.
|
|
402
|
+
"""
|
|
403
|
+
publisher, self._publisher = self._publisher, None
|
|
404
|
+
if publisher is not None:
|
|
405
|
+
await publisher.close()
|
|
406
|
+
|
|
407
|
+
async def _create_own_parameters(self) -> None:
|
|
408
|
+
"""Create the Parameters that are not message fields. A finite Skill has none."""
|
|
409
|
+
|
|
410
|
+
async def _handle_resetting(self) -> None:
|
|
411
|
+
"""Clear the failure count. The ParameterSet stays, so nothing a client wrote is lost."""
|
|
412
|
+
self._failures = 0
|
|
413
|
+
|
|
414
|
+
async def _publish(self) -> None:
|
|
415
|
+
"""Publish one snapshot of the Parameters, and let the continuity decide what a failure is.
|
|
416
|
+
|
|
417
|
+
:raises OpenSmiRuntimeError: When the publish failed and the tolerance is spent.
|
|
418
|
+
"""
|
|
419
|
+
publisher = self._publisher
|
|
420
|
+
if publisher is None: # pragma: no cover -- _init either advertises or raises
|
|
421
|
+
missing = "this Skill has no ROS2 publisher, so there is nothing to publish through"
|
|
422
|
+
raise OpenSmiRuntimeError(missing, error_code="PublisherMissing")
|
|
423
|
+
try:
|
|
424
|
+
message = await self.build_message(await self.read_parameters())
|
|
425
|
+
except ValueError as refused:
|
|
426
|
+
# Every refusal of a client's value is a ValueError; left to opensmi it would halt
|
|
427
|
+
# without an error code.
|
|
428
|
+
raise OpenSmiRuntimeError(str(refused), error_code=MESSAGE_UNBUILDABLE) from refused
|
|
429
|
+
try:
|
|
430
|
+
await publisher.publish(message)
|
|
431
|
+
except PUBLISH_FAULTS as error:
|
|
432
|
+
await self._note_a_failure(error)
|
|
433
|
+
return
|
|
434
|
+
self._failures = 0
|
|
435
|
+
|
|
436
|
+
async def _note_a_failure(self, error: Exception) -> None:
|
|
437
|
+
"""Count one failed publish, report it, and halt when the tolerance is spent.
|
|
438
|
+
|
|
439
|
+
Every failure is reported, tolerated or not: a tolerated one has no other surface, since
|
|
440
|
+
the Skill stays ``Running``.
|
|
441
|
+
|
|
442
|
+
:raises OpenSmiRuntimeError: When this failure is one too many.
|
|
443
|
+
"""
|
|
444
|
+
self._failures += 1
|
|
445
|
+
tolerated = self._binding.tolerated_failures
|
|
446
|
+
spent = self._failures > tolerated
|
|
447
|
+
self.logger.warning(
|
|
448
|
+
"A ROS2 publish did not happen",
|
|
449
|
+
binding=self._binding.name,
|
|
450
|
+
topic=self._binding.path,
|
|
451
|
+
consecutive=self._failures,
|
|
452
|
+
tolerated=tolerated,
|
|
453
|
+
)
|
|
454
|
+
await self._report(
|
|
455
|
+
PUBLISH_FAILED,
|
|
456
|
+
severity=Severity.ERROR if spent else Severity.WARNING,
|
|
457
|
+
text=str(error),
|
|
458
|
+
)
|
|
459
|
+
if spent:
|
|
460
|
+
raise OpenSmiRuntimeError(str(error), error_code=PUBLISH_FAILED)
|
|
461
|
+
|
|
462
|
+
async def _report(self, code: str, *, severity: Severity, text: str) -> None:
|
|
463
|
+
"""Fire one BindingEvent about this Binding, and never let the reporting be the fault.
|
|
464
|
+
|
|
465
|
+
A failure to raise the event is only logged: a stream must not die because the
|
|
466
|
+
report about a tolerated failure could not be made.
|
|
467
|
+
"""
|
|
468
|
+
emit = self._emit
|
|
469
|
+
if emit is None: # pragma: no cover -- _init resolves one or raises
|
|
470
|
+
return
|
|
471
|
+
try:
|
|
472
|
+
await emit(
|
|
473
|
+
binding=self._binding.name,
|
|
474
|
+
path=self._binding.path,
|
|
475
|
+
code=code,
|
|
476
|
+
severity=severity,
|
|
477
|
+
text=text,
|
|
478
|
+
)
|
|
479
|
+
except Exception:
|
|
480
|
+
self.logger.exception(
|
|
481
|
+
"Could not fire a BindingEvent about a publish",
|
|
482
|
+
binding=self._binding.name,
|
|
483
|
+
topic=self._binding.path,
|
|
484
|
+
code=code,
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class ROS2ContinuousPublisherSkill(ROS2PublisherSkill, ContinuousSkillLogicMixin, BaseSkill):
|
|
489
|
+
"""The stream: one publish per tick of the ``rate`` Parameter, until ``Halt`` or nobody is in charge.
|
|
490
|
+
|
|
491
|
+
opensmi has no periodic hook on a running Skill, so this one owns a wait loop that the halting
|
|
492
|
+
transition cancels. Two things end it besides ``Halt`` and a failed publish: the Lock
|
|
493
|
+
it was started under ends (:data:`LOCK_ENDED`), and a declared ``stale_after`` passes without a
|
|
494
|
+
write to any Parameter (:data:`SETPOINT_STALE`). Both are checked before every publish, and the
|
|
495
|
+
wait between ticks wakes for either, so a halt does not wait for the next tick. A stream whose
|
|
496
|
+
Binding declares a ``halt_message`` publishes it once as it ends, whatever ended it; without one
|
|
497
|
+
it just stops. The robot's own command timeout stays what brings it to rest.
|
|
498
|
+
"""
|
|
499
|
+
|
|
500
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
501
|
+
"""Build the Skill, and start out with nothing known about the client's writing."""
|
|
502
|
+
super().__init__(**kwargs)
|
|
503
|
+
self._rate: UaVariable[float] | None = None
|
|
504
|
+
self._locking_user_node: ua.NodeId | None = None
|
|
505
|
+
self._holder: UserAuthorization | None = None
|
|
506
|
+
self._lock_ended = asyncio.Event()
|
|
507
|
+
self._fresh_since = datetime.now(UTC)
|
|
508
|
+
self._halt_message = halt_message_from(self._binding, self._message_type, self._runtime)
|
|
509
|
+
self._streaming = False
|
|
510
|
+
|
|
511
|
+
async def _create_own_parameters(self) -> None:
|
|
512
|
+
"""Create the ``rate`` Parameter, and check a declared ``stale_after``.
|
|
513
|
+
|
|
514
|
+
The rate is bounded by an ``EURange``, which opensmi's write path enforces, so a client
|
|
515
|
+
cannot write a period of zero.
|
|
516
|
+
"""
|
|
517
|
+
require_unused_name(RATE_PARAMETER, (self.parameter_set,), self._named(self._parameters))
|
|
518
|
+
# The declaration refuses a continuous Binding without a rate, so the fallback is
|
|
519
|
+
# unreachable; it is spelled out because `rate` is optional on the declaration.
|
|
520
|
+
declared = self._binding.rate if self._binding.rate is not None else MINIMUM_RATE
|
|
521
|
+
entry = PlanVariable(
|
|
522
|
+
name=RATE_PARAMETER,
|
|
523
|
+
display_name="rate",
|
|
524
|
+
source="",
|
|
525
|
+
initial=float(declared),
|
|
526
|
+
variant_type=ua.VariantType.Double,
|
|
527
|
+
)
|
|
528
|
+
self._rate = await add_plan_variable(
|
|
529
|
+
self.parameter_set,
|
|
530
|
+
RATE_PARAMETER,
|
|
531
|
+
entry,
|
|
532
|
+
None,
|
|
533
|
+
writable=True,
|
|
534
|
+
unit="Hz",
|
|
535
|
+
value_range=(MINIMUM_RATE, MAXIMUM_RATE),
|
|
536
|
+
)
|
|
537
|
+
self._require_write_times_are_recorded()
|
|
538
|
+
|
|
539
|
+
async def _handle_running(self) -> None:
|
|
540
|
+
"""Publish the current snapshot on every tick, until something ends the stream.
|
|
541
|
+
|
|
542
|
+
Publishes first and waits afterwards, so ``Start`` sends at once; ``Start`` also counts as a
|
|
543
|
+
fresh setpoint. This never returns; every exit raises.
|
|
544
|
+
"""
|
|
545
|
+
self._fresh_since = datetime.now(UTC)
|
|
546
|
+
self._streaming = True
|
|
547
|
+
async with self._tied_to_the_lock():
|
|
548
|
+
while True:
|
|
549
|
+
await self._publish()
|
|
550
|
+
await self._until_the_next_tick(await self._period())
|
|
551
|
+
|
|
552
|
+
async def _handle_halting(self) -> None:
|
|
553
|
+
"""Publish the declared halt message once, when a stream that ran comes to an end.
|
|
554
|
+
|
|
555
|
+
opensmi halts through here whatever ended the stream: ``Halt``, the end of the Lock, a stale
|
|
556
|
+
setpoint or a spent tolerance. The rate loop has been cancelled or has raised by now, so the
|
|
557
|
+
halt message is the last one. A halt message that cannot be published is reported and does
|
|
558
|
+
not hold the halt up.
|
|
559
|
+
"""
|
|
560
|
+
streamed, self._streaming = self._streaming, False
|
|
561
|
+
message = self._halt_message
|
|
562
|
+
publisher = self._publisher
|
|
563
|
+
if not streamed or message is None or publisher is None:
|
|
564
|
+
return
|
|
565
|
+
try:
|
|
566
|
+
await publisher.publish(message)
|
|
567
|
+
except ROS2RuntimeError as error:
|
|
568
|
+
self.logger.warning("The halt message was not published", binding=self._binding.name)
|
|
569
|
+
text = f"the halt message of {self.name!r} was not published on {self._binding.path}: {error}"
|
|
570
|
+
await self._report(PUBLISH_FAILED, severity=Severity.ERROR, text=text)
|
|
571
|
+
|
|
572
|
+
async def _period(self) -> float:
|
|
573
|
+
"""Return how long until the next tick, read off the ``rate`` Parameter on every one.
|
|
574
|
+
|
|
575
|
+
Reading it per tick makes a rate change effective on the next tick. The range check is not
|
|
576
|
+
a second enforcement of the ``EURange``: it only refuses to divide by a number no client
|
|
577
|
+
write could have produced, such as one written by a consumer's own code.
|
|
578
|
+
|
|
579
|
+
:raises OpenSmiRuntimeError: When the Parameter holds a rate outside its published bounds.
|
|
580
|
+
"""
|
|
581
|
+
assert self._rate is not None
|
|
582
|
+
rate = float(await self._rate.read())
|
|
583
|
+
if not MINIMUM_RATE <= rate <= MAXIMUM_RATE:
|
|
584
|
+
refused = (
|
|
585
|
+
f"the publish rate of {self.name!r} is {rate}, and a rate is a number of times a "
|
|
586
|
+
f"second between {MINIMUM_RATE} and {MAXIMUM_RATE}"
|
|
587
|
+
)
|
|
588
|
+
raise OpenSmiRuntimeError(refused, error_code="RateOutOfRange")
|
|
589
|
+
return 1.0 / rate
|
|
590
|
+
|
|
591
|
+
async def _until_the_next_tick(self, period: float) -> None:
|
|
592
|
+
"""Wait one period, and halt on the way if the Lock ends or the setpoint goes stale.
|
|
593
|
+
|
|
594
|
+
:raises OpenSmiRuntimeError: When either happens before the period is over.
|
|
595
|
+
"""
|
|
596
|
+
loop = asyncio.get_running_loop()
|
|
597
|
+
tick = loop.time() + period
|
|
598
|
+
while True:
|
|
599
|
+
await self._require_the_lock_holds()
|
|
600
|
+
fresh_for = await self._require_a_fresh_setpoint()
|
|
601
|
+
remaining = tick - loop.time()
|
|
602
|
+
if remaining <= 0:
|
|
603
|
+
return
|
|
604
|
+
with contextlib.suppress(TimeoutError):
|
|
605
|
+
async with asyncio.timeout(min(remaining, fresh_for)):
|
|
606
|
+
await self._lock_ended.wait()
|
|
607
|
+
|
|
608
|
+
@contextlib.asynccontextmanager
|
|
609
|
+
async def _tied_to_the_lock(self) -> AsyncIterator[None]:
|
|
610
|
+
"""Tie the stream to whoever holds the Machine's Lock now, for as long as the block runs.
|
|
611
|
+
|
|
612
|
+
A client needs the Lock to call ``Start``, so its holder is the one in charge of the stream.
|
|
613
|
+
A Skill started through the server's own interface while nobody holds the Lock is tied to
|
|
614
|
+
nothing, since there is no Lock to end.
|
|
615
|
+
|
|
616
|
+
opensmi signals no change of the Lock, but every change (``ExitLock``, ``BreakLock``, the
|
|
617
|
+
inactivity timeout, a closed session) writes the Lock's ``LockingUser`` variable, so the
|
|
618
|
+
stream watches that write in asyncua's address space, as a subscription does.
|
|
619
|
+
"""
|
|
620
|
+
node = await self._locking_user()
|
|
621
|
+
self._lock_ended.clear()
|
|
622
|
+
self._holder = self.lock.locking_user
|
|
623
|
+
if self._holder is None:
|
|
624
|
+
yield
|
|
625
|
+
return
|
|
626
|
+
space: Any = self.server.ua_server.iserver.aspace
|
|
627
|
+
_, handle = space.add_datachange_callback(node, AttributeIds.Value, self._on_lock_written)
|
|
628
|
+
try:
|
|
629
|
+
yield
|
|
630
|
+
finally:
|
|
631
|
+
space.delete_datachange_callback(handle)
|
|
632
|
+
|
|
633
|
+
async def _locking_user(self) -> ua.NodeId:
|
|
634
|
+
"""Return the NodeId of the Lock's ``LockingUser`` variable, looked up once."""
|
|
635
|
+
if self._locking_user_node is None:
|
|
636
|
+
namespace = self.server.ua_get_namespace_index(DiNodeIds)
|
|
637
|
+
node = await self.lock.ua_node.get_child(f"{namespace}:LockingUser")
|
|
638
|
+
self._locking_user_node = node.nodeid
|
|
639
|
+
return self._locking_user_node
|
|
640
|
+
|
|
641
|
+
async def _on_lock_written(self, *_change: object) -> None:
|
|
642
|
+
"""Note that the Lock ended when its holder is no longer the one the stream started under.
|
|
643
|
+
|
|
644
|
+
It runs inside the Lock's own update, so it only sets a flag; the running loop halts.
|
|
645
|
+
"""
|
|
646
|
+
if self.lock.locking_user != self._holder:
|
|
647
|
+
self._lock_ended.set()
|
|
648
|
+
|
|
649
|
+
async def _require_the_lock_holds(self) -> None:
|
|
650
|
+
"""Halt the stream when the Lock it was started under has ended.
|
|
651
|
+
|
|
652
|
+
:raises OpenSmiRuntimeError: When the Lock was released, broken, expired or lost with its
|
|
653
|
+
session.
|
|
654
|
+
"""
|
|
655
|
+
if not self._lock_ended.is_set():
|
|
656
|
+
return
|
|
657
|
+
assert self._holder is not None
|
|
658
|
+
now = self.lock.locking_user
|
|
659
|
+
holding = "nobody holds it now" if now is None else f"{now.name!r} holds it now"
|
|
660
|
+
ended = (
|
|
661
|
+
f"the Lock {self._holder.name!r} held when {self.name!r} started has ended (released, broken, "
|
|
662
|
+
f"expired or its session closed) and {holding}, so nobody is in charge of {self._binding.path} "
|
|
663
|
+
f"any more and this stream is halting rather than republishing what it last said"
|
|
664
|
+
)
|
|
665
|
+
await self._report(LOCK_ENDED, severity=Severity.WARNING, text=ended)
|
|
666
|
+
raise OpenSmiRuntimeError(ended, error_code=LOCK_ENDED)
|
|
667
|
+
|
|
668
|
+
async def _require_a_fresh_setpoint(self) -> float:
|
|
669
|
+
"""Halt the stream when no Parameter has been written for ``stale_after`` seconds.
|
|
670
|
+
|
|
671
|
+
Without this, a stream whose client died keeps republishing the last values (on
|
|
672
|
+
``/cmd_vel``, a robot driving on a command nobody sends) for as long as the client's session
|
|
673
|
+
and Lock outlive it. It compares when each Parameter was last written, not what it holds: a
|
|
674
|
+
client steering straight ahead writes the same numbers every time. Every Parameter counts,
|
|
675
|
+
``rate`` included. The write times are wall-clock ``ServerTimestamp`` values, so a clock
|
|
676
|
+
stepped forward can halt a stream early, which is the safe side.
|
|
677
|
+
|
|
678
|
+
:return: The seconds left before the setpoint goes stale, infinite without ``stale_after``.
|
|
679
|
+
:raises OpenSmiRuntimeError: When the setpoint is stale.
|
|
680
|
+
"""
|
|
681
|
+
seconds = self._binding.stale_after
|
|
682
|
+
if seconds is None:
|
|
683
|
+
return math.inf
|
|
684
|
+
written = await self._newest_write()
|
|
685
|
+
if written is not None and written > self._fresh_since:
|
|
686
|
+
self._fresh_since = written
|
|
687
|
+
left = seconds - (datetime.now(UTC) - self._fresh_since).total_seconds()
|
|
688
|
+
if left > 0:
|
|
689
|
+
return left
|
|
690
|
+
stale = (
|
|
691
|
+
f"no Parameter of {self.name!r} has been written for {seconds} s, so the client driving "
|
|
692
|
+
f"{self._binding.path} has stopped and this stream is halting rather than republishing "
|
|
693
|
+
f"what it last said"
|
|
694
|
+
)
|
|
695
|
+
await self._report(SETPOINT_STALE, severity=Severity.WARNING, text=stale)
|
|
696
|
+
raise OpenSmiRuntimeError(stale, error_code=SETPOINT_STALE)
|
|
697
|
+
|
|
698
|
+
async def _newest_write(self) -> datetime | None:
|
|
699
|
+
"""Return when any Parameter was last written (its ``ServerTimestamp``), or ``None``."""
|
|
700
|
+
newest: datetime | None = None
|
|
701
|
+
for variable in self.parameter_set:
|
|
702
|
+
written = (await variable.ua_node.read_data_value()).ServerTimestamp
|
|
703
|
+
if written is not None and (newest is None or written > newest):
|
|
704
|
+
newest = written
|
|
705
|
+
return newest
|
|
706
|
+
|
|
707
|
+
def _require_write_times_are_recorded(self) -> None:
|
|
708
|
+
"""Refuse a declared ``stale_after`` on a server that does not stamp the writes it takes.
|
|
709
|
+
|
|
710
|
+
The check reads asyncua's ``ServerTimestamp``, which an application may turn off. Without
|
|
711
|
+
it every stream would halt after ``stale_after`` while its client writes.
|
|
712
|
+
|
|
713
|
+
:raises DeclarationError: When the server does not record write times.
|
|
714
|
+
"""
|
|
715
|
+
if self._binding.stale_after is None:
|
|
716
|
+
return
|
|
717
|
+
space: Any = getattr(getattr(self.server.ua_server, "iserver", None), "aspace", None)
|
|
718
|
+
if getattr(space, "force_server_timestamp", True):
|
|
719
|
+
return
|
|
720
|
+
refused = (
|
|
721
|
+
f"the Binding {self._binding.name!r} declares stale_after, and this server does not "
|
|
722
|
+
f"record when a value was written -- force_server_timestamp is off, so every Parameter "
|
|
723
|
+
f"would look untouched and the stream would halt while its client was writing; leave "
|
|
724
|
+
f"stale_after out, or leave asyncua's server timestamps on"
|
|
725
|
+
)
|
|
726
|
+
raise DeclarationError(refused)
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
class ROS2FinitePublisherSkill(ROS2PublisherSkill, FiniteSkillLogicMixin, BaseSkill):
|
|
730
|
+
"""The one-shot push: publish once on ``Start``, then reach ``Completed``.
|
|
731
|
+
|
|
732
|
+
A second push is ``Reset``, write, ``Start``. ``Ready`` is reachable only by an explicit reset,
|
|
733
|
+
because resetting automatically would discard what a client wrote.
|
|
734
|
+
"""
|
|
735
|
+
|
|
736
|
+
async def _handle_running(self) -> None:
|
|
737
|
+
"""Publish once. Returning reaches ``Completed``; any failure raises and halts.
|
|
738
|
+
|
|
739
|
+
A finite Skill has one publish and nothing to absorb, which is why a non-zero
|
|
740
|
+
``tolerated_failures`` on a finite declaration is refused.
|
|
741
|
+
"""
|
|
742
|
+
await self._publish()
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def binding_event_emitter(machinery_item: object, message: str) -> Callable[..., Awaitable[None]]:
|
|
746
|
+
"""Return the BindingEvent emitter of the machinery item that declared a Binding.
|
|
747
|
+
|
|
748
|
+
Resolved at init so that a missing reporting surface is not first noticed by a report going
|
|
749
|
+
nowhere. A Binding is only built by a Component that mixes ours in, so this is unreachable
|
|
750
|
+
through the declarative API.
|
|
751
|
+
|
|
752
|
+
:param message: The error text for a machinery item that cannot raise one.
|
|
753
|
+
:raises DeclarationError: When the machinery item has no BindingEvent emitter.
|
|
754
|
+
"""
|
|
755
|
+
emit = getattr(machinery_item, "emit_binding_event", None)
|
|
756
|
+
if emit is None:
|
|
757
|
+
raise DeclarationError(message)
|
|
758
|
+
return emit
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _require_the_rate_name_is_free(
|
|
762
|
+
plan: tuple[PlanEntry, ...],
|
|
763
|
+
message_type: type[Message],
|
|
764
|
+
binding: PublisherBinding,
|
|
765
|
+
) -> None:
|
|
766
|
+
"""Refuse a continuous declaration whose message already claims the ``rate`` Parameter's name.
|
|
767
|
+
|
|
768
|
+
Checked against the plan, not the message's fields, because a curated Projection chooses its
|
|
769
|
+
own names and those are what collide. A finite Skill has no ``rate`` node, so it is not checked.
|
|
770
|
+
|
|
771
|
+
:raises DeclarationError: When the plan has a top-level entry called ``rate``.
|
|
772
|
+
"""
|
|
773
|
+
if not any(entry.full_name == RATE_PARAMETER for entry in plan):
|
|
774
|
+
return
|
|
775
|
+
message = (
|
|
776
|
+
f"the continuous publishing Binding {binding.name!r} renders "
|
|
777
|
+
f"{message_type.ros2.type_name} into a Parameter called {RATE_PARAMETER!r}, and that name "
|
|
778
|
+
f"is the tick's period on a stream; exclude the field, give it another name with the rename option, "
|
|
779
|
+
f"curate the type so the name differs, or declare this Binding finite"
|
|
780
|
+
)
|
|
781
|
+
raise DeclarationError(message)
|