API Reference¶
Complete API reference for the VYRA State Machine system.
UnifiedStateMachine¶
The main class that manages all three state layers.
- class vyra_base.state.unified.UnifiedStateMachine(config=None)[Quellcode]
Bases:
objectUnified interface for 3-layer state machine.
Combines Lifecycle, Operational, and Health layers into a single easy-to-use API. Recommended for most use cases.
Example
>>> usm = UnifiedStateMachine() >>> usm.start() # Lifecycle >>> usm.complete_initialization() >>> usm.set_ready() # Operational >>> usm.start_task({'task_id': '123'}) >>> usm.report_warning({'cpu': '85%'}) # Health >>> usm.get_all_states() {'lifecycle': 'Active', 'operational': 'Running', 'health': 'Warning'}
- Parameter:
config (StateMachineConfig | None)
- __init__(config=None)[Quellcode]
Initialize unified state machine.
- Parameter:
config (
Optional[StateMachineConfig]) – Configuration for state machine behavior
- get_all_states()[Quellcode]
Get current state of all layers.
- get_lifecycle_state()[Quellcode]
Get lifecycle state.
- Rückgabetyp:
- get_operational_state()[Quellcode]
Get operational state.
- Rückgabetyp:
- get_health_state()[Quellcode]
Get health state.
- Rückgabetyp:
- is_operational()[Quellcode]
Check if module can execute tasks.
- Rückgabetyp:
- is_healthy()[Quellcode]
Check if module health is OK.
- Rückgabetyp:
- is_initializing()[Quellcode]
Check if module is initializing.
- Rückgabetyp:
- is_active()[Quellcode]
Check if module lifecycle is Active.
- Rückgabetyp:
- is_suspended()[Quellcode]
Check if module is suspended.
- Rückgabetyp:
- is_recovering()[Quellcode]
Check if module is in recovery.
- Rückgabetyp:
- is_shutting_down()[Quellcode]
Check if module is shutting down.
- Rückgabetyp:
- is_offline()[Quellcode]
Check if module is offline.
- Rückgabetyp:
- start(metadata=None)[Quellcode]
Start module initialization.
- Rückgabetyp:
- Parameter:
- complete_initialization(result=None)[Quellcode]
Complete initialization successfully.
- Rückgabetyp:
- Parameter:
- fail_initialization(error=None)[Quellcode]
Mark initialization as failed.
- Rückgabetyp:
- Parameter:
error (str | None)
- shutdown(reason=None)[Quellcode]
Begin controlled shutdown.
- Rückgabetyp:
- Parameter:
reason (str | None)
- complete_shutdown()[Quellcode]
Complete shutdown process.
- Rückgabetyp:
- suspend(reason=None)[Quellcode]
Suspend the module temporarily (e.g. for maintenance or updates).
Transitions: Active → Suspended
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- resume_from_suspend(info=None)[Quellcode]
Resume module from Suspended state.
Transitions: Suspended → Active
- enter_recovery(fault_info=None)[Quellcode]
Enter recovery mode due to fault.
Transitions: Active → Recovering
- complete_recovery(recovery_info=None)[Quellcode]
Complete recovery successfully.
Transitions: Recovering → Active
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- fail_recovery(error=None)[Quellcode]
Mark recovery as failed.
Transitions: Recovering → ShuttingDown
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- set_ready(metadata=None)[Quellcode]
Signal readiness for tasks.
- Rückgabetyp:
- Parameter:
- start_task(task_info=None)[Quellcode]
Start task execution.
- Rückgabetyp:
- Parameter:
- pause(reason=None)[Quellcode]
Pause current task.
- Rückgabetyp:
- Parameter:
reason (str | None)
- resume()[Quellcode]
Resume paused task.
- Rückgabetyp:
- stop(result=None)[Quellcode]
Mark task as completed.
- Rückgabetyp:
- Parameter:
- reset()[Quellcode]
Reset operational state to Idle.
- Rückgabetyp:
- report_warning(warning_info=None)[Quellcode]
Report non-critical warning.
- Rückgabetyp:
- Parameter:
- report_fault(fault_info=None)[Quellcode]
Report critical fault.
- Rückgabetyp:
- Parameter:
- recover(recovery_info=None)[Quellcode]
Attempt recovery from fault.
- Rückgabetyp:
- Parameter:
- emergency_stop(reason)[Quellcode]
Trigger emergency stop.
- on_lifecycle_change(callback, priority=0)[Quellcode]
Subscribe to lifecycle state changes.
- on_operational_change(callback, priority=0)[Quellcode]
Subscribe to operational state changes.
- on_health_change(callback, priority=0)[Quellcode]
Subscribe to health state changes.
- on_any_change(callback, priority=0)[Quellcode]
Subscribe to any state change across all layers.
- get_diagnostic_info()[Quellcode]
Get comprehensive diagnostic information.
- get_history(limit=None)[Quellcode]
Get state transition history.
- Parameter:
limit (int | None)
- clear_history()[Quellcode]
Clear transition history.
- send_event(event)[Quellcode]
Send an event to the state machine.
This method is required for compatibility with OperationalStateMachine which calls _state_machine.send_event(event).
- Parameter:
event – StateEvent to send to the FSM
- standard_startup()[Quellcode]
Execute standard module startup sequence.
Sequence: 1. Start initialization 2. Complete initialization 3. Set operational ready
- Rückgabetyp:
- Rückgabe:
True if startup successful, False otherwise
- standard_shutdown()[Quellcode]
Execute standard module shutdown sequence.
Sequence: 1. Begin shutdown 2. Complete any pending tasks (module responsibility) 3. Complete shutdown
- Rückgabetyp:
- Rückgabe:
True if shutdown successful, False otherwise
OperationalStateMachine¶
Base class for components that use operational state management.
- class vyra_base.state.operational_state_machine.OperationalStateMachine(state_machine)[Quellcode]
Bases:
objectBase class for modules that need automatic operational state management.
This class integrates with the 3-layer StateMachine and provides a clean interface for defining lifecycle methods that automatically handle state transitions.
Subclasses should implement one or more of the following methods:
initialize(): Setup and initialization logic
pause(): Pause current operation
resume(): Resume paused operation
stop(): Stop current operation
reset(): Reset to initial state
For dynamic operations, use the @operation decorator.
All methods should return True on success, False on failure. Exceptions are caught and treated as failures.
Example
>>> class MyModule(OperationalStateMachine): ... def __init__(self, state_machine): ... super().__init__(state_machine) ... self.data = None ... ... def initialize(self): ... # This runs when initialize() is called ... # Pre-condition: IDLE state ... # On success: IDLE -> READY (operation counter reset) ... # On failure: IDLE -> ERROR ... self.data = [] ... print("Initialized!") ... return True >>> >>> # Usage >>> fsm = StateMachine() >>> module = MyModule(fsm) >>> module.initialize() # Automatic state management >>> # Now in READY state, ready for operations
- Parameter:
state_machine (StateMachine)
- __init__(state_machine)[Quellcode]
Initialize the operational state machine.
- Parameter:
state_machine (
StateMachine) – The underlying 3-layer StateMachine instance
- get_operational_state()[Quellcode]
Get current operational state.
- Rückgabetyp:
- get_all_states()[Quellcode]
Get all current states (lifecycle, operational, health).
- is_idle()[Quellcode]
Check if in IDLE state.
- Rückgabetyp:
- is_ready()[Quellcode]
Check if in READY state.
- Rückgabetyp:
- is_running()[Quellcode]
Check if in RUNNING state.
- Rückgabetyp:
- is_paused()[Quellcode]
Check if in PAUSED state.
- Rückgabetyp:
- is_stopped()[Quellcode]
Check if in STOPPED state.
- Rückgabetyp:
- is_error()[Quellcode]
Check if in ERROR state.
- Rückgabetyp:
- get_operation_counter()[Quellcode]
Get the current operation reference counter value.
- Rückgabetyp:
- Rückgabe:
Number of currently active operations
State Types¶
LifecycleState¶
- class vyra_base.state.state_types.LifecycleState(*values)[Quellcode]
Bases:
EnumLifecycle states define the existence and high-level life of a module.
Similar to ROS2 Lifecycle nodes and IEC 61131-3 PLC states.
- INITIALIZING = 'Initializing'
- ACTIVE = 'Active'
- RECOVERING = 'Recovering'
- SUSPENDED = 'Suspended'
- SHUTTING_DOWN = 'ShuttingDown'
- OFFLINE = 'Offline'
OperationalState¶
- class vyra_base.state.state_types.OperationalState(*values)[Quellcode]
Bases:
EnumOperational states define the runtime activity of a module.
Represents what the module is currently doing during normal operation.
- IDLE = 'Idle'
- READY = 'Ready'
- RUNNING = 'Running'
- PAUSED = 'Paused'
- STOPPED = 'Stopped'
- ERROR = 'Error'
HealthState¶
- class vyra_base.state.state_types.HealthState(*values)[Quellcode]
Bases:
EnumHealth states describe the integrity and error conditions of a module.
Follows safety integrity levels (SIL) from IEC 61508.
- HEALTHY = 'Healthy'
- WARNING = 'Warning'
- CRITICAL = 'Critical'
Event System¶
StateEvent¶
- class vyra_base.state.state_events.StateEvent(event_type, timestamp=<factory>, origin_layer=None, payload=None, event_id=None)[Quellcode]
Bases:
objectImmutable event for state machine transitions.
Contains all information about a state transition event including timestamp, origin, and optional payload for tracing and debugging.
- Parameter:
- event_type: EventType
- timestamp: datetime
- to_dict()[Quellcode]
Convert event to dictionary for serialization.
EventType¶
- class vyra_base.state.state_events.EventType(*values)[Quellcode]
Bases:
EnumEvent types for state transitions.
- START = 'start'
- INIT_SUCCESS = 'init_success'
- INIT_FAILURE = 'init_failure'
- SET_SUSPENDED = 'set_suspended'
- RESUME_SUSPENDED = 'resume_suspended'
- SHUTDOWN = 'shutdown'
- FINISHED = 'finished'
- FAULT_DETECTED = 'fault_detected'
- RECOVERY_SUCCESS = 'recovery_success'
- RECOVERY_FAILED = 'recovery_failed'
- SET_READY = 'set_ready'
- TASK_START = 'task_start'
- TASK_PAUSE = 'task_pause'
- TASK_RESUME = 'task_resume'
- TASK_COMPLETE = 'task_complete'
- TASK_STOP = 'task_stop'
- TASK_RESET = 'task_reset'
- TASK_ERROR = 'task_error'
- WARN = 'warn'
- CLEAR_WARNING = 'clear_warning'
- FAULT = 'fault'
- RECOVER = 'recover'
- RESET = 'reset'
- INTERRUPT = 'interrupt'
- EMERGENCY_STOP = 'emergency_stop'
- PRIORITY_OVERRIDE = 'priority_override'
State Machines¶
The state machine implementation consists of three layer classes that work together within the UnifiedStateMachine. These are internal implementation details.
For usage, refer to the UnifiedStateMachine class above.
Decorators¶
The @remote_service decorator is used to mark methods that should be exposed as ROS2 services.
It automatically handles state transitions and validation.
Usage:
from vyra_base.com import remote_service
class MyComponent(OperationalStateMachine):
@remote_service()
def initialize(self, request=None, response=None):
return True
Exceptions¶
InvalidTransitionError¶
Raised when an invalid state transition is attempted.
from vyra_base.state.state_types import InvalidTransitionError
try:
state_machine.handle_event(EventType.TASK_START)
except InvalidTransitionError as e:
print(f"Invalid transition: {e}")
OperationalStateError¶
Raised when an operational state error occurs.
from vyra_base.state.state_types import OperationalStateError
try:
component.start()
except OperationalStateError as e:
print(f"Operational error: {e}")
Complete Module Reference¶
state.unified¶
Integration module for easy unified state machine access.
Provides a simple API that combines all three layers into a single unified interface for module state management.
- class vyra_base.state.unified.UnifiedStateMachine(config=None)[Quellcode]
Bases:
objectUnified interface for 3-layer state machine.
Combines Lifecycle, Operational, and Health layers into a single easy-to-use API. Recommended for most use cases.
Example
>>> usm = UnifiedStateMachine() >>> usm.start() # Lifecycle >>> usm.complete_initialization() >>> usm.set_ready() # Operational >>> usm.start_task({'task_id': '123'}) >>> usm.report_warning({'cpu': '85%'}) # Health >>> usm.get_all_states() {'lifecycle': 'Active', 'operational': 'Running', 'health': 'Warning'}
- Parameter:
config (StateMachineConfig | None)
- __init__(config=None)[Quellcode]
Initialize unified state machine.
- Parameter:
config (
Optional[StateMachineConfig]) – Configuration for state machine behavior
- get_all_states()[Quellcode]
Get current state of all layers.
- get_lifecycle_state()[Quellcode]
Get lifecycle state.
- Rückgabetyp:
- get_operational_state()[Quellcode]
Get operational state.
- Rückgabetyp:
- get_health_state()[Quellcode]
Get health state.
- Rückgabetyp:
- is_operational()[Quellcode]
Check if module can execute tasks.
- Rückgabetyp:
- is_healthy()[Quellcode]
Check if module health is OK.
- Rückgabetyp:
- is_initializing()[Quellcode]
Check if module is initializing.
- Rückgabetyp:
- is_active()[Quellcode]
Check if module lifecycle is Active.
- Rückgabetyp:
- is_suspended()[Quellcode]
Check if module is suspended.
- Rückgabetyp:
- is_recovering()[Quellcode]
Check if module is in recovery.
- Rückgabetyp:
- is_shutting_down()[Quellcode]
Check if module is shutting down.
- Rückgabetyp:
- is_offline()[Quellcode]
Check if module is offline.
- Rückgabetyp:
- start(metadata=None)[Quellcode]
Start module initialization.
- Rückgabetyp:
- Parameter:
- complete_initialization(result=None)[Quellcode]
Complete initialization successfully.
- Rückgabetyp:
- Parameter:
- fail_initialization(error=None)[Quellcode]
Mark initialization as failed.
- Rückgabetyp:
- Parameter:
error (str | None)
- shutdown(reason=None)[Quellcode]
Begin controlled shutdown.
- Rückgabetyp:
- Parameter:
reason (str | None)
- complete_shutdown()[Quellcode]
Complete shutdown process.
- Rückgabetyp:
- suspend(reason=None)[Quellcode]
Suspend the module temporarily (e.g. for maintenance or updates).
Transitions: Active → Suspended
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- resume_from_suspend(info=None)[Quellcode]
Resume module from Suspended state.
Transitions: Suspended → Active
- enter_recovery(fault_info=None)[Quellcode]
Enter recovery mode due to fault.
Transitions: Active → Recovering
- complete_recovery(recovery_info=None)[Quellcode]
Complete recovery successfully.
Transitions: Recovering → Active
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- fail_recovery(error=None)[Quellcode]
Mark recovery as failed.
Transitions: Recovering → ShuttingDown
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- set_ready(metadata=None)[Quellcode]
Signal readiness for tasks.
- Rückgabetyp:
- Parameter:
- start_task(task_info=None)[Quellcode]
Start task execution.
- Rückgabetyp:
- Parameter:
- pause(reason=None)[Quellcode]
Pause current task.
- Rückgabetyp:
- Parameter:
reason (str | None)
- resume()[Quellcode]
Resume paused task.
- Rückgabetyp:
- stop(result=None)[Quellcode]
Mark task as completed.
- Rückgabetyp:
- Parameter:
- reset()[Quellcode]
Reset operational state to Idle.
- Rückgabetyp:
- report_warning(warning_info=None)[Quellcode]
Report non-critical warning.
- Rückgabetyp:
- Parameter:
- report_fault(fault_info=None)[Quellcode]
Report critical fault.
- Rückgabetyp:
- Parameter:
- recover(recovery_info=None)[Quellcode]
Attempt recovery from fault.
- Rückgabetyp:
- Parameter:
- emergency_stop(reason)[Quellcode]
Trigger emergency stop.
- on_lifecycle_change(callback, priority=0)[Quellcode]
Subscribe to lifecycle state changes.
- on_operational_change(callback, priority=0)[Quellcode]
Subscribe to operational state changes.
- on_health_change(callback, priority=0)[Quellcode]
Subscribe to health state changes.
- on_any_change(callback, priority=0)[Quellcode]
Subscribe to any state change across all layers.
- get_diagnostic_info()[Quellcode]
Get comprehensive diagnostic information.
- get_history(limit=None)[Quellcode]
Get state transition history.
- Parameter:
limit (int | None)
- clear_history()[Quellcode]
Clear transition history.
- send_event(event)[Quellcode]
Send an event to the state machine.
This method is required for compatibility with OperationalStateMachine which calls _state_machine.send_event(event).
- Parameter:
event – StateEvent to send to the FSM
- standard_startup()[Quellcode]
Execute standard module startup sequence.
Sequence: 1. Start initialization 2. Complete initialization 3. Set operational ready
- Rückgabetyp:
- Rückgabe:
True if startup successful, False otherwise
- standard_shutdown()[Quellcode]
Execute standard module shutdown sequence.
Sequence: 1. Begin shutdown 2. Complete any pending tasks (module responsibility) 3. Complete shutdown
- Rückgabetyp:
- Rückgabe:
True if shutdown successful, False otherwise
state.lifecycle_layer¶
Lifecycle Layer - High-level API for module lifecycle management.
This layer controls module existence states: - Startup and initialization - Activation and deactivation - Recovery from failures - Controlled shutdown
Thread-safe wrapper around StateMachine for lifecycle operations.
- class vyra_base.state.lifecycle_layer.LifecycleLayer(fsm=None)[Quellcode]
Bases:
objectHigh-level API for lifecycle state management.
Provides intuitive methods for module lifecycle control: - start() - Begin initialization - activate() - Enter active state - shutdown() - Controlled deactivation - recover() - Recover from faults
Example
>>> lifecycle = LifecycleLayer() >>> lifecycle.start() >>> lifecycle.complete_initialization() >>> lifecycle.get_state() 'Active'
- Parameter:
fsm (StateMachine | None)
- __init__(fsm=None)[Quellcode]
Initialize lifecycle layer.
- Parameter:
fsm (
Optional[StateMachine]) – Existing StateMachine instance. Creates new if None.
- get_state()[Quellcode]
Get current lifecycle state.
- Rückgabetyp:
- get_state_name()[Quellcode]
Get current lifecycle state as string.
- Rückgabetyp:
- is_initializing()[Quellcode]
Check if module is initializing.
- Rückgabetyp:
- is_active()[Quellcode]
Check if module is active.
- Rückgabetyp:
- is_recovering()[Quellcode]
Check if module is recovering.
- Rückgabetyp:
- is_shutting_down()[Quellcode]
Check if module is shutting down.
- Rückgabetyp:
- is_offline()[Quellcode]
Check if module is offline.
- Rückgabetyp:
- is_suspended()[Quellcode]
Check if module is suspended.
- Rückgabetyp:
- can_accept_tasks()[Quellcode]
Check if module can accept operational tasks.
- Rückgabetyp:
- start(metadata=None)[Quellcode]
Start module initialization.
Transitions: Offline → Initializing
- Parameter:
metadata (
Optional[Dict[str,Any]]) – Optional initialization parameters- Rückgabetyp:
- Rückgabe:
New lifecycle state
- Verursacht:
InvalidTransitionError – If not in Offline state
- complete_initialization(result=None)[Quellcode]
Mark initialization as successful.
Transitions: Initializing → Active
- fail_initialization(error=None)[Quellcode]
Mark initialization as failed.
Transitions: Initializing → Recovering
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- shutdown(reason=None)[Quellcode]
Begin controlled shutdown.
Transitions: Active → ShuttingDown
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- complete_shutdown()[Quellcode]
Complete shutdown process.
Transitions: ShuttingDown → Offline
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- enter_suspend(reason=None)[Quellcode]
Suspend the module temporarily (e.g. for maintenance or updates).
Transitions: Active → Suspended
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- Verursacht:
InvalidTransitionError – If not in Active state
- resume_from_suspend(info=None)[Quellcode]
Resume module from Suspended state.
Transitions: Suspended → Active
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- Verursacht:
InvalidTransitionError – If not in Suspended state
- enter_recovery(fault_info=None)[Quellcode]
Enter recovery mode due to fault.
Transitions: Active → Recovering
- complete_recovery(recovery_info=None)[Quellcode]
Complete recovery successfully.
Transitions: Recovering → Active
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- fail_recovery(error=None)[Quellcode]
Mark recovery as failed.
Transitions: Recovering → ShuttingDown
- Parameter:
- Rückgabetyp:
- Rückgabe:
New lifecycle state
- on_state_change(callback, priority=0)[Quellcode]
Register callback for lifecycle state changes.
- Parameter:
callback – Function(layer, old_state, new_state)
priority (
int) – Callback priority (higher = earlier execution)
- get_info()[Quellcode]
Get lifecycle layer information.
state.operational_layer¶
Operational Layer - High-level API for task and activity management.
This layer controls operational states: - Task lifecycle (ready, running, paused, completed) - Processing and delegation - Blocking and unblocking - Auto-reset mechanisms
Thread-safe wrapper around StateMachine for operational control.
- class vyra_base.state.operational_layer.OperationalLayer(fsm)[Quellcode]
Bases:
objectHigh-level API for operational state management.
Provides intuitive methods for task control: - ready() - Signal readiness for tasks - start_task() - Begin task execution - pause() / resume() - Pause and resume tasks - complete() - Mark task completion
Example
>>> operational = OperationalLayer(fsm) >>> operational.ready() >>> operational.start_task({'task_id': '123'}) >>> operational.get_state() 'Running'
- Parameter:
fsm (StateMachine)
- __init__(fsm)[Quellcode]
Initialize operational layer.
- Parameter:
fsm (
StateMachine) – StateMachine instance to control
- get_state()[Quellcode]
Get current operational state.
- Rückgabetyp:
- get_state_name()[Quellcode]
Get current operational state as string.
- Rückgabetyp:
- is_idle()[Quellcode]
Check if operational is idle.
- Rückgabetyp:
- is_ready()[Quellcode]
Check if operational is ready for tasks.
- Rückgabetyp:
- is_running()[Quellcode]
Check if task is running.
- Rückgabetyp:
- is_paused()[Quellcode]
Check if task is paused.
- Rückgabetyp:
- is_stopped()[Quellcode]
Check if task is stopped.
- Rückgabetyp:
- can_start_task()[Quellcode]
Check if new task can be started.
- Rückgabetyp:
- is_busy()[Quellcode]
Check if actively working (running, processing, delegating).
- Rückgabetyp:
- set_ready(metadata=None)[Quellcode]
Signal readiness for task execution.
Transitions: Idle → Ready
- start_task(task_info=None)[Quellcode]
Start task execution.
Transitions: Ready → Running
- pause(reason=None)[Quellcode]
Pause current task.
Transitions: Running → Paused
- Parameter:
- Rückgabetyp:
- Rückgabe:
New operational state
- resume()[Quellcode]
Resume paused task.
Transitions: Paused → Running
- Rückgabetyp:
- Rückgabe:
New operational state
- stop(result=None)[Quellcode]
Mark task as completed.
Transitions: Running → Completed
- reset()[Quellcode]
Reset from Completed to Ready state.
Transitions: Completed → Ready
- Rückgabetyp:
- Rückgabe:
New operational state
- on_state_change(callback, priority=0)[Quellcode]
Register callback for operational state changes.
- Parameter:
callback – Function(layer, old_state, new_state)
priority (
int) – Callback priority (higher = earlier execution)
- get_info()[Quellcode]
Get operational layer information.
state.health_layer¶
Health Layer - High-level API for system health monitoring and management.
This layer monitors system integrity: - Health status tracking (OK, Warning, Overloaded, Faulted, Critical) - Warning and fault reporting - Load management - Recovery coordination - Escalation to lifecycle layer
Thread-safe wrapper around StateMachine for health management.
- class vyra_base.state.health_layer.HealthLayer(fsm)[Quellcode]
Bases:
objectHigh-level API for health state management.
Provides intuitive methods for health monitoring: - report_warning() - Report non-critical issues - recover() - Attempt recovery - escalate() - Escalate to critical state
Example
>>> health = HealthLayer(fsm) >>> health.report_warning({'cpu': '85%'}) >>> health.is_degraded() True >>> health.clear_warning()
- Parameter:
fsm (StateMachine)
- __init__(fsm)[Quellcode]
Initialize health layer.
- Parameter:
fsm (
StateMachine) – StateMachine instance to control
- get_state()[Quellcode]
Get current health state.
- Rückgabetyp:
- get_state_name()[Quellcode]
Get current health state as string.
- Rückgabetyp:
- is_healthy()[Quellcode]
Check if health is OK.
- Rückgabetyp:
- is_warning()[Quellcode]
Check if there are warnings.
- Rückgabetyp:
- is_critical()[Quellcode]
Check if health is critical.
- Rückgabetyp:
- is_degraded()[Quellcode]
Check if health is degraded (warning or worse).
- Rückgabetyp:
- is_operational_safe()[Quellcode]
Check if safe for operational tasks.
- Rückgabetyp:
- report_warning(warning_info=None)[Quellcode]
Report non-critical warning.
Transitions: OK → Warning
- clear_warning(clearance_info=None)[Quellcode]
Clear active warnings.
Transitions: Warning → OK
- report_fault(fault_info=None)[Quellcode]
Report critical fault.
Transitions: OK/Warning → Critical
- Parameter:
- Rückgabetyp:
- Rückgabe:
New health state
- recover(recovery_info=None)[Quellcode]
Attempt recovery from fault.
Transitions: Critical → OK/Warning
- Parameter:
- Rückgabetyp:
- Rückgabe:
New health state
- check_and_report(metrics, warning_threshold=None)[Quellcode]
Check metrics and automatically report appropriate health state.
- Parameter:
- Rückgabetyp:
- Rückgabe:
New health state after evaluation
Example
>>> health.check_and_report( ... {'cpu_usage': 0.85}, ... warning_threshold=0.7, ... overload_threshold=0.9 ... )
- emergency_stop(reason)[Quellcode]
Trigger emergency stop (affects all layers).
This is an interrupt event that immediately: - Sets lifecycle to Deactivated - Sets operational to Idle - Sets health to Warning
- on_state_change(callback, priority=0)[Quellcode]
Register callback for health state changes.
- Parameter:
callback – Function(layer, old_state, new_state)
priority (
int) – Callback priority (higher = earlier execution)
- get_info()[Quellcode]
Get health layer information.
- get_severity_level()[Quellcode]
Get health severity as numeric level.
- Rückgabetyp:
- Rückgabe:
0 = HEALTHY, 1 = Warning, 2 = Critical
state.state_machine¶
Core 3-layer state machine engine for industrial automation.
This implementation follows industrial standards: - IEC 61508 (Functional Safety) - IEC 61131-3 (PLC Programming) - ISO 13849 (Safety of Machinery)
Features: - Thread-safe operation with RLock - Event-driven architecture - Comprehensive logging and tracing - Rule-based state transitions - Layer interaction validation
- exception vyra_base.state.state_machine.StateMachineError[Quellcode]
Bases:
ExceptionBase exception for state machine errors.
- exception vyra_base.state.state_machine.InvalidTransitionError[Quellcode]
Bases:
StateMachineErrorRaised when an invalid state transition is attempted.
- exception vyra_base.state.state_machine.LayerViolationError[Quellcode]
Bases:
StateMachineErrorRaised when layer interaction rules are violated.
- class vyra_base.state.state_machine.StateTransition(from_state, to_state, layer, event, timestamp=<factory>, success=True, error_message=None)[Quellcode]
Bases:
objectRecord of a state transition for auditing and debugging.
- Parameter:
- from_state: str
- to_state: str
- layer: str
- event: StateEvent
- timestamp: datetime
- success: bool = True
- to_dict()[Quellcode]
Convert transition to dictionary.
- class vyra_base.state.state_machine.StateMachineConfig(initial_lifecycle=LifecycleState.OFFLINE, initial_operational=OperationalState.IDLE, initial_health=HealthState.HEALTHY, enable_transition_log=True, max_history_size=1000, strict_mode=True)[Quellcode]
Bases:
objectConfiguration for state machine behavior.
- Parameter:
initial_lifecycle (LifecycleState)
initial_operational (OperationalState)
initial_health (HealthState)
enable_transition_log (bool)
max_history_size (int)
strict_mode (bool)
- initial_lifecycle: LifecycleState = 'Offline'
- initial_operational: OperationalState = 'Idle'
- initial_health: HealthState = 'Healthy'
- operational_on_recovery(current_operational=OperationalState.IDLE)[Quellcode]
- Rückgabetyp:
- Parameter:
current_operational (OperationalState)
- operational_on_shutdown(current_operational=OperationalState.IDLE)[Quellcode]
- Rückgabetyp:
- Parameter:
current_operational (OperationalState)
- enable_transition_log: bool = True
- max_history_size: int = 1000
- strict_mode: bool = True
- __init__(initial_lifecycle=LifecycleState.OFFLINE, initial_operational=OperationalState.IDLE, initial_health=HealthState.HEALTHY, enable_transition_log=True, max_history_size=1000, strict_mode=True)
- Parameter:
initial_lifecycle (LifecycleState)
initial_operational (OperationalState)
initial_health (HealthState)
enable_transition_log (bool)
max_history_size (int)
strict_mode (bool)
- Rückgabetyp:
None
- class vyra_base.state.state_machine.StateMachine(config=None, loop=None)[Quellcode]
Bases:
objectProfessional 3-layer state machine for industrial automation.
Architecture: - Lifecycle Layer: Controls module existence (startup/lifetime/shutdown) - Operational Layer: Manages runtime activity (tasks/processing) - Health Layer: Monitors system integrity (health/warnings/errors)
Layer Interaction Rules: 1. Lifecycle → Operational: Controls allowed states 2. Health → Operational: Regulates behavior 3. Health → Lifecycle: Escalates critical issues 4. Operational cannot directly affect Lifecycle or Health
Thread Safety: All public methods are thread-safe using reentrant locks.
Example
>>> config = StateMachineConfig() >>> fsm = StateMachine(config) >>> fsm.send_event(StateEvent(EventType.START)) >>> fsm.get_current_state() {'lifecycle': 'Initializing', 'operational': 'Idle', 'health': 'OK'}
- Parameter:
config (StateMachineConfig | None)
loop (AbstractEventLoop)
- __init__(config=None, loop=None)[Quellcode]
Initialize the state machine.
- Parameter:
config (
Optional[StateMachineConfig]) – Configuration object. Uses defaults if None.loop (AbstractEventLoop)
- get_current_state()[Quellcode]
Get current state of all layers.
- get_lifecycle_state()[Quellcode]
Get current lifecycle state.
- Rückgabetyp:
- get_operational_state()[Quellcode]
Get current operational state.
- Rückgabetyp:
- get_health_state()[Quellcode]
Get current health state.
- Rückgabetyp:
- is_active()[Quellcode]
Check if module is in Active lifecycle state.
- Rückgabetyp:
- is_operational()[Quellcode]
Check if module can accept operational tasks.
- Rückgabetyp:
- is_healthy()[Quellcode]
Check if module health is OK.
- Rückgabetyp:
- send_event(event)[Quellcode]
Send event to state machine and trigger transitions.
- Parameter:
event (
StateEvent) – StateEvent object- Rückgabetyp:
- Rückgabe:
New state after processing event
- Verursacht:
InvalidTransitionError – In strict mode, if transition is invalid
LayerViolationError – If layer rules are violated
- subscribe(layer, callback, priority=0)[Quellcode]
Subscribe to state changes on a specific layer.
- Parameter:
Example
>>> def on_state_change(layer, old, new): ... print(f"{layer}: {old} -> {new}") >>> fsm.subscribe(StateType.LIFECYCLE, on_state_change)
- unsubscribe(layer, callback)[Quellcode]
Remove a callback subscription.
- get_history(limit=None)[Quellcode]
Get state transition history.
- clear_history()[Quellcode]
Clear transition history.
- get_diagnostic_info()[Quellcode]
Get comprehensive diagnostic information.
state.state_events¶
Event definitions for the 3-layer state machine.
Events trigger state transitions according to the industrial automation event-driven architecture pattern.
- class vyra_base.state.state_events.EventType(*values)[Quellcode]
Bases:
EnumEvent types for state transitions.
- START = 'start'
- INIT_SUCCESS = 'init_success'
- INIT_FAILURE = 'init_failure'
- SET_SUSPENDED = 'set_suspended'
- RESUME_SUSPENDED = 'resume_suspended'
- SHUTDOWN = 'shutdown'
- FINISHED = 'finished'
- FAULT_DETECTED = 'fault_detected'
- RECOVERY_SUCCESS = 'recovery_success'
- RECOVERY_FAILED = 'recovery_failed'
- SET_READY = 'set_ready'
- TASK_START = 'task_start'
- TASK_PAUSE = 'task_pause'
- TASK_RESUME = 'task_resume'
- TASK_COMPLETE = 'task_complete'
- TASK_STOP = 'task_stop'
- TASK_RESET = 'task_reset'
- TASK_ERROR = 'task_error'
- WARN = 'warn'
- CLEAR_WARNING = 'clear_warning'
- FAULT = 'fault'
- RECOVER = 'recover'
- RESET = 'reset'
- INTERRUPT = 'interrupt'
- EMERGENCY_STOP = 'emergency_stop'
- PRIORITY_OVERRIDE = 'priority_override'
- class vyra_base.state.state_events.StateEvent(event_type, timestamp=<factory>, origin_layer=None, payload=None, event_id=None)[Quellcode]
Bases:
objectImmutable event for state machine transitions.
Contains all information about a state transition event including timestamp, origin, and optional payload for tracing and debugging.
- Parameter:
- event_type: EventType
- timestamp: datetime
- to_dict()[Quellcode]
Convert event to dictionary for serialization.
- vyra_base.state.state_events.get_event_target_layer(event_type)[Quellcode]
Get the primary layer affected by an event.
- vyra_base.state.state_events.is_interrupt_event(event_type)[Quellcode]
Check if event is a system interrupt.
state.state_types¶
State type definitions for the 3-layer state machine.
This module defines the valid states for each layer according to industrial automation standards (ISO 13849, IEC 61508).
- class vyra_base.state.state_types.StateType(*values)[Quellcode]
Bases:
EnumEnum for state types.
- LIFECYCLE = 'Lifecycle'
- OPERATIONAL = 'Operational'
- HEALTH = 'Health'
- ANY = 'Any'
- class vyra_base.state.state_types.LifecycleState(*values)[Quellcode]
Bases:
EnumLifecycle states define the existence and high-level life of a module.
Similar to ROS2 Lifecycle nodes and IEC 61131-3 PLC states.
- INITIALIZING = 'Initializing'
- ACTIVE = 'Active'
- RECOVERING = 'Recovering'
- SUSPENDED = 'Suspended'
- SHUTTING_DOWN = 'ShuttingDown'
- OFFLINE = 'Offline'
- class vyra_base.state.state_types.OperationalState(*values)[Quellcode]
Bases:
EnumOperational states define the runtime activity of a module.
Represents what the module is currently doing during normal operation.
- IDLE = 'Idle'
- READY = 'Ready'
- RUNNING = 'Running'
- PAUSED = 'Paused'
- STOPPED = 'Stopped'
- ERROR = 'Error'
- class vyra_base.state.state_types.HealthState(*values)[Quellcode]
Bases:
EnumHealth states describe the integrity and error conditions of a module.
Follows safety integrity levels (SIL) from IEC 61508.
- HEALTHY = 'Healthy'
- WARNING = 'Warning'
- CRITICAL = 'Critical'
- vyra_base.state.state_types.is_valid_lifecycle_transition(from_state, to_state)[Quellcode]
Check if lifecycle transition is valid.
- Rückgabetyp:
- Parameter:
from_state (LifecycleState)
to_state (LifecycleState)
- vyra_base.state.state_types.is_valid_operational_transition(from_state, to_state)[Quellcode]
Check if operational transition is valid.
- Rückgabetyp:
- Parameter:
from_state (OperationalState)
to_state (OperationalState)
- vyra_base.state.state_types.is_valid_health_transition(from_state, to_state)[Quellcode]
Check if health transition is valid.
- Rückgabetyp:
- Parameter:
from_state (HealthState)
to_state (HealthState)
- vyra_base.state.state_types.is_operational_allowed_in_lifecycle(lifecycle, operational)[Quellcode]
Check if operational state is allowed in current lifecycle state.
- Rückgabetyp:
- Parameter:
lifecycle (LifecycleState)
operational (OperationalState)
state.operational_metaclass¶
Metaclass for automatic operational state management.
This module provides a metaclass that automatically wraps lifecycle methods with state validation and transition logic, following industrial automation best practices.
- exception vyra_base.state.operational_metaclass.OperationalStateError[Quellcode]
Bases:
ExceptionRaised when an operation is called in an invalid operational state.
- class vyra_base.state.operational_metaclass.MetaOperationalState(name, bases, attrs)[Quellcode]
Bases:
typeMetaclass that automatically manages operational state transitions.
This metaclass wraps user-defined lifecycle methods and automatically handles:
Pre-condition state validation
State transitions before method execution
Success/failure state transitions after method execution
Error handling and logging
Supported lifecycle methods and their state transitions:
initialize():Pre-condition: IDLE
On success: IDLE -> READY (resets operation counter)
On failure: IDLE -> ERROR
pause():Pre-condition: RUNNING
On success: RUNNING -> PAUSED
On failure: No state change
resume():Pre-condition: PAUSED
On success: PAUSED -> READY (resets operation counter)
On failure: PAUSED -> ERROR
stop():Pre-condition: RUNNING, PAUSED
On success: (current) -> STOPPED
On failure: (current) -> ERROR
reset():Pre-condition: STOPPED, ERROR
On success: (current) -> IDLE
On failure: No state change
Example
>>> class MyModule(OperationalStateMachine): ... def initialize(self): ... # Setup hardware, load config, etc. ... print("Initializing...") ... return True ... >>> >>> module = MyModule(state_machine) >>> module.initialize() # Automatically: IDLE -> READY on success
- STATE_RULES = {'initialize': {'failure_transition': OperationalState.ERROR, 'pre_transition': None, 'required_states': {OperationalState.IDLE}, 'reset_counter': True, 'success_transition': OperationalState.READY}, 'pause': {'failure_transition': OperationalState.ERROR, 'pre_transition': None, 'required_states': {OperationalState.RUNNING}, 'reset_counter': False, 'success_transition': OperationalState.PAUSED}, 'reset': {'failure_transition': None, 'pre_transition': None, 'required_states': {OperationalState.ERROR, OperationalState.STOPPED}, 'reset_counter': False, 'success_transition': OperationalState.IDLE}, 'resume': {'failure_transition': OperationalState.ERROR, 'pre_transition': None, 'required_states': {OperationalState.PAUSED}, 'reset_counter': True, 'success_transition': OperationalState.READY}, 'stop': {'failure_transition': OperationalState.ERROR, 'pre_transition': None, 'required_states': {OperationalState.PAUSED, OperationalState.RUNNING}, 'reset_counter': False, 'success_transition': OperationalState.STOPPED}}
state.operation_decorator¶
Operation decorator for automatic state management with reference counting.
This module provides a decorator that can be applied to any method to automatically manage operational state transitions based on active operation count.
- class vyra_base.state.operation_decorator.OperationConfig(required_states=None, pre_transition=None, success_transition=None, failure_transition=None, use_reference_counting=True)[Quellcode]
Bases:
objectConfiguration for operation decorator behavior.
- Parameter:
required_states (Set[OperationalState] | None)
pre_transition (OperationalState | None)
success_transition (OperationalState | None)
failure_transition (OperationalState | None)
use_reference_counting (bool)
- __init__(required_states=None, pre_transition=None, success_transition=None, failure_transition=None, use_reference_counting=True)[Quellcode]
Initialize operation configuration.
- Parameter:
required_states (
Optional[Set[OperationalState]]) – Set of states required before operation can executepre_transition (
Optional[OperationalState]) – State to transition to before execution (if not using ref counting)success_transition (
Optional[OperationalState]) – State to transition to on success (if not using ref counting)failure_transition (
Optional[OperationalState]) – State to transition to on failure (if not using ref counting)use_reference_counting (
bool) – If True, use reference counting for READY<->RUNNING transitions
- vyra_base.state.operation_decorator.operation(func=None, *, required_states=None, pre_transition=None, success_transition=None, failure_transition=None, use_reference_counting=True)[Quellcode]
Decorator for methods that need automatic operational state management.
This decorator wraps a method with state validation and transition logic. When reference counting is enabled (default), it automatically manages READY <-> RUNNING transitions based on the number of active operations.
Default behavior with reference counting: - Pre-condition: READY or RUNNING state - Before execution: If in READY, transition to RUNNING and increment counter - After execution: Decrement counter; if counter reaches 0, transition to READY
Custom behavior (use_reference_counting=False): - Use custom required_states, pre_transition, success/failure transitions
- Parameter:
func (
Optional[Callable]) – Function to decorate (provided automatically when used without parentheses)required_states (
Optional[Set[OperationalState]]) – States that must be active before operation can runpre_transition (
Optional[OperationalState]) – State to transition to before executionsuccess_transition (
Optional[OperationalState]) – State to transition to on successfailure_transition (
Optional[OperationalState]) – State to transition to on failureuse_reference_counting (
bool) – Enable automatic reference counting for READY<->RUNNING
- Rückgabetyp:
Example
>>> from vyra_base import state >>> >>> class MyModule(state.OperationalStateMachine): ... @state.operation ... def process_data(self, data): ... # This method is automatically wrapped with state management ... # State will be RUNNING while executing ... result = self._do_processing(data) ... return result ... ... @state.operation(required_states={OperationalState.RUNNING}) ... def critical_task(self): ... # This can only run when already in RUNNING state ... pass
- Rückgabetyp:
- Rückgabe:
Decorated function with state management
- Parameter:
func (Callable | None)
required_states (Set[OperationalState] | None)
pre_transition (OperationalState | None)
success_transition (OperationalState | None)
failure_transition (OperationalState | None)
use_reference_counting (bool)