vention-state-machine 0.4__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.
- state_machine/__init__.py +0 -0
- state_machine/core.py +303 -0
- state_machine/decorator_manager.py +102 -0
- state_machine/decorator_protocols.py +23 -0
- state_machine/decorators.py +116 -0
- state_machine/defs.py +100 -0
- state_machine/machine_protocols.py +33 -0
- state_machine/utils.py +82 -0
- state_machine/vention_communication.py +167 -0
- vention_state_machine-0.4.0.dist-info/METADATA +407 -0
- vention_state_machine-0.4.0.dist-info/RECORD +12 -0
- vention_state_machine-0.4.0.dist-info/WHEEL +4 -0
|
File without changes
|
state_machine/core.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
# mypy: disable-error-code=misc
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections import deque
|
|
5
|
+
from collections.abc import Coroutine
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Any, Callable, Optional, Union, List
|
|
8
|
+
from transitions.extensions import HierarchicalGraphMachine
|
|
9
|
+
from transitions.core import State, Condition
|
|
10
|
+
from state_machine.defs import StateGroup
|
|
11
|
+
from enum import Enum
|
|
12
|
+
from state_machine.decorator_manager import DecoratorManager
|
|
13
|
+
from state_machine.utils import is_state_container
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BaseStates(str, Enum):
|
|
17
|
+
"""Base states that all state machines include."""
|
|
18
|
+
|
|
19
|
+
READY = "ready"
|
|
20
|
+
FAULT = "fault"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BaseTriggers(str, Enum):
|
|
24
|
+
"""Base triggers that all state machines include."""
|
|
25
|
+
|
|
26
|
+
START = "start"
|
|
27
|
+
RESET = "reset"
|
|
28
|
+
TO_FAULT = "to_fault"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
StateDict = dict[str, object]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class StateMachine(HierarchicalGraphMachine):
|
|
35
|
+
"""
|
|
36
|
+
State Machine wrapping `HierarchicalGraphMachine` with:
|
|
37
|
+
- Default states: 'ready', 'fault'
|
|
38
|
+
- Global transitions: 'to_fault', 'reset'
|
|
39
|
+
- Async task tracking (spawn/cancel)
|
|
40
|
+
- Auto-timeout support via decorator
|
|
41
|
+
- Recoverable last-state functionality
|
|
42
|
+
- Transition history recording
|
|
43
|
+
- Decorator-based entry/exit hooks
|
|
44
|
+
- Guard conditions for transitions
|
|
45
|
+
- Global state change callbacks
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
DEFAULT_HISTORY_SIZE: int = 1000
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
states: Union[object, list[StateDict], None] = None,
|
|
53
|
+
*,
|
|
54
|
+
transitions: Optional[list[dict[str, str]]] = None,
|
|
55
|
+
history_size: Optional[int] = None,
|
|
56
|
+
enable_last_state_recovery: bool = True,
|
|
57
|
+
**kw: Any,
|
|
58
|
+
) -> None:
|
|
59
|
+
# Normalize state definitions
|
|
60
|
+
if is_state_container(states):
|
|
61
|
+
state_groups = [
|
|
62
|
+
value
|
|
63
|
+
for value in vars(states).values()
|
|
64
|
+
if isinstance(value, StateGroup)
|
|
65
|
+
]
|
|
66
|
+
resolved_states = [group.to_state_list()[0] for group in state_groups]
|
|
67
|
+
elif isinstance(states, list):
|
|
68
|
+
resolved_states = states
|
|
69
|
+
else:
|
|
70
|
+
raise TypeError(
|
|
71
|
+
f"`states` must be either a StateGroup container or a list of state dicts. "
|
|
72
|
+
f"Got: {type(states).__name__}"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
self._declared_states: list[dict[str, Any]] = resolved_states
|
|
76
|
+
|
|
77
|
+
self._decorator_manager = DecoratorManager(self)
|
|
78
|
+
self._decorator_manager.discover_decorated_handlers(self.__class__)
|
|
79
|
+
|
|
80
|
+
# Initialize base machine
|
|
81
|
+
combined_states = self._declared_states + [
|
|
82
|
+
BaseStates.READY.value,
|
|
83
|
+
BaseStates.FAULT.value,
|
|
84
|
+
]
|
|
85
|
+
super().__init__(
|
|
86
|
+
states=combined_states,
|
|
87
|
+
transitions=transitions or [],
|
|
88
|
+
initial="ready",
|
|
89
|
+
send_event=True,
|
|
90
|
+
**kw,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Internal tracking
|
|
94
|
+
self._tasks: set[asyncio.Task[Any]] = set()
|
|
95
|
+
self._timeouts: dict[str, asyncio.Task[Any]] = {}
|
|
96
|
+
self._last_state: Optional[str] = None
|
|
97
|
+
self._enable_recovery: bool = enable_last_state_recovery
|
|
98
|
+
self._history: deque[dict[str, Any]] = deque(
|
|
99
|
+
maxlen=history_size or self.DEFAULT_HISTORY_SIZE
|
|
100
|
+
)
|
|
101
|
+
self._current_start: Optional[datetime] = None
|
|
102
|
+
self._guard_conditions: dict[str, List[Callable[[], bool]]] = {}
|
|
103
|
+
self._state_change_callbacks: List[Callable[[str, str, str], None]] = []
|
|
104
|
+
|
|
105
|
+
self._decorator_manager.bind_decorated_handlers(self)
|
|
106
|
+
self._add_recovery_transitions()
|
|
107
|
+
self.add_transition(
|
|
108
|
+
BaseTriggers.TO_FAULT.value,
|
|
109
|
+
"*",
|
|
110
|
+
BaseStates.FAULT.value,
|
|
111
|
+
before="cancel_tasks",
|
|
112
|
+
)
|
|
113
|
+
self.add_transition(
|
|
114
|
+
BaseTriggers.RESET.value, BaseStates.FAULT.value, BaseStates.READY.value
|
|
115
|
+
)
|
|
116
|
+
self._attach_after_hooks()
|
|
117
|
+
self._add_guard_conditions_to_transitions()
|
|
118
|
+
|
|
119
|
+
def spawn(self, coro: Coroutine[Any, Any, Any]) -> asyncio.Task[Any]:
|
|
120
|
+
"""
|
|
121
|
+
Start an async background task and track it for potential cancellation.
|
|
122
|
+
"""
|
|
123
|
+
task: asyncio.Task[Any] = asyncio.create_task(coro)
|
|
124
|
+
self._tasks.add(task)
|
|
125
|
+
task.add_done_callback(lambda _: self._tasks.discard(task))
|
|
126
|
+
return task
|
|
127
|
+
|
|
128
|
+
async def cancel_tasks(self, *_: Any) -> None:
|
|
129
|
+
"""
|
|
130
|
+
Cancel all tracked background tasks and clear any timeouts.
|
|
131
|
+
"""
|
|
132
|
+
self._clear_all_timeouts()
|
|
133
|
+
for task in list(self._tasks):
|
|
134
|
+
task.cancel()
|
|
135
|
+
try:
|
|
136
|
+
await task
|
|
137
|
+
except asyncio.CancelledError:
|
|
138
|
+
pass
|
|
139
|
+
|
|
140
|
+
def set_timeout(
|
|
141
|
+
self, state_name: str, seconds: float, trigger_fn: Callable[[], str]
|
|
142
|
+
) -> None:
|
|
143
|
+
"""
|
|
144
|
+
Schedule a timeout: if `state_name` remains active after `seconds`, fire `trigger_fn()`.
|
|
145
|
+
"""
|
|
146
|
+
self._clear_timeout(state_name)
|
|
147
|
+
|
|
148
|
+
async def _timeout_task() -> None:
|
|
149
|
+
await asyncio.sleep(seconds)
|
|
150
|
+
if self.state == state_name:
|
|
151
|
+
self.trigger(trigger_fn())
|
|
152
|
+
|
|
153
|
+
self._timeouts[state_name] = self.spawn(_timeout_task())
|
|
154
|
+
|
|
155
|
+
def _clear_timeout(self, state_name: str) -> None:
|
|
156
|
+
"""Cancel a pending timeout for the given state."""
|
|
157
|
+
task = self._timeouts.pop(state_name, None)
|
|
158
|
+
if task:
|
|
159
|
+
task.cancel()
|
|
160
|
+
|
|
161
|
+
def _clear_all_timeouts(self) -> None:
|
|
162
|
+
"""Cancel all pending state timeouts."""
|
|
163
|
+
for timeout in self._timeouts.values():
|
|
164
|
+
timeout.cancel()
|
|
165
|
+
self._timeouts.clear()
|
|
166
|
+
|
|
167
|
+
def record_last_state(self) -> None:
|
|
168
|
+
"""Manually record the current state for later recovery."""
|
|
169
|
+
self._last_state = self.state
|
|
170
|
+
|
|
171
|
+
def get_last_state(self) -> Optional[str]:
|
|
172
|
+
"""Get the most recently recorded recoverable state."""
|
|
173
|
+
return self._last_state
|
|
174
|
+
|
|
175
|
+
def start(self) -> None:
|
|
176
|
+
"""
|
|
177
|
+
Enter the machine: if recovery is enabled and a state was recorded, fire the
|
|
178
|
+
corresponding recover__ transition; otherwise fire 'start'.
|
|
179
|
+
"""
|
|
180
|
+
if self._enable_recovery and self._last_state:
|
|
181
|
+
self.trigger(f"recover__{self._last_state}")
|
|
182
|
+
else:
|
|
183
|
+
self.trigger(BaseTriggers.START.value)
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def history(self) -> list[dict[str, Any]]:
|
|
187
|
+
"""Get the full transition history with timestamps and durations."""
|
|
188
|
+
return list(self._history)
|
|
189
|
+
|
|
190
|
+
def get_last_history_entries(self, n: int = 10) -> list[dict[str, Any]]:
|
|
191
|
+
"""Get the last `n` history entries."""
|
|
192
|
+
return list(self._history)[-n:] if n > 0 else []
|
|
193
|
+
|
|
194
|
+
def add_transition_condition(
|
|
195
|
+
self, trigger_name: str, condition_fn: Callable[[], bool]
|
|
196
|
+
) -> None:
|
|
197
|
+
"""
|
|
198
|
+
Add a guard condition to a transition trigger.
|
|
199
|
+
Multiple conditions can be added for the same trigger - ALL must pass for the transition to be allowed.
|
|
200
|
+
"""
|
|
201
|
+
if trigger_name not in self._guard_conditions:
|
|
202
|
+
self._guard_conditions[trigger_name] = []
|
|
203
|
+
self._guard_conditions[trigger_name].append(condition_fn)
|
|
204
|
+
|
|
205
|
+
def add_state_change_callback(
|
|
206
|
+
self, callback: Callable[[str, str, str], None]
|
|
207
|
+
) -> None:
|
|
208
|
+
"""
|
|
209
|
+
Add a callback that fires on any state change.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
callback: Function that takes (old_state, new_state, trigger_name) as arguments
|
|
213
|
+
"""
|
|
214
|
+
self._state_change_callbacks.append(callback)
|
|
215
|
+
|
|
216
|
+
# -- Private helpers --
|
|
217
|
+
def _run_enter_callbacks(self, state_name: str) -> None:
|
|
218
|
+
state_obj = self.get_state(state_name)
|
|
219
|
+
for callback in getattr(state_obj, "enter", []):
|
|
220
|
+
callback(None)
|
|
221
|
+
|
|
222
|
+
def on_enter_ready(self, _: Any) -> None:
|
|
223
|
+
if not self._enable_recovery:
|
|
224
|
+
self._last_state = None
|
|
225
|
+
|
|
226
|
+
def _is_leaf(self, state: Union[State, str]) -> bool:
|
|
227
|
+
state_data = self.get_state(state) if isinstance(state, str) else state
|
|
228
|
+
return not getattr(state_data, "children", [])
|
|
229
|
+
|
|
230
|
+
def _record_history_event(self, event: Any) -> None:
|
|
231
|
+
now = datetime.now(timezone.utc)
|
|
232
|
+
dest = event.transition.dest
|
|
233
|
+
if self._history and self._current_start is not None:
|
|
234
|
+
elapsed = (now - self._current_start).total_seconds() * 1000
|
|
235
|
+
self._history[-1]["duration_ms"] = int(elapsed)
|
|
236
|
+
self._history.append({"timestamp": now, "state": dest})
|
|
237
|
+
self._current_start = now
|
|
238
|
+
if self._is_leaf(dest) and dest not in {
|
|
239
|
+
BaseStates.READY.value,
|
|
240
|
+
BaseStates.FAULT.value,
|
|
241
|
+
}:
|
|
242
|
+
self._last_state = dest
|
|
243
|
+
|
|
244
|
+
def _attach_after_hooks(self) -> None:
|
|
245
|
+
# Attach after hooks to all transitions in all events
|
|
246
|
+
for _, event in self.events.items():
|
|
247
|
+
# Loop over all transitions for this event
|
|
248
|
+
for transitions_for_source in event.transitions.values():
|
|
249
|
+
# Add our custom callbacks to each transition
|
|
250
|
+
for transition in transitions_for_source:
|
|
251
|
+
transition.add_callback("after", self._record_history_event)
|
|
252
|
+
transition.add_callback("after", self._attach_exit_timeout_clear)
|
|
253
|
+
transition.add_callback("after", self._notify_state_change_callback)
|
|
254
|
+
|
|
255
|
+
def _attach_exit_timeout_clear(self, event: Any) -> None:
|
|
256
|
+
self._clear_timeout(event.transition.source)
|
|
257
|
+
|
|
258
|
+
def _add_recovery_transitions(self) -> None:
|
|
259
|
+
for state_spec in self._declared_states:
|
|
260
|
+
parent_name = state_spec["name"]
|
|
261
|
+
for child_spec in state_spec.get("children", []):
|
|
262
|
+
full_state_name = f"{parent_name}_{child_spec['name']}"
|
|
263
|
+
self.add_transition(
|
|
264
|
+
f"recover__{full_state_name}",
|
|
265
|
+
BaseStates.READY.value,
|
|
266
|
+
full_state_name,
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
def _add_guard_conditions_to_transitions(self) -> None:
|
|
270
|
+
"""Add guard conditions to transitions using the transitions library's condition system."""
|
|
271
|
+
for trigger_name, guard_fns in self._guard_conditions.items():
|
|
272
|
+
if trigger_name not in self.events:
|
|
273
|
+
continue
|
|
274
|
+
|
|
275
|
+
event = self.events[trigger_name]
|
|
276
|
+
condition = self._create_guard_condition(guard_fns)
|
|
277
|
+
|
|
278
|
+
for transitions_for_source in event.transitions.values():
|
|
279
|
+
for transition in transitions_for_source:
|
|
280
|
+
transition.conditions.append(condition)
|
|
281
|
+
|
|
282
|
+
def _create_guard_condition(self, guard_fns: List[Callable[[], bool]]) -> Condition:
|
|
283
|
+
"""Create a condition function for the transitions library."""
|
|
284
|
+
|
|
285
|
+
def condition(_: Any) -> bool:
|
|
286
|
+
for guard_fn in guard_fns:
|
|
287
|
+
if not guard_fn():
|
|
288
|
+
return False
|
|
289
|
+
return True
|
|
290
|
+
|
|
291
|
+
return Condition(condition)
|
|
292
|
+
|
|
293
|
+
def _notify_state_change_callback(self, event: Any) -> None:
|
|
294
|
+
"""Notify state change callbacks after successful transition."""
|
|
295
|
+
trigger_name = event.event.name
|
|
296
|
+
old_state = event.transition.source
|
|
297
|
+
new_state = event.transition.dest
|
|
298
|
+
|
|
299
|
+
for callback in self._state_change_callbacks:
|
|
300
|
+
try:
|
|
301
|
+
callback(old_state, new_state, trigger_name)
|
|
302
|
+
except Exception as e:
|
|
303
|
+
print(f"Error in state change callback: {e}")
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
from typing import Any, Callable, cast
|
|
2
|
+
from state_machine.utils import wrap_with_timeout
|
|
3
|
+
from state_machine.machine_protocols import (
|
|
4
|
+
StateMachineProtocol,
|
|
5
|
+
)
|
|
6
|
+
from typing_extensions import TypeAlias
|
|
7
|
+
|
|
8
|
+
StateCallbackBinding: TypeAlias = tuple[str, str, Any]
|
|
9
|
+
GuardBinding: TypeAlias = tuple[str, Callable[[], bool]]
|
|
10
|
+
StateChangeCallback: TypeAlias = Callable[[str, str, str], None]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DecoratorManager:
|
|
14
|
+
"""
|
|
15
|
+
Manages discovery and binding of decorator-based lifecycle hooks
|
|
16
|
+
(`on_enter_state`, `on_exit_state`, `auto_timeout`, `guard`, and `on_state_change`) to a state machine instance.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, machine: StateMachineProtocol) -> None:
|
|
20
|
+
self.machine = machine
|
|
21
|
+
self._decorator_bindings: list[StateCallbackBinding] = []
|
|
22
|
+
self._exit_decorator_bindings: list[StateCallbackBinding] = []
|
|
23
|
+
self._guard_bindings: list[GuardBinding] = []
|
|
24
|
+
self._state_change_callbacks: list[StateChangeCallback] = []
|
|
25
|
+
|
|
26
|
+
def discover_decorated_handlers(self, target_class: type) -> None:
|
|
27
|
+
"""
|
|
28
|
+
Collect decorated methods from a class definition.
|
|
29
|
+
You must call this on the class object before instantiating.
|
|
30
|
+
"""
|
|
31
|
+
for attr in dir(target_class):
|
|
32
|
+
callback_fn = getattr(target_class, attr, None)
|
|
33
|
+
if callable(callback_fn):
|
|
34
|
+
self._discover_state_callbacks(callback_fn)
|
|
35
|
+
self._discover_guard_conditions(callback_fn)
|
|
36
|
+
self._discover_state_change_callbacks(callback_fn)
|
|
37
|
+
|
|
38
|
+
def _discover_state_callbacks(self, callback_fn: Any) -> None:
|
|
39
|
+
"""Discover on_enter_state and on_exit_state decorators."""
|
|
40
|
+
if hasattr(callback_fn, "_on_enter_state"):
|
|
41
|
+
self._decorator_bindings.append(
|
|
42
|
+
(callback_fn._on_enter_state, "enter", callback_fn)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
if hasattr(callback_fn, "_on_exit_state"):
|
|
46
|
+
self._exit_decorator_bindings.append(
|
|
47
|
+
(callback_fn._on_exit_state, "exit", callback_fn)
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def _discover_guard_conditions(self, callback_fn: Any) -> None:
|
|
51
|
+
"""Discover guard decorators."""
|
|
52
|
+
if hasattr(callback_fn, "_guard_conditions"):
|
|
53
|
+
for trigger_name, guard_fn in callback_fn._guard_conditions.items():
|
|
54
|
+
self._guard_bindings.append((trigger_name, guard_fn))
|
|
55
|
+
|
|
56
|
+
def _discover_state_change_callbacks(self, callback_fn: Any) -> None:
|
|
57
|
+
"""Discover on_state_change decorators."""
|
|
58
|
+
if hasattr(callback_fn, "_state_change_callback"):
|
|
59
|
+
state_change_callback = cast(StateChangeCallback, callback_fn)
|
|
60
|
+
self._state_change_callbacks.append(state_change_callback)
|
|
61
|
+
|
|
62
|
+
def bind_decorated_handlers(self, instance: Any) -> None:
|
|
63
|
+
"""
|
|
64
|
+
After instantiating your class, call this with the instance.
|
|
65
|
+
Hooks will be registered onto the state machine, and timeouts applied if needed.
|
|
66
|
+
"""
|
|
67
|
+
self._bind_state_callbacks(instance)
|
|
68
|
+
self._bind_guard_conditions(instance)
|
|
69
|
+
self._bind_state_change_callbacks(instance)
|
|
70
|
+
|
|
71
|
+
def _bind_state_callbacks(self, instance: Any) -> None:
|
|
72
|
+
"""Bind state entry/exit callbacks."""
|
|
73
|
+
for state_name, hook_type, callback_fn in (
|
|
74
|
+
self._decorator_bindings + self._exit_decorator_bindings
|
|
75
|
+
):
|
|
76
|
+
bound_fn = callback_fn.__get__(instance)
|
|
77
|
+
|
|
78
|
+
if hook_type == "enter" and hasattr(callback_fn, "_timeout_config"):
|
|
79
|
+
handler = wrap_with_timeout(
|
|
80
|
+
bound_fn,
|
|
81
|
+
state_name,
|
|
82
|
+
callback_fn._timeout_config,
|
|
83
|
+
self.machine.set_timeout,
|
|
84
|
+
)
|
|
85
|
+
else:
|
|
86
|
+
handler = bound_fn
|
|
87
|
+
|
|
88
|
+
state_obj = self.machine.get_state(state_name)
|
|
89
|
+
if state_obj:
|
|
90
|
+
state_obj.add_callback(hook_type, handler)
|
|
91
|
+
|
|
92
|
+
def _bind_guard_conditions(self, instance: Any) -> None:
|
|
93
|
+
"""Bind guard conditions."""
|
|
94
|
+
for trigger_name, guard_fn in self._guard_bindings:
|
|
95
|
+
bound_guard = guard_fn.__get__(instance)
|
|
96
|
+
self.machine.add_transition_condition(trigger_name, bound_guard)
|
|
97
|
+
|
|
98
|
+
def _bind_state_change_callbacks(self, instance: Any) -> None:
|
|
99
|
+
"""Bind state change callbacks."""
|
|
100
|
+
for callback_fn in self._state_change_callbacks:
|
|
101
|
+
bound_callback = callback_fn.__get__(instance)
|
|
102
|
+
self.machine.add_state_change_callback(bound_callback)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from typing import Protocol, Callable, Any, Union
|
|
2
|
+
|
|
3
|
+
CallableType = Callable[..., Any]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SupportsGuardConditions(Protocol):
|
|
7
|
+
_guard_conditions: dict[str, CallableType]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SupportsStateChangeCallback(Protocol):
|
|
11
|
+
_state_change_callback: bool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SupportsEnterState(Protocol):
|
|
15
|
+
_on_enter_state: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SupportsExitState(Protocol):
|
|
19
|
+
_on_exit_state: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SupportsTimeoutConfig(Protocol):
|
|
23
|
+
_timeout_config: tuple[float, Union[str, Callable[[], str]]]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from typing import Union, Callable, cast
|
|
2
|
+
from .defs import State, Trigger
|
|
3
|
+
from .decorator_protocols import (
|
|
4
|
+
SupportsGuardConditions,
|
|
5
|
+
SupportsStateChangeCallback,
|
|
6
|
+
SupportsEnterState,
|
|
7
|
+
SupportsExitState,
|
|
8
|
+
SupportsTimeoutConfig,
|
|
9
|
+
CallableType,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def on_enter_state(
|
|
14
|
+
state_node: Union[str, State],
|
|
15
|
+
) -> Callable[[CallableType], CallableType]:
|
|
16
|
+
"""
|
|
17
|
+
Decorator to bind a function to the on-enter hook for a state.
|
|
18
|
+
Accepts a str or a State descriptor.
|
|
19
|
+
"""
|
|
20
|
+
if hasattr(state_node, "name"):
|
|
21
|
+
state_name = state_node.name
|
|
22
|
+
elif isinstance(state_node, str):
|
|
23
|
+
state_name = state_node
|
|
24
|
+
else:
|
|
25
|
+
raise TypeError(f"Expected a State or str, got {type(state_node)}")
|
|
26
|
+
|
|
27
|
+
def decorator(fn: CallableType) -> CallableType:
|
|
28
|
+
enter_fn: SupportsEnterState = cast(SupportsEnterState, fn)
|
|
29
|
+
enter_fn._on_enter_state = state_name
|
|
30
|
+
return fn
|
|
31
|
+
|
|
32
|
+
return decorator
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def on_exit_state(
|
|
36
|
+
state_node: Union[str, State],
|
|
37
|
+
) -> Callable[[CallableType], CallableType]:
|
|
38
|
+
"""
|
|
39
|
+
Decorator to bind a function to the on-exit hook for a state.
|
|
40
|
+
Accepts a str or a State descriptor.
|
|
41
|
+
"""
|
|
42
|
+
if hasattr(state_node, "name"):
|
|
43
|
+
state_name = state_node.name
|
|
44
|
+
elif isinstance(state_node, str):
|
|
45
|
+
state_name = state_node
|
|
46
|
+
else:
|
|
47
|
+
raise TypeError(f"Expected a State or str, got {type(state_node)}")
|
|
48
|
+
|
|
49
|
+
def decorator(fn: CallableType) -> CallableType:
|
|
50
|
+
exit_fn: SupportsExitState = cast(SupportsExitState, fn)
|
|
51
|
+
exit_fn._on_exit_state = state_name
|
|
52
|
+
return fn
|
|
53
|
+
|
|
54
|
+
return decorator
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def auto_timeout(
|
|
58
|
+
seconds: float, trigger: Union[str, Callable[[], str]] = "to_fault"
|
|
59
|
+
) -> Callable[[CallableType], CallableType]:
|
|
60
|
+
"""
|
|
61
|
+
Decorator that applies an auto-timeout configuration to a state entry handler.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def decorator(fn: CallableType) -> CallableType:
|
|
65
|
+
timeout_fn: SupportsTimeoutConfig = cast(SupportsTimeoutConfig, fn)
|
|
66
|
+
timeout_fn._timeout_config = (seconds, trigger)
|
|
67
|
+
return fn
|
|
68
|
+
|
|
69
|
+
return decorator
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def guard(
|
|
73
|
+
*triggers: Union[str, Trigger],
|
|
74
|
+
) -> Callable[[CallableType], CallableType]:
|
|
75
|
+
"""
|
|
76
|
+
Decorator to add a guard condition to one or more transition triggers.
|
|
77
|
+
The decorated function should return a boolean indicating whether the transition is allowed.
|
|
78
|
+
Accepts multiple str or Trigger descriptors.
|
|
79
|
+
|
|
80
|
+
Examples:
|
|
81
|
+
@guard(Triggers.reset) # Single trigger
|
|
82
|
+
@guard(Triggers.reset, Triggers.start) # Multiple triggers
|
|
83
|
+
@guard("reset", "start") # Multiple string triggers
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def decorator(fn: CallableType) -> CallableType:
|
|
87
|
+
guard_fn: SupportsGuardConditions = cast(SupportsGuardConditions, fn)
|
|
88
|
+
|
|
89
|
+
if not hasattr(guard_fn, "_guard_conditions"):
|
|
90
|
+
guard_fn._guard_conditions = {}
|
|
91
|
+
|
|
92
|
+
for trigger in triggers:
|
|
93
|
+
trigger_name = (
|
|
94
|
+
getattr(trigger, "name", trigger)
|
|
95
|
+
if hasattr(trigger, "name")
|
|
96
|
+
else trigger
|
|
97
|
+
)
|
|
98
|
+
if not isinstance(trigger_name, str):
|
|
99
|
+
raise TypeError(f"Expected a Trigger or str, got {type(trigger)}")
|
|
100
|
+
|
|
101
|
+
guard_fn._guard_conditions[trigger_name] = fn
|
|
102
|
+
|
|
103
|
+
return fn
|
|
104
|
+
|
|
105
|
+
return decorator
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def on_state_change(fn: CallableType) -> CallableType:
|
|
109
|
+
"""
|
|
110
|
+
Decorator to register a global state change callback.
|
|
111
|
+
The decorated function will be called whenever any state transition occurs.
|
|
112
|
+
The callback receives (old_state, new_state, trigger_name) as arguments.
|
|
113
|
+
"""
|
|
114
|
+
callback_fn: SupportsStateChangeCallback = cast(SupportsStateChangeCallback, fn)
|
|
115
|
+
callback_fn._state_change_callback = True
|
|
116
|
+
return fn
|
state_machine/defs.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import Any, Dict, List, Union
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class State:
|
|
6
|
+
"""
|
|
7
|
+
Descriptor for a single leaf state in a hierarchical state machine.
|
|
8
|
+
|
|
9
|
+
On class definition it captures its fully-qualified name, as well as
|
|
10
|
+
the owning group and member names separately.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
__slots__ = ("name", "group_name", "member_name")
|
|
14
|
+
|
|
15
|
+
def __init__(self) -> None:
|
|
16
|
+
self.name: str = ""
|
|
17
|
+
self.group_name: str = ""
|
|
18
|
+
self.member_name: str = ""
|
|
19
|
+
|
|
20
|
+
def __set_name__(self, owner: type, attr_name: str) -> None:
|
|
21
|
+
self.group_name = owner.__name__
|
|
22
|
+
self.member_name = attr_name
|
|
23
|
+
self.name = f"{self.group_name}_{self.member_name}"
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
return self.name
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return f"{self.__class__.__name__}({self.name!r})"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class StateGroup:
|
|
33
|
+
"""
|
|
34
|
+
Base class for grouping related State descriptors.
|
|
35
|
+
|
|
36
|
+
Subclass this, declare State fields, and `to_state_list()`
|
|
37
|
+
will emit exactly the structure transitions needs.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def to_state_list(self) -> List[Dict[str, Any]]:
|
|
41
|
+
"""
|
|
42
|
+
Build a singleβelement list of a dict:
|
|
43
|
+
|
|
44
|
+
{
|
|
45
|
+
"name": "<GroupName>",
|
|
46
|
+
"children": [{"name":"member"}...],
|
|
47
|
+
"initial": "<member>"
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
transitions will register:
|
|
51
|
+
<GroupName>_<member>
|
|
52
|
+
as the leaf states.
|
|
53
|
+
"""
|
|
54
|
+
children: List[Dict[str, str]] = []
|
|
55
|
+
for _, descriptor in vars(self.__class__).items():
|
|
56
|
+
if isinstance(descriptor, State):
|
|
57
|
+
children.append({"name": descriptor.member_name})
|
|
58
|
+
|
|
59
|
+
if not children:
|
|
60
|
+
raise ValueError(f"{self.__class__.__name__} has no State members")
|
|
61
|
+
|
|
62
|
+
initial = children[0]["name"]
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
"name": self.__class__.__name__,
|
|
66
|
+
"children": children,
|
|
67
|
+
"initial": initial,
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Trigger:
|
|
73
|
+
"""
|
|
74
|
+
Represents a state machine trigger/event.
|
|
75
|
+
|
|
76
|
+
You give it exactly one name; `.transition(...)` then builds
|
|
77
|
+
the dict transitions wants.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
__slots__ = ("name",)
|
|
81
|
+
|
|
82
|
+
def __init__(self, name: str) -> None:
|
|
83
|
+
self.name = name
|
|
84
|
+
|
|
85
|
+
def __repr__(self) -> str:
|
|
86
|
+
return f"{self.__class__.__name__}({self.name!r})"
|
|
87
|
+
|
|
88
|
+
def __call__(self) -> str:
|
|
89
|
+
return self.name
|
|
90
|
+
|
|
91
|
+
def transition(
|
|
92
|
+
self, source: Union[str, State], dest: Union[str, State]
|
|
93
|
+
) -> Dict[str, str]:
|
|
94
|
+
"""
|
|
95
|
+
Build {"trigger": self.name, "source": <src>, "dest": <dst>}.
|
|
96
|
+
`source` / `dest` may be raw strings or StateKey instances.
|
|
97
|
+
"""
|
|
98
|
+
src = source if isinstance(source, str) else str(source)
|
|
99
|
+
dst = dest if isinstance(dest, str) else str(dest)
|
|
100
|
+
return {"trigger": self.name, "source": src, "dest": dst}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from typing import Protocol, Callable, Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class SupportsTimeout(Protocol):
|
|
5
|
+
def set_timeout(
|
|
6
|
+
self, state_name: str, seconds: float, trigger_fn: Callable[[], str]
|
|
7
|
+
) -> None: ...
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SupportsStateCallbacks(Protocol):
|
|
11
|
+
def get_state(self, state_name: str) -> Any: ...
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SupportsGuardConditions(Protocol):
|
|
15
|
+
def add_transition_condition(
|
|
16
|
+
self, trigger_name: str, condition_fn: Callable[[], bool]
|
|
17
|
+
) -> None: ...
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SupportsStateChangeCallbacks(Protocol):
|
|
21
|
+
def add_state_change_callback(
|
|
22
|
+
self, callback: Callable[[str, str, str], None]
|
|
23
|
+
) -> None: ...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class StateMachineProtocol(
|
|
27
|
+
SupportsTimeout,
|
|
28
|
+
SupportsStateCallbacks,
|
|
29
|
+
SupportsGuardConditions,
|
|
30
|
+
SupportsStateChangeCallbacks,
|
|
31
|
+
Protocol,
|
|
32
|
+
):
|
|
33
|
+
"""Combined protocol for state machine interface."""
|
state_machine/utils.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import Any, Callable, Optional, Union
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
from state_machine.defs import StateGroup
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def wrap_with_timeout(
|
|
8
|
+
handler: Callable[[Any], Any],
|
|
9
|
+
state_name: str,
|
|
10
|
+
timeout: tuple[float, Union[str, Callable[[], str]]],
|
|
11
|
+
set_timeout_fn: Callable[[str, float, Callable[[], str]], None],
|
|
12
|
+
) -> Callable[[Any], Any]:
|
|
13
|
+
"""
|
|
14
|
+
Wraps a state entry handler with timeout behavior.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
handler: The original state entry function to wrap.
|
|
18
|
+
state_name: The name of the state for which the timeout applies.
|
|
19
|
+
timeout: A tuple containing (seconds, trigger), where:
|
|
20
|
+
- seconds: Timeout duration in seconds.
|
|
21
|
+
- trigger: A string (trigger name) or a function returning a trigger name.
|
|
22
|
+
set_timeout_fn: A function used to register the timeout with the FSM. Signature:
|
|
23
|
+
(state_name: str, seconds: float, trigger_fn: () -> str) -> None
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
A new function that sets the timeout and then invokes the original handler.
|
|
27
|
+
"""
|
|
28
|
+
seconds, trig = timeout
|
|
29
|
+
|
|
30
|
+
if isinstance(trig, str):
|
|
31
|
+
|
|
32
|
+
def trigger_fn() -> str:
|
|
33
|
+
return trig
|
|
34
|
+
elif callable(trig):
|
|
35
|
+
trigger_fn = trig
|
|
36
|
+
else:
|
|
37
|
+
raise TypeError(f"Unsupported trigger type: {type(trig).__name__}")
|
|
38
|
+
|
|
39
|
+
def wrapped(event: Any) -> Any:
|
|
40
|
+
set_timeout_fn(state_name, seconds, trigger_fn)
|
|
41
|
+
return handler(event)
|
|
42
|
+
|
|
43
|
+
return wrapped
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def is_state_container(state_source: object) -> bool:
|
|
47
|
+
"""
|
|
48
|
+
Return True if `obj` is an instance or class that contains StateGroup(s).
|
|
49
|
+
"""
|
|
50
|
+
try:
|
|
51
|
+
return any(
|
|
52
|
+
isinstance(value, StateGroup) for value in vars(state_source).values()
|
|
53
|
+
) or any(
|
|
54
|
+
isinstance(value, StateGroup)
|
|
55
|
+
for value in vars(state_source.__class__).values()
|
|
56
|
+
)
|
|
57
|
+
except TypeError:
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# Shared schema definitions for REST and RPC endpoints
|
|
62
|
+
# (camelCase aliases applied automatically by registry)
|
|
63
|
+
class StateResponse(BaseModel):
|
|
64
|
+
state: str
|
|
65
|
+
last_state: Optional[str] = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class HistoryEntry(BaseModel):
|
|
69
|
+
timestamp: datetime
|
|
70
|
+
state: str
|
|
71
|
+
duration_ms: Optional[int] = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class HistoryResponse(BaseModel):
|
|
75
|
+
history: list[HistoryEntry]
|
|
76
|
+
buffer_size: int
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class TriggerResponse(BaseModel):
|
|
80
|
+
result: str
|
|
81
|
+
previous_state: str
|
|
82
|
+
new_state: str
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Any, Callable, Coroutine, Optional, Sequence
|
|
6
|
+
|
|
7
|
+
from communication.entries import RpcBundle, ActionEntry
|
|
8
|
+
from communication.errors import ConnectError
|
|
9
|
+
from state_machine.core import StateMachine
|
|
10
|
+
from state_machine.utils import (
|
|
11
|
+
StateResponse,
|
|
12
|
+
HistoryResponse,
|
|
13
|
+
HistoryEntry,
|
|
14
|
+
TriggerResponse,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
__all__ = ["build_state_machine_rpc_bundle"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_state_machine_rpc_bundle(
|
|
22
|
+
state_machine: StateMachine,
|
|
23
|
+
*,
|
|
24
|
+
include_state_actions: bool = True,
|
|
25
|
+
include_history_action: bool = True,
|
|
26
|
+
triggers: Optional[Sequence[str]] = None,
|
|
27
|
+
) -> RpcBundle:
|
|
28
|
+
"""
|
|
29
|
+
Build and return an RpcBundle exposing a StateMachine instance.
|
|
30
|
+
|
|
31
|
+
Provides unary RPCs:
|
|
32
|
+
|
|
33
|
+
- GetState
|
|
34
|
+
- GetHistory
|
|
35
|
+
- Trigger_<TriggerName> (one per trigger)
|
|
36
|
+
|
|
37
|
+
For integration via app.extend_bundle(bundle).
|
|
38
|
+
"""
|
|
39
|
+
bundle = RpcBundle()
|
|
40
|
+
|
|
41
|
+
# ======================================================
|
|
42
|
+
# GetState
|
|
43
|
+
# ======================================================
|
|
44
|
+
if include_state_actions:
|
|
45
|
+
|
|
46
|
+
async def get_state() -> StateResponse:
|
|
47
|
+
last = getattr(state_machine, "get_last_state", lambda: None)()
|
|
48
|
+
return StateResponse(state=state_machine.state, last_state=last)
|
|
49
|
+
|
|
50
|
+
bundle.actions.append(
|
|
51
|
+
ActionEntry(
|
|
52
|
+
name="GetState",
|
|
53
|
+
func=get_state,
|
|
54
|
+
input_type=None,
|
|
55
|
+
output_type=StateResponse,
|
|
56
|
+
)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# ======================================================
|
|
60
|
+
# GetHistory
|
|
61
|
+
# ======================================================
|
|
62
|
+
if include_history_action:
|
|
63
|
+
|
|
64
|
+
async def get_history() -> HistoryResponse:
|
|
65
|
+
raw = getattr(state_machine, "history", [])
|
|
66
|
+
out = []
|
|
67
|
+
|
|
68
|
+
for item in raw:
|
|
69
|
+
if isinstance(item, dict):
|
|
70
|
+
state_str = str(item.get("state", ""))
|
|
71
|
+
duration_ms: Optional[int] = item.get("duration_ms")
|
|
72
|
+
if duration_ms is not None and not isinstance(duration_ms, int):
|
|
73
|
+
duration_ms = None
|
|
74
|
+
timestamp: datetime
|
|
75
|
+
if "timestamp" in item and isinstance(item["timestamp"], datetime):
|
|
76
|
+
timestamp = item["timestamp"]
|
|
77
|
+
else:
|
|
78
|
+
timestamp = datetime.now()
|
|
79
|
+
out.append(
|
|
80
|
+
HistoryEntry(
|
|
81
|
+
state=state_str,
|
|
82
|
+
timestamp=timestamp,
|
|
83
|
+
duration_ms=duration_ms,
|
|
84
|
+
)
|
|
85
|
+
)
|
|
86
|
+
else:
|
|
87
|
+
out.append(HistoryEntry(state=str(item), timestamp=datetime.now()))
|
|
88
|
+
|
|
89
|
+
return HistoryResponse(history=out, buffer_size=len(raw))
|
|
90
|
+
|
|
91
|
+
bundle.actions.append(
|
|
92
|
+
ActionEntry(
|
|
93
|
+
name="GetHistory",
|
|
94
|
+
func=get_history,
|
|
95
|
+
input_type=None,
|
|
96
|
+
output_type=HistoryResponse,
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
# ======================================================
|
|
101
|
+
# Triggers
|
|
102
|
+
# ======================================================
|
|
103
|
+
# Source of truth: transitions registered on state machine
|
|
104
|
+
all_triggers = sorted(state_machine.events.keys())
|
|
105
|
+
selected = all_triggers if triggers is None else list(triggers)
|
|
106
|
+
|
|
107
|
+
# ---------- factory function (fixes closure bug) ----------
|
|
108
|
+
def make_trigger_handler(
|
|
109
|
+
trigger_name: str,
|
|
110
|
+
) -> Callable[[], Coroutine[Any, Any, TriggerResponse]]:
|
|
111
|
+
async def trigger_call() -> TriggerResponse:
|
|
112
|
+
current = state_machine.state
|
|
113
|
+
allowed = state_machine.get_triggers(current)
|
|
114
|
+
|
|
115
|
+
# Precondition error if invalid in current state
|
|
116
|
+
if trigger_name not in allowed:
|
|
117
|
+
raise ConnectError(
|
|
118
|
+
code="failed_precondition",
|
|
119
|
+
message=(
|
|
120
|
+
f"Trigger '{trigger_name}' cannot run from '{current}'. "
|
|
121
|
+
f"Allowed: {sorted(allowed)}"
|
|
122
|
+
),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# Fetch bound trigger method
|
|
126
|
+
try:
|
|
127
|
+
method = getattr(state_machine, trigger_name)
|
|
128
|
+
except AttributeError as e:
|
|
129
|
+
raise ConnectError(
|
|
130
|
+
code="internal",
|
|
131
|
+
message=f"StateMachine missing trigger '{trigger_name}'",
|
|
132
|
+
) from e
|
|
133
|
+
|
|
134
|
+
# Execute trigger (sync or async)
|
|
135
|
+
try:
|
|
136
|
+
result = method()
|
|
137
|
+
if inspect.isawaitable(result):
|
|
138
|
+
await result
|
|
139
|
+
except Exception as e:
|
|
140
|
+
raise ConnectError(
|
|
141
|
+
code="internal",
|
|
142
|
+
message=f"Trigger '{trigger_name}' failed: {e}",
|
|
143
|
+
) from e
|
|
144
|
+
|
|
145
|
+
return TriggerResponse(
|
|
146
|
+
result=trigger_name,
|
|
147
|
+
previous_state=current,
|
|
148
|
+
new_state=state_machine.state,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
return trigger_call
|
|
152
|
+
|
|
153
|
+
# ---------- register each trigger ----------
|
|
154
|
+
for trig in selected:
|
|
155
|
+
rpc_name = f"Trigger_{trig[0].upper()}{trig[1:]}" # PascalCase RPC names
|
|
156
|
+
handler = make_trigger_handler(trig)
|
|
157
|
+
|
|
158
|
+
bundle.actions.append(
|
|
159
|
+
ActionEntry(
|
|
160
|
+
name=rpc_name,
|
|
161
|
+
func=handler,
|
|
162
|
+
input_type=None,
|
|
163
|
+
output_type=TriggerResponse,
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
return bundle
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vention-state-machine
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Declarative state machine framework for machine apps
|
|
5
|
+
License: Proprietary
|
|
6
|
+
Author: VentionCo
|
|
7
|
+
Requires-Python: >=3.10,<3.11
|
|
8
|
+
Classifier: License :: Other/Proprietary License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Requires-Dist: asyncio (>=3.4.3,<4.0.0)
|
|
12
|
+
Requires-Dist: coverage (>=7.10.1,<8.0.0)
|
|
13
|
+
Requires-Dist: graphviz (>=0.21,<0.22)
|
|
14
|
+
Requires-Dist: transitions (>=0.9.3,<0.10.0)
|
|
15
|
+
Requires-Dist: uvicorn (>=0.35.0,<0.36.0)
|
|
16
|
+
Requires-Dist: vention-communication (>=0.2.2,<0.3.0)
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# vention-state-machine
|
|
20
|
+
|
|
21
|
+
A lightweight wrapper around `transitions` for building async-safe, recoverable hierarchical state machines with minimal boilerplate.
|
|
22
|
+
|
|
23
|
+
## Table of Contents
|
|
24
|
+
|
|
25
|
+
- [β¨ Features](#-features)
|
|
26
|
+
- [π§ Concepts & Overview](#-concepts--overview)
|
|
27
|
+
- [βοΈ Installation & Setup](#οΈ-installation--setup)
|
|
28
|
+
- [π Quickstart Tutorial](#-quickstart-tutorial)
|
|
29
|
+
- [π How-to Guides](#-how-to-guides)
|
|
30
|
+
- [π API Reference](#-api-reference)
|
|
31
|
+
- [π Troubleshooting & FAQ](#-troubleshooting--faq)
|
|
32
|
+
|
|
33
|
+
## β¨ Features
|
|
34
|
+
|
|
35
|
+
- Built-in `ready` / `fault` states
|
|
36
|
+
- Global transitions: `to_fault`, `reset`
|
|
37
|
+
- Optional state recovery (`recover__state`)
|
|
38
|
+
- Async task spawning and cancellation
|
|
39
|
+
- Timeouts and auto-fault handling
|
|
40
|
+
- Transition history recording with timestamps + durations
|
|
41
|
+
- Guard conditions for blocking transitions
|
|
42
|
+
- Global state change callbacks for logging/MQTT
|
|
43
|
+
- Optional RPC bundle for exposing state machine via Connect RPCs
|
|
44
|
+
|
|
45
|
+
## π§ Concepts & Overview
|
|
46
|
+
|
|
47
|
+
This library uses a **declarative domain-specific language (DSL)** to define state machines in a readable, strongly typed way.
|
|
48
|
+
|
|
49
|
+
- **State** β A leaf node in the state machine
|
|
50
|
+
- **StateGroup** β Groups related states, creating hierarchical namespaces
|
|
51
|
+
- **Trigger** β Named events that initiate transitions
|
|
52
|
+
|
|
53
|
+
Example:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
class MyStates(StateGroup):
|
|
57
|
+
idle: State = State()
|
|
58
|
+
working: State = State()
|
|
59
|
+
|
|
60
|
+
class Triggers:
|
|
61
|
+
begin = Trigger("begin")
|
|
62
|
+
finish = Trigger("finish")
|
|
63
|
+
|
|
64
|
+
TRANSITIONS = [
|
|
65
|
+
Triggers.finish.transition(MyStates.working, MyStates.idle),
|
|
66
|
+
]
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
### Base States and Triggers
|
|
71
|
+
|
|
72
|
+
All machines include:
|
|
73
|
+
|
|
74
|
+
**States:**
|
|
75
|
+
- `ready` (initial)
|
|
76
|
+
- `fault` (global error)
|
|
77
|
+
|
|
78
|
+
**Triggers:**
|
|
79
|
+
- `start`, `to_fault`, `reset`
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from state_machine.core import BaseStates, BaseTriggers
|
|
83
|
+
|
|
84
|
+
state_machine.trigger(BaseTriggers.RESET.value)
|
|
85
|
+
assert state_machine.state == BaseStates.READY.value
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## βοΈ Installation & Setup
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pip install vention-state-machine
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
**Optional dependencies:**
|
|
95
|
+
- Graphviz (required for diagram generation)
|
|
96
|
+
- vention-communication (for RPC bundle integration)
|
|
97
|
+
|
|
98
|
+
**Install optional tools:**
|
|
99
|
+
|
|
100
|
+
MacOS:
|
|
101
|
+
```bash
|
|
102
|
+
brew install graphviz
|
|
103
|
+
pip install vention-communication
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Linux (Debian/Ubuntu)
|
|
107
|
+
```bash
|
|
108
|
+
sudo apt-get install graphviz
|
|
109
|
+
pip install vention-communication
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
## π Quickstart Tutorial
|
|
114
|
+
|
|
115
|
+
### 1. Define States and Triggers
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from state_machine.defs import StateGroup, State, Trigger
|
|
119
|
+
|
|
120
|
+
class Running(StateGroup):
|
|
121
|
+
picking: State = State()
|
|
122
|
+
placing: State = State()
|
|
123
|
+
homing: State = State()
|
|
124
|
+
|
|
125
|
+
class States:
|
|
126
|
+
running = Running()
|
|
127
|
+
|
|
128
|
+
class Triggers:
|
|
129
|
+
start = Trigger("start")
|
|
130
|
+
finished_picking = Trigger("finished_picking")
|
|
131
|
+
finished_placing = Trigger("finished_placing")
|
|
132
|
+
finished_homing = Trigger("finished_homing")
|
|
133
|
+
to_fault = Trigger("to_fault")
|
|
134
|
+
reset = Trigger("reset")
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 2. Define Transitions
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
TRANSITIONS = [
|
|
141
|
+
Triggers.start.transition("ready", States.running.picking),
|
|
142
|
+
Triggers.finished_picking.transition(States.running.picking, States.running.placing),
|
|
143
|
+
Triggers.finished_placing.transition(States.running.placing, States.running.homing),
|
|
144
|
+
Triggers.finished_homing.transition(States.running.homing, States.running.picking),
|
|
145
|
+
]
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### 3. Implement Your State Machine
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from state_machine.core import StateMachine
|
|
152
|
+
from state_machine.decorators import on_enter_state, auto_timeout, guard, on_state_change
|
|
153
|
+
|
|
154
|
+
class CustomMachine(StateMachine):
|
|
155
|
+
def __init__(self):
|
|
156
|
+
super().__init__(states=States, transitions=TRANSITIONS)
|
|
157
|
+
|
|
158
|
+
@on_enter_state(States.running.picking)
|
|
159
|
+
@auto_timeout(5.0, Triggers.to_fault)
|
|
160
|
+
def enter_picking(self, _):
|
|
161
|
+
print("πΉ Entering picking")
|
|
162
|
+
|
|
163
|
+
@on_enter_state(States.running.placing)
|
|
164
|
+
def enter_placing(self, _):
|
|
165
|
+
print("πΈ Entering placing")
|
|
166
|
+
|
|
167
|
+
@on_enter_state(States.running.homing)
|
|
168
|
+
def enter_homing(self, _):
|
|
169
|
+
print("πΊ Entering homing")
|
|
170
|
+
|
|
171
|
+
@guard(Triggers.reset)
|
|
172
|
+
def check_safety_conditions(self) -> bool:
|
|
173
|
+
return not self.estop_pressed
|
|
174
|
+
|
|
175
|
+
@on_state_change
|
|
176
|
+
def publish_state_to_mqtt(self, old_state: str, new_state: str, trigger: str):
|
|
177
|
+
mqtt_client.publish("machine/state", {
|
|
178
|
+
"old_state": old_state,
|
|
179
|
+
"new_state": new_state,
|
|
180
|
+
"trigger": trigger
|
|
181
|
+
})
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### 4. Start It
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
state_machine = StateMachine()
|
|
188
|
+
state_machine.start()
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## π How-to Guides
|
|
192
|
+
|
|
193
|
+
### Expose Over RPC with VentionApp
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
from communication.app import VentionApp
|
|
197
|
+
from state_machine.vention_communication import build_state_machine_bundle
|
|
198
|
+
from state_machine.core import StateMachine
|
|
199
|
+
|
|
200
|
+
state_machine = StateMachine(...)
|
|
201
|
+
state_machine.start()
|
|
202
|
+
|
|
203
|
+
app = VentionApp(name="MyApp")
|
|
204
|
+
bundle = build_state_machine_bundle(state_machine)
|
|
205
|
+
app.register_rpc_plugin(bundle)
|
|
206
|
+
app.finalize()
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
**RPC Actions:**
|
|
210
|
+
- `GetState` β Returns current state and last known state
|
|
211
|
+
- `GetHistory` β Returns transition history with timestamps
|
|
212
|
+
- `Trigger_<TriggerName>` β Triggers a state transition (e.g., `Trigger_Start`, `Trigger_Activate`)
|
|
213
|
+
|
|
214
|
+
**Options:**
|
|
215
|
+
```python
|
|
216
|
+
# Customize which actions are included
|
|
217
|
+
bundle = build_state_machine_bundle(
|
|
218
|
+
state_machine,
|
|
219
|
+
include_state_actions=True, # Include GetState
|
|
220
|
+
include_history_action=True, # Include GetHistory
|
|
221
|
+
triggers=["start", "activate"], # Only include specific triggers
|
|
222
|
+
)
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Timeout Example
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
@auto_timeout(5.0, Triggers.to_fault)
|
|
229
|
+
def enter_state(self, _):
|
|
230
|
+
...
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Recovery Example
|
|
234
|
+
|
|
235
|
+
```python
|
|
236
|
+
state_machine = StateMachine(enable_last_state_recovery=True)
|
|
237
|
+
state_machine.start() # will attempt recover__{last_state}
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### Triggering state transitions via I/O
|
|
241
|
+
|
|
242
|
+
Here's an example of hooking up state transitions to I/O events via MQTT
|
|
243
|
+
|
|
244
|
+
```python
|
|
245
|
+
import asyncio
|
|
246
|
+
import paho.mqtt.client as mqtt
|
|
247
|
+
from state_machine.core import StateMachine
|
|
248
|
+
from state_machine.defs import State, StateGroup, Trigger
|
|
249
|
+
from state_machine.decorators import on_enter_state
|
|
250
|
+
|
|
251
|
+
class MachineStates(StateGroup):
|
|
252
|
+
idle: State = State()
|
|
253
|
+
running: State = State()
|
|
254
|
+
|
|
255
|
+
class States:
|
|
256
|
+
machine = MachineStates()
|
|
257
|
+
|
|
258
|
+
class Triggers:
|
|
259
|
+
start_button = Trigger("start_button")
|
|
260
|
+
box_missing = Trigger("box_missing")
|
|
261
|
+
|
|
262
|
+
TRANSITIONS = [
|
|
263
|
+
Triggers.start_button.transition(States.machine.idle, States.machine.running),
|
|
264
|
+
Triggers.box_missing.transition(States.machine.running, States.machine.idle),
|
|
265
|
+
]
|
|
266
|
+
|
|
267
|
+
class MachineController(StateMachine):
|
|
268
|
+
def __init__(self):
|
|
269
|
+
super().__init__(states=States, transitions=TRANSITIONS)
|
|
270
|
+
self.mqtt_client = mqtt.Client()
|
|
271
|
+
self.setup_mqtt()
|
|
272
|
+
|
|
273
|
+
def setup_mqtt(self):
|
|
274
|
+
"""Configure MQTT client to listen for I/O signals."""
|
|
275
|
+
self.mqtt_client.on_connect = self.on_mqtt_connect
|
|
276
|
+
self.mqtt_client.on_message = self.on_mqtt_message
|
|
277
|
+
self.mqtt_client.connect("localhost", 1883, 60)
|
|
278
|
+
|
|
279
|
+
# Start MQTT loop in background
|
|
280
|
+
self.spawn(self.mqtt_loop())
|
|
281
|
+
|
|
282
|
+
async def mqtt_loop(self):
|
|
283
|
+
"""Background task to handle MQTT messages."""
|
|
284
|
+
self.mqtt_client.loop_start()
|
|
285
|
+
while True:
|
|
286
|
+
await asyncio.sleep(0.1)
|
|
287
|
+
|
|
288
|
+
def on_mqtt_connect(self, client, userdata, flags, rc):
|
|
289
|
+
"""Subscribe to I/O topics when connected."""
|
|
290
|
+
client.subscribe("machine/io/start_button")
|
|
291
|
+
client.subscribe("machine/sensors/box_sensor")
|
|
292
|
+
|
|
293
|
+
def on_mqtt_message(self, client, userdata, msg):
|
|
294
|
+
"""Handle incoming MQTT messages and trigger state transitions."""
|
|
295
|
+
topic = msg.topic
|
|
296
|
+
payload = msg.payload.decode()
|
|
297
|
+
|
|
298
|
+
# Map MQTT topics to state machine triggers
|
|
299
|
+
if topic == "machine/io/start_button" and payload == "pressed":
|
|
300
|
+
self.trigger(Triggers.start_button.value)
|
|
301
|
+
elif topic == "machine/sensors/box_sensor" and payload == "0":
|
|
302
|
+
self.trigger(Triggers.box_missing.value)
|
|
303
|
+
|
|
304
|
+
@on_enter_state(States.machine.running)
|
|
305
|
+
def enter_running(self, _):
|
|
306
|
+
print("π§ Machine started - processing parts")
|
|
307
|
+
self.mqtt_client.publish("machine/status", "running")
|
|
308
|
+
|
|
309
|
+
@on_enter_state(States.machine.idle)
|
|
310
|
+
def enter_idle(self, _):
|
|
311
|
+
print("βΈοΈ Machine idle - ready for start")
|
|
312
|
+
self.mqtt_client.publish("machine/status", "idle")
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
## π API Reference
|
|
316
|
+
|
|
317
|
+
### StateMachine
|
|
318
|
+
|
|
319
|
+
```python
|
|
320
|
+
class StateMachine(HierarchicalGraphMachine):
|
|
321
|
+
def __init__(
|
|
322
|
+
self,
|
|
323
|
+
states: Union[object, list[dict[str, Any]], None],
|
|
324
|
+
*,
|
|
325
|
+
transitions: Optional[list[dict[str, str]]] = None,
|
|
326
|
+
history_size: Optional[int] = None,
|
|
327
|
+
enable_last_state_recovery: bool = True,
|
|
328
|
+
**kw: Any,
|
|
329
|
+
)
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
**Parameters:**
|
|
333
|
+
- `states`: Either a container of StateGroups or a list of state dicts.
|
|
334
|
+
- `transitions`: List of transition dictionaries, or `[]`.
|
|
335
|
+
- `history_size`: Max number of entries in transition history (default 1000).
|
|
336
|
+
- `enable_last_state_recovery`: If True, machine can resume from last recorded state.
|
|
337
|
+
|
|
338
|
+
### Methods
|
|
339
|
+
|
|
340
|
+
**`spawn(coro: Coroutine) -> asyncio.Task`**
|
|
341
|
+
Start a background coroutine and track it. Auto-cancelled on fault/reset.
|
|
342
|
+
|
|
343
|
+
**`cancel_tasks() -> None`**
|
|
344
|
+
Cancel all tracked tasks and timeouts.
|
|
345
|
+
|
|
346
|
+
**`set_timeout(state_name: str, seconds: float, trigger_fn: Callable[[], str]) -> None`**
|
|
347
|
+
Schedule a trigger if state_name stays active too long.
|
|
348
|
+
|
|
349
|
+
**`record_last_state() -> None`**
|
|
350
|
+
Save current state for recovery.
|
|
351
|
+
|
|
352
|
+
**`get_last_state() -> Optional[str]`**
|
|
353
|
+
Return most recently recorded state.
|
|
354
|
+
|
|
355
|
+
**`start() -> None`**
|
|
356
|
+
Enter machine (recover__... if applicable, else start).
|
|
357
|
+
|
|
358
|
+
### Properties
|
|
359
|
+
|
|
360
|
+
**`history -> list[dict[str, Any]]`**
|
|
361
|
+
Full transition history with timestamps/durations.
|
|
362
|
+
|
|
363
|
+
**`get_last_history_entries(n: int) -> list[dict[str, Any]]`**
|
|
364
|
+
Return last n transitions.
|
|
365
|
+
|
|
366
|
+
### Decorators
|
|
367
|
+
|
|
368
|
+
**`@on_enter_state(state: State)`**
|
|
369
|
+
Bind function to run on entry.
|
|
370
|
+
|
|
371
|
+
**`@on_exit_state(state: State)`**
|
|
372
|
+
Bind function to run on exit.
|
|
373
|
+
|
|
374
|
+
**`@auto_timeout(seconds: float, trigger: Trigger)`**
|
|
375
|
+
Auto-trigger if timeout expires.
|
|
376
|
+
|
|
377
|
+
**`@guard(*triggers: Trigger)`**
|
|
378
|
+
Guard transition; blocks if function returns False.
|
|
379
|
+
|
|
380
|
+
**`@on_state_change`**
|
|
381
|
+
Global callback `(old_state, new_state, trigger)` fired after each transition.
|
|
382
|
+
|
|
383
|
+
### RPC Bundle
|
|
384
|
+
|
|
385
|
+
```python
|
|
386
|
+
def build_state_machine_bundle(
|
|
387
|
+
sm: StateMachine,
|
|
388
|
+
*,
|
|
389
|
+
include_state_actions: bool = True,
|
|
390
|
+
include_history_action: bool = True,
|
|
391
|
+
triggers: Optional[Sequence[str]] = None,
|
|
392
|
+
) -> RpcBundle
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
Builds an RPC bundle exposing the state machine via Connect-style RPCs:
|
|
396
|
+
- `GetState` - Returns current and last known state
|
|
397
|
+
- `GetHistory` - Returns transition history
|
|
398
|
+
- `Trigger_<TriggerName>` - One RPC per trigger (PascalCase naming)
|
|
399
|
+
|
|
400
|
+
The bundle can be registered with a `VentionApp` using `app.register_rpc_plugin(bundle)`.
|
|
401
|
+
|
|
402
|
+
## π Troubleshooting & FAQ
|
|
403
|
+
|
|
404
|
+
- **Transitions blocked unexpectedly** β Check guard conditions.
|
|
405
|
+
- **Callbacks not firing** β Only successful transitions trigger them.
|
|
406
|
+
- **State not restored after restart** β Ensure `enable_last_state_recovery=True`.
|
|
407
|
+
- **RPC actions not available** β Ensure `app.finalize()` is called after registering bundles.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
state_machine/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
state_machine/core.py,sha256=lAiGGPtWCiYQPCh1iz3P26YFrz8VvveIGlL5k2AFvKs,11201
|
|
3
|
+
state_machine/decorator_manager.py,sha256=uHhbtR1vS7idcn4kJsaNtJ1Z_7kiHf9YVa_cxkb-WNk,4420
|
|
4
|
+
state_machine/decorator_protocols.py,sha256=E6_xflTPxxTqDBa4Dj4p3OdPvR_EW0jA3PAjHTDlG8c,485
|
|
5
|
+
state_machine/decorators.py,sha256=V-KBJ6fSvINi7JHN_VmrQLTnOxGPy5iRV5QzXLKwWDw,3668
|
|
6
|
+
state_machine/defs.py,sha256=eYtkTqRMm89ZHFKs3p7H3HyGNZbrOnoCzAJbSeMxSDg,2836
|
|
7
|
+
state_machine/machine_protocols.py,sha256=Yxs4aw2-NJ1RluygbthsquVKn35-xMYae7PB7xlqQmE,826
|
|
8
|
+
state_machine/utils.py,sha256=3eWL63_RAk_Jijh0ZIArBsUF3A7f0vQmwTjDRwRvpIs,2395
|
|
9
|
+
state_machine/vention_communication.py,sha256=BZjHC1SsXFqLiSpX0ChCEGfhkEeitpXmLClZCQIgOrA,5530
|
|
10
|
+
vention_state_machine-0.4.0.dist-info/METADATA,sha256=UlROQZDnqaO5j0AbfJJ2KofpSrrr_woWR8xPWbJY35c,11671
|
|
11
|
+
vention_state_machine-0.4.0.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
|
|
12
|
+
vention_state_machine-0.4.0.dist-info/RECORD,,
|