OpenSMI-Server 0.4__tar.gz → 0.4.2__tar.gz

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 (94) hide show
  1. {opensmi_server-0.4 → opensmi_server-0.4.2}/PKG-INFO +2 -2
  2. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/skills.md +11 -7
  3. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/variables.md +20 -2
  4. {opensmi_server-0.4 → opensmi_server-0.4.2}/pyproject.toml +1 -1
  5. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/OpenSMI_Server.egg-info/PKG-INFO +2 -2
  6. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/OpenSMI_Server.egg-info/SOURCES.txt +1 -0
  7. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/OpenSMI_Server.egg-info/requires.txt +1 -1
  8. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/OpenSMI_Server.egg-info/scm_file_list.json +4 -0
  9. opensmi_server-0.4.2/src/OpenSMI_Server.egg-info/scm_version.json +8 -0
  10. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_startup_skill.py +1 -1
  11. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/common.py +6 -5
  12. opensmi_server-0.4.2/src/opensmi/server/docstrings.py +39 -0
  13. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/description_mixin.py +3 -3
  14. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/skill_logic_mixins.py +38 -17
  15. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/ua_fsm.py +58 -4
  16. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/ua_variable.py +11 -1
  17. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/ua_variable_containers.py +7 -4
  18. opensmi_server-0.4/src/OpenSMI_Server.egg-info/scm_version.json +0 -8
  19. {opensmi_server-0.4 → opensmi_server-0.4.2}/.github/workflows/api-docs.yml +0 -0
  20. {opensmi_server-0.4 → opensmi_server-0.4.2}/.github/workflows/checks.yml +0 -0
  21. {opensmi_server-0.4 → opensmi_server-0.4.2}/.github/workflows/python-publish.yml +0 -0
  22. {opensmi_server-0.4 → opensmi_server-0.4.2}/.gitignore +0 -0
  23. {opensmi_server-0.4 → opensmi_server-0.4.2}/.pre-commit +0 -0
  24. {opensmi_server-0.4 → opensmi_server-0.4.2}/.pre-commit-config.yaml +0 -0
  25. {opensmi_server-0.4 → opensmi_server-0.4.2}/LICENSE +0 -0
  26. {opensmi_server-0.4 → opensmi_server-0.4.2}/LICENSES/CC0-1.0.txt +0 -0
  27. {opensmi_server-0.4 → opensmi_server-0.4.2}/LICENSES/MIT.txt +0 -0
  28. {opensmi_server-0.4 → opensmi_server-0.4.2}/MANIFEST.in +0 -0
  29. {opensmi_server-0.4 → opensmi_server-0.4.2}/README.md +0 -0
  30. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/development.md +0 -0
  31. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/events.md +0 -0
  32. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/faq.md +0 -0
  33. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/machinery_item.md +0 -0
  34. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/methods.md +0 -0
  35. {opensmi_server-0.4 → opensmi_server-0.4.2}/docs/migration.md +0 -0
  36. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/check/main.py +0 -0
  37. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dictionary_entries/main.py +0 -0
  38. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/__init__.py +0 -0
  39. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/composite_skill.py +0 -0
  40. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/config.toml +0 -0
  41. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/continuous_skill.py +0 -0
  42. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/continuous_skill_self_halting.py +0 -0
  43. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/dummy_component.py +0 -0
  44. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/dummy_machine.py +0 -0
  45. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/dummy_method.py +0 -0
  46. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/dummy_skill.py +0 -0
  47. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/dummy_skill_resources.py +0 -0
  48. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/dummy_skill_simple.py +0 -0
  49. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/main.py +0 -0
  50. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/resources.py +0 -0
  51. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/startup_skill.py +0 -0
  52. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/dummy/suspendable_dummy_skill.py +0 -0
  53. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/quick_start/main.py +0 -0
  54. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/rsl/main.py +0 -0
  55. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/structures/README.md +0 -0
  56. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/structures/client.py +0 -0
  57. {opensmi_server-0.4 → opensmi_server-0.4.2}/examples/structures/server.py +0 -0
  58. {opensmi_server-0.4 → opensmi_server-0.4.2}/setup.cfg +0 -0
  59. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/OpenSMI_Server.egg-info/dependency_links.txt +0 -0
  60. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/OpenSMI_Server.egg-info/top_level.txt +0 -0
  61. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/__init__.py +0 -0
  62. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/_history.py +0 -0
  63. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/_server.py +0 -0
  64. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/access_control.py +0 -0
  65. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_callable.py +0 -0
  66. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_feasibility_check.py +0 -0
  67. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_machine.py +0 -0
  68. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_machinery_item.py +0 -0
  69. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_method.py +0 -0
  70. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_precondition_check.py +0 -0
  71. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/base_skill.py +0 -0
  72. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/config.py +0 -0
  73. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/data_types.py +0 -0
  74. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/errors.py +0 -0
  75. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/interfaces.py +0 -0
  76. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/lock.py +0 -0
  77. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/__init__.py +0 -0
  78. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/lockable_mixin.py +0 -0
  79. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/notification_mixins.py +0 -0
  80. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/parent_mixin.py +0 -0
  81. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/requirements_mixin.py +0 -0
  82. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/spatial_object_mixin.py +0 -0
  83. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/ua_object_container_mixins.py +0 -0
  84. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/mixins/ua_variable_container_mixins.py +0 -0
  85. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/notification.py +0 -0
  86. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/protocols.py +0 -0
  87. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/resource.py +0 -0
  88. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/spatial_object.py +0 -0
  89. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/structures.py +0 -0
  90. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/ua_dictionary_entry.py +0 -0
  91. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/ua_object.py +0 -0
  92. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/ua_object_containers.py +0 -0
  93. {opensmi_server-0.4 → opensmi_server-0.4.2}/src/opensmi/server/user.py +0 -0
  94. {opensmi_server-0.4 → opensmi_server-0.4.2}/tools/create_password.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: OpenSMI-Server
3
- Version: 0.4
3
+ Version: 0.4.2
4
4
  Summary: Asynchronous Python framework for building Smart Machine Interface-compliant OPC UA servers.
5
5
  Author-email: Carsten Harms <Carsten.Harms@dfki.de>, Simon Jungbluth <Simon.Jungbluth@smartfactory.de>
6
6
  License-Expression: MIT
@@ -28,7 +28,7 @@ Description-Content-Type: text/markdown
28
28
  License-File: LICENSES/MIT.txt
29
29
  Requires-Dist: OpenSMI-Core<0.9,>=0.8.1
30
30
  Requires-Dist: asyncua<3,>=2.0.1
31
- Requires-Dist: transitions<1,>=0.9
31
+ Requires-Dist: transitions<0.10,>=0.9.3
32
32
  Requires-Dist: structlog>=26
33
33
  Requires-Dist: typing-extensions>=4.16.0
34
34
  Provides-Extra: rich
@@ -2,8 +2,8 @@
2
2
 
3
3
  ## Basics
4
4
 
5
- Each skill is a self-contained capability exposed over OPC-UA with `start()`/`suspend()`/`reset()`/`halt()` methods and
6
- a standard state machine. They have
5
+ Each skill is a self-contained capability exposed over OPC-UA with `start()`/`reset()`/`halt()` methods (and
6
+ `suspend()` for skills created with `suspendable=True`) and a standard state machine. They have
7
7
 
8
8
  - **`ParameterSet`** — the inputs a skill needs to do its work, written by a caller before or during `start`. For
9
9
  example a "MoveTo" skill's target position, or a "Drilling" skill's hole diameter and depth.
@@ -43,6 +43,8 @@ stateDiagram-v2
43
43
  }
44
44
  ```
45
45
 
46
+ `Suspending` and `Suspended` exist only for skills created with `suspendable=True`.
47
+
46
48
  - `Halted`: A halted skill is in a failed/safe-ish state. E.g. a motor should apply fail-safe brakes, cut power etc. and
47
49
  no longer move.
48
50
  - `Halting`: A halting skill is currently transitioning into `Halted`, but has not reached the safe-ish state yet. E.g.
@@ -84,8 +86,8 @@ the skill is `Suspending`, the skill finishes suspending and completes once it i
84
86
  ### Continuous Skills
85
87
 
86
88
  A continuous skill is a skill with no terminal "done" state — its `Running` state has no `Completed` counterpart at
87
- all. Once started, it keeps working until it is explicitly `suspend()`ed (paused, resumable) or `halt()`ed (stopped,
88
- non-resumable), rather than finishing on its own.
89
+ all. Once started, it keeps working until it is explicitly `halt()`ed (stopped, non-resumable) or, if created with
90
+ `suspendable=True`, `suspend()`ed (paused, resumable), rather than finishing on its own.
89
91
 
90
92
  For example, a "ConveyorFeed" skill that drives a belt to keep feeding parts downstream: `Running` means the motor
91
93
  is actively driving, for as long as the line needs material moved — there is no single unit of work after which the
@@ -109,15 +111,17 @@ stateDiagram-v2
109
111
  }
110
112
  ```
111
113
 
114
+ `Suspending` and `Suspended` exist only for skills created with `suspendable=True`.
115
+
112
116
  As for finite skills, `halt()` works from every state in the `Operational` box.
113
117
 
114
118
  ### The state machine in the address space
115
119
 
116
120
  The transitions are those of `SkillStateMachineType` in the MachineSet nodeset; OpenSMI-Core provides them as
117
121
  `opensmi.core.skill_state_machine`, which the server builds its state machine from and clients use to know which
118
- commands a state allows (`allowed_commands()`). A skill created with `suspendable=False` has no `Suspend` method in
119
- the address space and never reaches `Suspending` or `Suspended`; calling its Python `suspend()` raises
120
- `BadNotImplemented`.
122
+ commands a state allows (`allowed_commands()`). Suspending is opt-in: a skill created without `suspendable=True` (the
123
+ default is `False`) has no `Suspend` method in the address space and never reaches `Suspending` or `Suspended`; calling
124
+ its Python `suspend()` raises `BadNotImplemented`.
121
125
 
122
126
  Besides the text of `CurrentState`, every skill's state machine publishes:
123
127
 
@@ -1,8 +1,23 @@
1
1
  # Variables
2
2
 
3
3
  Machinery items, skills and methods hold their values in `UaVariable`s inside the variable containers `ParameterSet`,
4
- `Monitoring` and `FinalResultData` (see [Machinery Items](machinery_item.md)). This page covers values without a valid
5
- value, and values that belong together: structures, and groups of variables.
4
+ `Monitoring` and `FinalResultData` (see [Machinery Items](machinery_item.md)). This page covers their descriptions,
5
+ values without a valid value, and values that belong together: structures, and groups of variables.
6
+
7
+ ## Descriptions
8
+
9
+ The docstring right after a variable (or group) in its container class becomes the OPC UA `Description` of its node,
10
+ just like the docstring of a skill, component or machine class becomes the description of its object:
11
+
12
+ ```python
13
+ class Results(FinalResultData):
14
+ Count = UaVariable(0)
15
+ """Number of parts produced since server start."""
16
+ ```
17
+
18
+ Descriptions are Markdown, and plain text is fine. The lines of a paragraph are joined, so wrap docstrings as usual;
19
+ paragraphs and list items keep their own lines. They are read by clients, so describe the value for an operator or
20
+ integrator, not the Python API.
6
21
 
7
22
  ## Bad status
8
23
 
@@ -150,6 +165,9 @@ await parameters.read_all()
150
165
  # {"Controller": {"UseSimTime": False, "FollowPath": {"MaxVelX": 0.5}}}
151
166
  ```
152
167
 
168
+ `reset_all()` skips variables created with `resettable=False`, e.g. counters since server start; their own `reset()`
169
+ still resets them.
170
+
153
171
  ## Structure or group?
154
172
 
155
173
  A complex variable is one value: it is valid as a whole or not at all. A bad status on any of its nodes reaches all
@@ -40,7 +40,7 @@ requires-python = ">=3.11"
40
40
  dependencies = [
41
41
  "OpenSMI-Core>=0.8.1,<0.9",
42
42
  "asyncua>=2.0.1,<3", # OPC UA, main dep; has quite a few deps
43
- "transitions>=0.9, <1", # FSM; TODO remove it
43
+ "transitions>=0.9.3, <0.10", # FSM; private hooks overridden in ua_fsm.py; TODO remove it
44
44
  "structlog>=26", # structured logging; has no deps
45
45
  "typing-extensions>=4.16.0", # backported type hints; already a dep of asyncua
46
46
  ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: OpenSMI-Server
3
- Version: 0.4
3
+ Version: 0.4.2
4
4
  Summary: Asynchronous Python framework for building Smart Machine Interface-compliant OPC UA servers.
5
5
  Author-email: Carsten Harms <Carsten.Harms@dfki.de>, Simon Jungbluth <Simon.Jungbluth@smartfactory.de>
6
6
  License-Expression: MIT
@@ -28,7 +28,7 @@ Description-Content-Type: text/markdown
28
28
  License-File: LICENSES/MIT.txt
29
29
  Requires-Dist: OpenSMI-Core<0.9,>=0.8.1
30
30
  Requires-Dist: asyncua<3,>=2.0.1
31
- Requires-Dist: transitions<1,>=0.9
31
+ Requires-Dist: transitions<0.10,>=0.9.3
32
32
  Requires-Dist: structlog>=26
33
33
  Requires-Dist: typing-extensions>=4.16.0
34
34
  Provides-Extra: rich
@@ -62,6 +62,7 @@ src/opensmi/server/base_startup_skill.py
62
62
  src/opensmi/server/common.py
63
63
  src/opensmi/server/config.py
64
64
  src/opensmi/server/data_types.py
65
+ src/opensmi/server/docstrings.py
65
66
  src/opensmi/server/errors.py
66
67
  src/opensmi/server/interfaces.py
67
68
  src/opensmi/server/lock.py
@@ -1,6 +1,6 @@
1
1
  OpenSMI-Core<0.9,>=0.8.1
2
2
  asyncua<3,>=2.0.1
3
- transitions<1,>=0.9
3
+ transitions<0.10,>=0.9.3
4
4
  structlog>=26
5
5
  typing-extensions>=4.16.0
6
6
 
@@ -57,6 +57,7 @@
57
57
  "src/opensmi/server/common.py",
58
58
  "src/opensmi/server/config.py",
59
59
  "src/opensmi/server/data_types.py",
60
+ "src/opensmi/server/docstrings.py",
60
61
  "src/opensmi/server/errors.py",
61
62
  "src/opensmi/server/interfaces.py",
62
63
  "src/opensmi/server/lock.py",
@@ -94,10 +95,13 @@
94
95
  "tests/integration/test_paths.py",
95
96
  "tests/integration/test_skill.py",
96
97
  "tests/integration/test_spatial_object_integration.py",
98
+ "tests/integration/test_startup_skill.py",
97
99
  "tests/integration/test_structures_integration.py",
98
100
  "tests/integration/test_variable_groups.py",
99
101
  "tests/unit/test_access_control.py",
100
102
  "tests/unit/test_base_machinery_item.py",
103
+ "tests/unit/test_docstrings.py",
104
+ "tests/unit/test_halt_during_custom_start_condition.py",
101
105
  "tests/unit/test_parent_mixin.py",
102
106
  "tests/unit/test_scrypt.py",
103
107
  "tests/unit/test_skill_logic_mixins.py",
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.4.2",
3
+ "distance": 0,
4
+ "node": "g1c97f82918de5c9a448b0ad7c90cfb1ff2228a9a",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-12-04"
8
+ }
@@ -102,7 +102,7 @@ class BaseStartupSkill(ParentMixin["BaseMachineryItem"], BaseSkillContinuous):
102
102
  # this skill is important for the machine/component to function correctly,
103
103
  # so halt the machine/component if this skill is halted
104
104
  await self.parent.halt_components()
105
- await self.parent.halt_skills()
105
+ await self.parent.halt_skills([skill for skill in self.parent.skill_set if skill is not self])
106
106
 
107
107
  @override
108
108
  async def _get_definition(self) -> UaObjectDefinition:
@@ -32,7 +32,7 @@ async def reset_skill_and_wait(skill: AbstractSkill, *, timeout: float | None =
32
32
  async with asyncio.timeout(timeout):
33
33
  await skill.wait_for_state(SkillState.HALTED)
34
34
 
35
- if skill.current_state in (SkillState.HALTED, SkillState.SUSPENDED, SkillState.COMPLETED):
35
+ if skill.current_state in (SkillState.HALTED, SkillState.COMPLETED): # the states with a Reset transition
36
36
  _LOGGER.debug("Resetting skill...", skill_name=skill.path)
37
37
  await skill.reset()
38
38
  # resetting takes time, we need to wait until the skill is actually ready!
@@ -41,15 +41,16 @@ async def reset_skill_and_wait(skill: AbstractSkill, *, timeout: float | None =
41
41
 
42
42
 
43
43
  async def halt_skill_and_wait(skill: AbstractSkill, *, timeout: float | None = 60.0) -> None:
44
- """Halt the given skill and wait until it finished and is in the Halted state."""
44
+ """Halt the given skill and wait until it is in the Halted state, also if it was already halting."""
45
45
  try:
46
46
  _LOGGER.debug("Trying to halt skill...", skill_name=skill.path)
47
- await skill.halt()
47
+ try:
48
+ await skill.halt()
49
+ except (BadInvalidState, MachineError):
50
+ pass # already halting or halted; either way, wait for Halted below
48
51
  # halting takes time, we need to wait until the skill is actually halted!
49
52
  async with asyncio.timeout(timeout):
50
53
  await skill.wait_for_state(SkillState.HALTED)
51
- except (BadInvalidState, MachineError):
52
- pass # assume that skill is already halted
53
54
  except (Exception, asyncio.CancelledError) as ex:
54
55
  msg = f"Could not halt skill '{skill.name}'!"
55
56
  raise OpenSmiRuntimeError(msg) from ex
@@ -0,0 +1,39 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Python docstrings as OPC UA descriptions."""
6
+
7
+ import inspect
8
+ import re
9
+
10
+ _LIST_ITEM = re.compile(r"(?:[-*]|\d+\.) ")
11
+
12
+
13
+ def description_from_docstring(docstring: str | None) -> str | None:
14
+ """Turn a docstring into an OPC UA description, which is Markdown.
15
+
16
+ The indentation is removed and the lines of a paragraph are joined, so docstrings can be wrapped as usual and
17
+ clients that show the text as is don't break it in the middle of a sentence. Paragraphs stay separated by a blank
18
+ line and list items (lines starting with ``-``, ``*`` or a number like ``1.``) stay on their own lines. Markup is
19
+ kept.
20
+
21
+ :return: The description, or ``None`` if the docstring is empty.
22
+ """
23
+ text = inspect.cleandoc(docstring or "")
24
+ paragraphs = (_unwrap(paragraph) for paragraph in text.split("\n\n"))
25
+ return "\n\n".join(paragraph for paragraph in paragraphs if paragraph) or None
26
+
27
+
28
+ def _unwrap(paragraph: str) -> str:
29
+ """Join the wrapped lines of a paragraph; a list item starts a new line."""
30
+ lines: list[str] = []
31
+ for line in paragraph.splitlines():
32
+ line = line.strip() # noqa: PLW2901
33
+ if not line:
34
+ continue
35
+ if lines and not _LIST_ITEM.match(line):
36
+ lines[-1] = f"{lines[-1]} {line}"
37
+ else:
38
+ lines.append(line)
39
+ return "\n".join(lines)
@@ -4,12 +4,12 @@
4
4
 
5
5
  """Mixin for initializing the OPC UA description of `UaObject` using their Python docstrings."""
6
6
 
7
- import inspect
8
7
  from abc import ABC
9
8
  from collections.abc import AsyncGenerator
10
9
 
11
10
  from opensmi.core.lifecycle_mixin import lifecycle
12
11
 
12
+ from opensmi.server.docstrings import description_from_docstring
13
13
  from opensmi.server.interfaces import AbstractUaObject
14
14
 
15
15
 
@@ -18,9 +18,9 @@ class DescriptionMixin(AbstractUaObject, ABC):
18
18
 
19
19
  @lifecycle
20
20
  async def lifecycle_description(self) -> AsyncGenerator[None]:
21
- """Initialize the `Lock` for an `UaObject`."""
21
+ """Write the class docstring as OPC UA description."""
22
22
  # Note: inspect.getdoc() would also access inherited docstrings, which is unwanted behavior here
23
- description: str | None = inspect.cleandoc(type(self).__doc__ or "") or None
23
+ description = description_from_docstring(type(self).__doc__)
24
24
  if description:
25
25
  await self.write_description(description)
26
26
  else:
@@ -73,12 +73,16 @@ class _SkillLogicMixin(AbstractSkill, AbstractUaLogger):
73
73
  self._resume_event: asyncio.Event = asyncio.Event()
74
74
  self._resume_event.set() # not suspended by default
75
75
  self._paused_event: asyncio.Event = asyncio.Event()
76
+ self._execution_counted = False
77
+ """Whether the current execution was counted in ``SuccessfulExecutionsCount``."""
76
78
 
77
79
  self._machine: UaFiniteStateMachine[SkillState] = UaFiniteStateMachine(
78
80
  name=f"{self.name}_StateMachine",
79
81
  states=SkillState,
80
82
  initial=SkillState.HALTED,
81
83
  write_func=self._write_current_state,
84
+ # a Start whose conditions wait, e.g. a custom start condition, must not override a Halt that came meanwhile
85
+ drop_if_state_changed=("start",),
82
86
  )
83
87
  """Skill Finite State Machine."""
84
88
  self._add_transitions()
@@ -134,8 +138,20 @@ class _SkillLogicMixin(AbstractSkill, AbstractUaLogger):
134
138
 
135
139
  async def _after_resetting(self, *args, **kwargs) -> None:
136
140
  """Is called by the finite state machine after the `SkillState.RESETTING` state is entered."""
141
+ self._execution_counted = False # every execution starts from Ready, which is only reached through Resetting
137
142
  await self._wrap_handle_method(handle_method=self._handle_resetting, success_trigger="resetting_done")
138
143
 
144
+ async def _count_successful_execution(self) -> None:
145
+ """Increment ``SuccessfulExecutionsCount`` of the final result data, if the skill has one."""
146
+ counter = getattr(getattr(self, "final_result_data", None), "SuccessfulExecutionsCount", None)
147
+ if counter is None:
148
+ return
149
+ old_value: int | None = await counter.read()
150
+ new_value = old_value + 1 if old_value is not None else 1
151
+ await counter.write(new_value)
152
+ self._execution_counted = True
153
+ self.logger.debug("Updated successful executions count", new_value=new_value)
154
+
139
155
  async def _after_halting(self, *args, **kwargs) -> None:
140
156
  """Is called by the finite state machine after the `SkillState.HALTING` state is entered."""
141
157
  # prevent infinite loop
@@ -368,10 +384,11 @@ class _SkillLogicMixin(AbstractSkill, AbstractUaLogger):
368
384
 
369
385
 
370
386
  class BaseSkillFinalResultData(FinalResultData):
371
- """Base final result data for finite skills."""
387
+ """Base final result data for skills, counting their successful executions."""
372
388
 
373
- SuccessfulExecutionsCount = UaVariable(0)
374
- """Number of successful executions of this skill since server start."""
389
+ SuccessfulExecutionsCount = UaVariable(0, resettable=False)
390
+ """Number of successful executions of this skill since server start. A finite skill counts when it reaches
391
+ Completed, a continuous skill once per start from Ready. Not reset by Reset."""
375
392
 
376
393
 
377
394
  class ContinuousSkillLogicMixin(_SkillLogicMixin):
@@ -383,11 +400,13 @@ class ContinuousSkillLogicMixin(_SkillLogicMixin):
383
400
 
384
401
  @override
385
402
  async def _after_running(self, *args, **kwargs):
386
- """Is called by the finite state machine after `SkillState.RUNNING` is entered."""
387
- with contextlib.suppress(AttributeError):
388
- old_value = await self.final_result_data.SuccessfulExecutionsCount.read() # pyright: ignore[reportAttributeAccessIssue]
389
- new_value = old_value + 1 if old_value is not None else 1
390
- await self.final_result_data.SuccessfulExecutionsCount.write(new_value) # pyright: ignore[reportAttributeAccessIssue]
403
+ """Is called by the finite state machine after `SkillState.RUNNING` is entered.
404
+
405
+ A continuous skill never completes, so an execution counts as successful once it is running. Resuming from
406
+ `SkillState.SUSPENDED` continues the same execution and isn't counted again.
407
+ """
408
+ if not self._execution_counted:
409
+ await self._count_successful_execution()
391
410
 
392
411
  await self._wrap_handle_method(handle_method=self._handle_running, success_trigger=None)
393
412
 
@@ -435,15 +454,17 @@ class FiniteSkillLogicMixin(_SkillLogicMixin):
435
454
  await self._suspend_point()
436
455
 
437
456
  async def _after_completing(self, *args, **kwargs):
438
- """Is called by the finite state machine after the `SkillState.COMPLETED` state is entered."""
439
- # Update successful executions count if it exists
440
- with contextlib.suppress(AttributeError):
441
- old_value: int = await self.final_result_data.SuccessfulExecutionsCount.read() # pyright: ignore[reportAttributeAccessIssue]
442
- new_value = old_value + 1 if old_value is not None else 1
443
- await self.final_result_data.SuccessfulExecutionsCount.write(new_value) # pyright: ignore[reportAttributeAccessIssue]
444
- self.logger.debug("Updated successful executions count", new_value=new_value)
445
-
446
- await self._wrap_handle_method(handle_method=self._handle_completing, success_trigger="completing_done")
457
+ """Is called by the finite state machine after the `SkillState.COMPLETING` state is entered."""
458
+ await self._wrap_handle_method(handle_method=self._complete_and_count, success_trigger="completing_done")
459
+
460
+ async def _complete_and_count(self) -> None:
461
+ """Run `_handle_completing`, then count the execution as successful.
462
+
463
+ Counted before the skill reaches `SkillState.COMPLETED`, so a client seeing Completed reads the new count. A
464
+ failing `_handle_completing` halts the skill and isn't counted.
465
+ """
466
+ await self._handle_completing()
467
+ await self._count_successful_execution()
447
468
 
448
469
  async def _handle_completing(self) -> None:
449
470
  """Handle user-specific logic during the `SkillState.COMPLETING` state.
@@ -8,20 +8,63 @@ from __future__ import annotations
8
8
 
9
9
  from collections.abc import Awaitable, Callable, Iterable
10
10
  from enum import Enum
11
- from typing import Generic, TypeVar
11
+ from typing import Generic, TypeVar, cast
12
12
 
13
13
  import structlog
14
14
  from asyncua import ua
15
15
  from asyncua.common.node import Node
16
16
  from asyncua.ua.status_codes import StatusCodes as UaStatusCodes
17
17
  from transitions import MachineError
18
- from transitions.extensions.asyncio import AsyncMachine
18
+ from transitions.extensions.asyncio import AsyncEventData, AsyncMachine, AsyncTransition
19
19
 
20
20
  from opensmi.server.protocols import UserProtocol
21
21
 
22
22
  _StateType = TypeVar("_StateType", bound=Enum)
23
23
 
24
24
 
25
+ class _AsyncTransition(AsyncTransition):
26
+ """Transition that does not happen if the state changed while its conditions were checked.
27
+
28
+ ``transitions`` determines the source state when a trigger begins and sets the destination after the conditions,
29
+ without checking the state again. A condition may wait, e.g. a custom start condition for the answer of a device,
30
+ and meanwhile another trigger may change the state, e.g. a Halt. For a trigger in
31
+ ``_AsyncMachine.drop_if_state_changed``, the transition then does not happen.
32
+ """
33
+
34
+ async def _eval_conditions(self, event_data: AsyncEventData) -> bool:
35
+ machine = cast("_AsyncMachine", event_data.machine)
36
+ state_changes = machine.state_changes
37
+ if not await super()._eval_conditions(event_data):
38
+ return False
39
+ if machine.state_changes != state_changes and event_data.event.name in machine.drop_if_state_changed:
40
+ cast("UaFiniteStateMachine[Enum]", event_data.model).logger.info(
41
+ "Transition dropped, the state changed while its conditions were checked",
42
+ trigger_func=event_data.event.name,
43
+ source=self.source,
44
+ dest=self.dest,
45
+ )
46
+ return False
47
+ return True
48
+
49
+ async def _change_state(self, event_data: AsyncEventData) -> None:
50
+ # count before the first await, so that a transition whose conditions end meanwhile sees the change
51
+ cast("_AsyncMachine", event_data.machine).state_changes += 1
52
+ await super()._change_state(event_data)
53
+
54
+
55
+ class _AsyncMachine(AsyncMachine):
56
+ """``AsyncMachine`` that counts the state changes and uses ``_AsyncTransition``."""
57
+
58
+ transition_cls = _AsyncTransition
59
+
60
+ def __init__(self, *, drop_if_state_changed: Iterable[str] = (), **kwargs) -> None:
61
+ self.state_changes = 0
62
+ """Number of state changes so far."""
63
+ self.drop_if_state_changed = frozenset(drop_if_state_changed)
64
+ """Triggers whose transition does not happen if the state changed while its conditions were checked."""
65
+ super().__init__(**kwargs)
66
+
67
+
25
68
  class UaFiniteStateMachine(Generic[_StateType]):
26
69
  """Finite state machine with OPC-UA representation based on ``transitions`` library."""
27
70
 
@@ -37,6 +80,7 @@ class UaFiniteStateMachine(Generic[_StateType]):
37
80
  states: Iterable[_StateType],
38
81
  initial: _StateType,
39
82
  write_func: Callable[[_StateType], Awaitable[None]],
83
+ drop_if_state_changed: Iterable[str] = (),
40
84
  ) -> None:
41
85
  """Create a new instance.
42
86
 
@@ -44,15 +88,19 @@ class UaFiniteStateMachine(Generic[_StateType]):
44
88
  :param states: States of the state machine.
45
89
  :param initial: Initial state of the state machine.
46
90
  :param write_func: Async callback to write the current state.
91
+ :param drop_if_state_changed: Triggers whose transition does not happen if the state changed while its
92
+ conditions were checked, e.g. by a Halt while a custom start condition waits. For these triggers,
93
+ ``try_trigger()`` answers ``BadInvalidState`` if the transition did not happen.
47
94
  """
48
95
  self.name = name
49
96
  self.logger = structlog.getLogger("opensmi.UaFiniteStateMachine", name=name)
50
- self._internal_machine = AsyncMachine(
97
+ self._internal_machine = _AsyncMachine(
51
98
  model=self,
52
99
  name=name,
53
100
  states=tuple(states),
54
101
  initial=initial,
55
102
  auto_transitions=False,
103
+ drop_if_state_changed=drop_if_state_changed,
56
104
  # after_state_change=self._after_state_change,
57
105
  )
58
106
  # Note: machine.after_state_change triggers too late, so use each state's on_enter callback
@@ -95,6 +143,7 @@ class UaFiniteStateMachine(Generic[_StateType]):
95
143
  """Try to trigger an event in the internal state machine.
96
144
 
97
145
  Handles expected exceptions due to wrong state and UaStatusCodeError exceptions due to unsatisfied conditions.
146
+ For a trigger in ``drop_if_state_changed``, a transition that did not happen answers ``BadInvalidState``.
98
147
 
99
148
  :param user: User which triggers the event.
100
149
  :param trigger_func: Name of the trigger function.
@@ -105,7 +154,12 @@ class UaFiniteStateMachine(Generic[_StateType]):
105
154
  # noinspection PyUnresolvedReferences
106
155
  # try to call the trigger function, defined during runtime by transitions library
107
156
  self.logger.debug("Trying to trigger...", trigger_func=trigger_func)
108
- await self.trigger(trigger_func, user) # type: ignore
157
+ happened = await self.trigger(trigger_func, user) # type: ignore
158
+ if not happened and trigger_func in self._internal_machine.drop_if_state_changed:
159
+ # the state changed while the conditions were checked, a Halt cancelled the trigger, or a condition
160
+ # returned False instead of raising
161
+ self.logger.info("Transition did not happen", trigger_func=trigger_func)
162
+ return ua.StatusCode(ua.UInt32(UaStatusCodes.BadInvalidState))
109
163
  return ua.StatusCode(ua.UInt32(UaStatusCodes.Good))
110
164
  except MachineError as e:
111
165
  self.logger.warning("State machine error", error=e.value, trigger_func=trigger_func)
@@ -135,6 +135,7 @@ class UaVariable(NotificationForwarderMixin, UaObject, Generic[_VariableType]):
135
135
  ua_value_rank: ua.ValueRank | int | None = None,
136
136
  ua_data_type: ua.NodeId | int | None = None,
137
137
  display_name: str | None = None,
138
+ resettable: bool = True,
138
139
  **kwargs,
139
140
  ) -> None:
140
141
  """*Cooperative* constructor for a new variable instance.
@@ -163,6 +164,8 @@ class UaVariable(NotificationForwarderMixin, UaObject, Generic[_VariableType]):
163
164
  :param ua_data_type: (Optional) OPC UA data type of the variable. **Advanced**, make sure this type maps to
164
165
  the Python type! You could use this for UInt16, etc. instead of default Int64 types
165
166
  :param display_name: (Optional) OPC UA display name of the variable. Defaults to the name.
167
+ :param resettable: Whether `UaVariableContainer.reset_all` resets the variable. ``False`` for values that must
168
+ survive it, e.g. counters since server start. An explicit `reset` always resets.
166
169
  """
167
170
  super().__init__(minimum_access_level=minimum_access_level, bypass_lock=bypass_lock, name=name, **kwargs)
168
171
 
@@ -191,6 +194,7 @@ class UaVariable(NotificationForwarderMixin, UaObject, Generic[_VariableType]):
191
194
  self._historize: bool = historize
192
195
  self._references: set[UaObject] = set()
193
196
  self.optional_ok: bool = optional_ok
197
+ self._resettable: bool = resettable
194
198
  self._write_check_callback = write_check_callback
195
199
  self._dictionary_entry: DictionaryEntry | None = dictionary_entry
196
200
  self.description: str | None = description
@@ -658,8 +662,13 @@ class UaVariable(NotificationForwarderMixin, UaObject, Generic[_VariableType]):
658
662
  except NoValidValueReadError:
659
663
  return None
660
664
 
665
+ @property
666
+ def resettable(self) -> bool:
667
+ """Whether `UaVariableContainer.reset_all` resets this variable."""
668
+ return self._resettable
669
+
661
670
  async def reset(self) -> None:
662
- """Reset variable to initial value."""
671
+ """Reset variable to initial value, also if it isn't `resettable`."""
663
672
  await self.write(self._initial_value)
664
673
 
665
674
  def check_range(self, value: _VariableType | ua.Variant | None) -> bool:
@@ -707,6 +716,7 @@ class UaVariable(NotificationForwarderMixin, UaObject, Generic[_VariableType]):
707
716
  ua_value_rank=self._ua_value_rank,
708
717
  ua_data_type=self._ua_data_type,
709
718
  display_name=self._display_name,
719
+ resettable=self._resettable,
710
720
  )
711
721
 
712
722
  @override
@@ -24,6 +24,7 @@ from opensmi.core.paths import check_segment
24
24
  from opensmi.core.ua_node_util import get_properties
25
25
  from typing_extensions import override
26
26
 
27
+ from opensmi.server.docstrings import description_from_docstring
27
28
  from opensmi.server.mixins.notification_mixins import NotificationForwarderMixin
28
29
  from opensmi.server.ua_object import UaObject, UaObjectDefinition
29
30
  from opensmi.server.ua_variable import UaVariable
@@ -57,8 +58,9 @@ def collect_attr_docs(cls: type) -> dict[str, str]:
57
58
 
58
59
  for t in targets:
59
60
  if isinstance(t, ast.Name): # skip things like self.x or a[0]
60
- # cleandoc strips the indentation and surrounding blank lines
61
- docs[t.id] = inspect.cleandoc(nxt.value.value)
61
+ description = description_from_docstring(nxt.value.value)
62
+ if description:
63
+ docs[t.id] = description
62
64
  return docs
63
65
 
64
66
 
@@ -326,9 +328,10 @@ class UaVariableContainer(NotificationForwarderMixin, UaObject):
326
328
  # )
327
329
 
328
330
  async def reset_all(self) -> None:
329
- """Reset all contained `UaVariable` to their initial value."""
331
+ """Reset all contained `UaVariable` to their initial value, except those created with ``resettable=False``."""
330
332
  for variable in self:
331
- await variable.reset()
333
+ if variable.resettable:
334
+ await variable.reset()
332
335
  for group in self._groups.values():
333
336
  await group.reset_all()
334
337
 
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "0.4",
3
- "distance": 0,
4
- "node": "gc202fd0d37771889b43242a1884c52606d8de110",
5
- "dirty": false,
6
- "branch": "HEAD",
7
- "node_date": "2026-11-19"
8
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes