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)[source]
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'}
- Parameters:
config (StateMachineConfig | None)
- __init__(config=None)[source]
Initialize unified state machine.
- Parameters:
config (
Optional[StateMachineConfig]) – Configuration for state machine behavior
- get_lifecycle_state()[source]
Get lifecycle state.
- Return type:
- get_operational_state()[source]
Get operational state.
- Return type:
- get_health_state()[source]
Get health state.
- Return type:
- start(metadata=None)[source]
Start module initialization.
- Return type:
- Parameters:
- complete_initialization(result=None)[source]
Complete initialization successfully.
- Return type:
- Parameters:
- fail_initialization(error=None)[source]
Mark initialization as failed.
- Return type:
- Parameters:
error (str | None)
- shutdown(reason=None)[source]
Begin controlled shutdown.
- Return type:
- Parameters:
reason (str | None)
- complete_shutdown()[source]
Complete shutdown process.
- Return type:
- suspend(reason=None)[source]
Suspend the module temporarily (e.g. for maintenance or updates).
Transitions: Active → Suspended
- Parameters:
- Return type:
- Returns:
New lifecycle state
- resume_from_suspend(info=None)[source]
Resume module from Suspended state.
Transitions: Suspended → Active
- enter_recovery(fault_info=None)[source]
Enter recovery mode due to fault.
Transitions: Active → Recovering
- complete_recovery(recovery_info=None)[source]
Complete recovery successfully.
Transitions: Recovering → Active
- Parameters:
- Return type:
- Returns:
New lifecycle state
- fail_recovery(error=None)[source]
Mark recovery as failed.
Transitions: Recovering → ShuttingDown
- Parameters:
- Return type:
- Returns:
New lifecycle state
- set_ready(metadata=None)[source]
Signal readiness for tasks.
- Return type:
- Parameters:
- start_task(task_info=None)[source]
Start task execution.
- Return type:
- Parameters:
- resume()[source]
Resume paused task.
- Return type:
- stop(result=None)[source]
Mark task as completed.
- Return type:
- Parameters:
- reset()[source]
Reset operational state to Idle.
- Return type:
- report_warning(warning_info=None)[source]
Report non-critical warning.
- Return type:
- Parameters:
- report_fault(fault_info=None)[source]
Report critical fault.
- Return type:
- Parameters:
- recover(recovery_info=None)[source]
Attempt recovery from fault.
- Return type:
- Parameters:
- emergency_stop(reason)[source]
Trigger emergency stop.
- on_lifecycle_change(callback, priority=0)[source]
Subscribe to lifecycle state changes.
- on_operational_change(callback, priority=0)[source]
Subscribe to operational state changes.
- on_health_change(callback, priority=0)[source]
Subscribe to health state changes.
- on_any_change(callback, priority=0)[source]
Subscribe to any state change across all layers.
- clear_history()[source]
Clear transition history.
- send_event(event)[source]
Send an event to the state machine.
This method is required for compatibility with OperationalStateMachine which calls _state_machine.send_event(event).
- Parameters:
event – StateEvent to send to the FSM
- standard_startup()[source]
Execute standard module startup sequence.
Sequence: 1. Start initialization 2. Complete initialization 3. Set operational ready
- Return type:
- Returns:
True if startup successful, False otherwise
OperationalStateMachine¶
Base class for components that use operational state management.
- class vyra_base.state.operational_state_machine.OperationalStateMachine(state_machine)[source]
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
- Parameters:
state_machine (StateMachine)
- __init__(state_machine)[source]
Initialize the operational state machine.
- Parameters:
state_machine (
StateMachine) – The underlying 3-layer StateMachine instance
- get_operational_state()[source]
Get current operational state.
- Return type:
- get_all_states()[source]
Get all current states (lifecycle, operational, health).
State Types¶
LifecycleState¶
- class vyra_base.state.state_types.LifecycleState(*values)[source]
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)[source]
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¶
Event System¶
StateEvent¶
- class vyra_base.state.state_events.StateEvent(event_type, timestamp=<factory>, origin_layer=None, payload=None, event_id=None)[source]
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.
- Parameters:
- event_type: EventType
- timestamp: datetime
EventType¶
- class vyra_base.state.state_events.EventType(*values)[source]
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)[source]
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'}
- Parameters:
config (StateMachineConfig | None)
- __init__(config=None)[source]
Initialize unified state machine.
- Parameters:
config (
Optional[StateMachineConfig]) – Configuration for state machine behavior
- get_lifecycle_state()[source]
Get lifecycle state.
- Return type:
- get_operational_state()[source]
Get operational state.
- Return type:
- get_health_state()[source]
Get health state.
- Return type:
- start(metadata=None)[source]
Start module initialization.
- Return type:
- Parameters:
- complete_initialization(result=None)[source]
Complete initialization successfully.
- Return type:
- Parameters:
- fail_initialization(error=None)[source]
Mark initialization as failed.
- Return type:
- Parameters:
error (str | None)
- shutdown(reason=None)[source]
Begin controlled shutdown.
- Return type:
- Parameters:
reason (str | None)
- complete_shutdown()[source]
Complete shutdown process.
- Return type:
- suspend(reason=None)[source]
Suspend the module temporarily (e.g. for maintenance or updates).
Transitions: Active → Suspended
- Parameters:
- Return type:
- Returns:
New lifecycle state
- resume_from_suspend(info=None)[source]
Resume module from Suspended state.
Transitions: Suspended → Active
- enter_recovery(fault_info=None)[source]
Enter recovery mode due to fault.
Transitions: Active → Recovering
- complete_recovery(recovery_info=None)[source]
Complete recovery successfully.
Transitions: Recovering → Active
- Parameters:
- Return type:
- Returns:
New lifecycle state
- fail_recovery(error=None)[source]
Mark recovery as failed.
Transitions: Recovering → ShuttingDown
- Parameters:
- Return type:
- Returns:
New lifecycle state
- set_ready(metadata=None)[source]
Signal readiness for tasks.
- Return type:
- Parameters:
- start_task(task_info=None)[source]
Start task execution.
- Return type:
- Parameters:
- resume()[source]
Resume paused task.
- Return type:
- stop(result=None)[source]
Mark task as completed.
- Return type:
- Parameters:
- reset()[source]
Reset operational state to Idle.
- Return type:
- report_warning(warning_info=None)[source]
Report non-critical warning.
- Return type:
- Parameters:
- report_fault(fault_info=None)[source]
Report critical fault.
- Return type:
- Parameters:
- recover(recovery_info=None)[source]
Attempt recovery from fault.
- Return type:
- Parameters:
- emergency_stop(reason)[source]
Trigger emergency stop.
- on_lifecycle_change(callback, priority=0)[source]
Subscribe to lifecycle state changes.
- on_operational_change(callback, priority=0)[source]
Subscribe to operational state changes.
- on_health_change(callback, priority=0)[source]
Subscribe to health state changes.
- on_any_change(callback, priority=0)[source]
Subscribe to any state change across all layers.
- clear_history()[source]
Clear transition history.
- send_event(event)[source]
Send an event to the state machine.
This method is required for compatibility with OperationalStateMachine which calls _state_machine.send_event(event).
- Parameters:
event – StateEvent to send to the FSM
- standard_startup()[source]
Execute standard module startup sequence.
Sequence: 1. Start initialization 2. Complete initialization 3. Set operational ready
- Return type:
- Returns:
True if startup 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)[source]
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'
- Parameters:
fsm (StateMachine | None)
- __init__(fsm=None)[source]
Initialize lifecycle layer.
- Parameters:
fsm (
Optional[StateMachine]) – Existing StateMachine instance. Creates new if None.
- get_state()[source]
Get current lifecycle state.
- Return type:
- start(metadata=None)[source]
Start module initialization.
Transitions: Offline → Initializing
- Parameters:
metadata (
Optional[Dict[str,Any]]) – Optional initialization parameters- Return type:
- Returns:
New lifecycle state
- Raises:
InvalidTransitionError – If not in Offline state
- complete_initialization(result=None)[source]
Mark initialization as successful.
Transitions: Initializing → Active
- fail_initialization(error=None)[source]
Mark initialization as failed.
Transitions: Initializing → Recovering
- Parameters:
- Return type:
- Returns:
New lifecycle state
- shutdown(reason=None)[source]
Begin controlled shutdown.
Transitions: Active → ShuttingDown
- Parameters:
- Return type:
- Returns:
New lifecycle state
- complete_shutdown()[source]
Complete shutdown process.
Transitions: ShuttingDown → Offline
- Return type:
- Returns:
New lifecycle state
- enter_suspend(reason=None)[source]
Suspend the module temporarily (e.g. for maintenance or updates).
Transitions: Active → Suspended
- Parameters:
- Return type:
- Returns:
New lifecycle state
- Raises:
InvalidTransitionError – If not in Active state
- resume_from_suspend(info=None)[source]
Resume module from Suspended state.
Transitions: Suspended → Active
- Parameters:
- Return type:
- Returns:
New lifecycle state
- Raises:
InvalidTransitionError – If not in Suspended state
- enter_recovery(fault_info=None)[source]
Enter recovery mode due to fault.
Transitions: Active → Recovering
- complete_recovery(recovery_info=None)[source]
Complete recovery successfully.
Transitions: Recovering → Active
- Parameters:
- Return type:
- Returns:
New lifecycle state
- fail_recovery(error=None)[source]
Mark recovery as failed.
Transitions: Recovering → ShuttingDown
- Parameters:
- Return type:
- Returns:
New lifecycle state
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)[source]
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'
- Parameters:
fsm (StateMachine)
- __init__(fsm)[source]
Initialize operational layer.
- Parameters:
fsm (
StateMachine) – StateMachine instance to control
- get_state()[source]
Get current operational state.
- Return type:
- set_ready(metadata=None)[source]
Signal readiness for task execution.
Transitions: Idle → Ready
- start_task(task_info=None)[source]
Start task execution.
Transitions: Ready → Running
- pause(reason=None)[source]
Pause current task.
Transitions: Running → Paused
- Parameters:
- Return type:
- Returns:
New operational state
- resume()[source]
Resume paused task.
Transitions: Paused → Running
- Return type:
- Returns:
New operational state
- stop(result=None)[source]
Mark task as completed.
Transitions: Running → Completed
- reset()[source]
Reset from Completed to Ready state.
Transitions: Completed → Ready
- Return type:
- Returns:
New operational state
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)[source]
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()
- Parameters:
fsm (StateMachine)
- __init__(fsm)[source]
Initialize health layer.
- Parameters:
fsm (
StateMachine) – StateMachine instance to control
- get_state()[source]
Get current health state.
- Return type:
- report_warning(warning_info=None)[source]
Report non-critical warning.
Transitions: OK → Warning
- clear_warning(clearance_info=None)[source]
Clear active warnings.
Transitions: Warning → OK
- report_fault(fault_info=None)[source]
Report critical fault.
Transitions: OK/Warning → Critical
- Parameters:
- Return type:
- Returns:
New health state
- recover(recovery_info=None)[source]
Attempt recovery from fault.
Transitions: Critical → OK/Warning
- Parameters:
- Return type:
- Returns:
New health state
- check_and_report(metrics, warning_threshold=None)[source]
Check metrics and automatically report appropriate health state.
- Parameters:
- Return type:
- Returns:
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)[source]
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)[source]
Register callback for health state changes.
- Parameters:
callback – Function(layer, old_state, new_state)
priority (
int) – Callback priority (higher = earlier execution)
- get_info()[source]
Get health layer information.
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[source]
Bases:
ExceptionBase exception for state machine errors.
- exception vyra_base.state.state_machine.InvalidTransitionError[source]
Bases:
StateMachineErrorRaised when an invalid state transition is attempted.
- exception vyra_base.state.state_machine.LayerViolationError[source]
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)[source]
Bases:
objectRecord of a state transition for auditing and debugging.
- Parameters:
- from_state: str
- to_state: str
- layer: str
- event: StateEvent
- timestamp: datetime
- success: bool = True
- 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)[source]
Bases:
objectConfiguration for state machine behavior.
- Parameters:
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)[source]
- Return type:
- Parameters:
current_operational (OperationalState)
- operational_on_shutdown(current_operational=OperationalState.IDLE)[source]
- Return type:
- Parameters:
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)
- Parameters:
initial_lifecycle (LifecycleState)
initial_operational (OperationalState)
initial_health (HealthState)
enable_transition_log (bool)
max_history_size (int)
strict_mode (bool)
- Return type:
None
- class vyra_base.state.state_machine.StateMachine(config=None, loop=None)[source]
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'}
- Parameters:
config (StateMachineConfig | None)
loop (AbstractEventLoop)
- __init__(config=None, loop=None)[source]
Initialize the state machine.
- Parameters:
config (
Optional[StateMachineConfig]) – Configuration object. Uses defaults if None.loop (AbstractEventLoop)
- get_current_state()[source]
Get current state of all layers.
- get_lifecycle_state()[source]
Get current lifecycle state.
- Return type:
- get_operational_state()[source]
Get current operational state.
- Return type:
- get_health_state()[source]
Get current health state.
- Return type:
- send_event(event)[source]
Send event to state machine and trigger transitions.
- Parameters:
event (
StateEvent) – StateEvent object- Return type:
- Returns:
New state after processing event
- Raises:
InvalidTransitionError – In strict mode, if transition is invalid
LayerViolationError – If layer rules are violated
- subscribe(layer, callback, priority=0)[source]
Subscribe to state changes on a specific layer.
- Parameters:
Example
>>> def on_state_change(layer, old, new): ... print(f"{layer}: {old} -> {new}") >>> fsm.subscribe(StateType.LIFECYCLE, on_state_change)
- unsubscribe(layer, callback)[source]
Remove a callback subscription.
- get_history(limit=None)[source]
Get state transition history.
- clear_history()[source]
Clear transition history.
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)[source]
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)[source]
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.
- Parameters:
- event_type: EventType
- timestamp: datetime
- vyra_base.state.state_events.get_event_target_layer(event_type)[source]
Get the primary layer affected by an event.
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)[source]
Bases:
EnumEnum for state types.
- LIFECYCLE = 'Lifecycle'
- OPERATIONAL = 'Operational'
- HEALTH = 'Health'
- ANY = 'Any'
- class vyra_base.state.state_types.LifecycleState(*values)[source]
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)[source]
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)[source]
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)[source]
Check if lifecycle transition is valid.
- Return type:
- Parameters:
from_state (LifecycleState)
to_state (LifecycleState)
- vyra_base.state.state_types.is_valid_operational_transition(from_state, to_state)[source]
Check if operational transition is valid.
- Return type:
- Parameters:
from_state (OperationalState)
to_state (OperationalState)
- vyra_base.state.state_types.is_valid_health_transition(from_state, to_state)[source]
Check if health transition is valid.
- Return type:
- Parameters:
from_state (HealthState)
to_state (HealthState)
- vyra_base.state.state_types.is_operational_allowed_in_lifecycle(lifecycle, operational)[source]
Check if operational state is allowed in current lifecycle state.
- Return type:
- Parameters:
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[source]
Bases:
ExceptionRaised when an operation is called in an invalid operational state.
- class vyra_base.state.operational_metaclass.MetaOperationalState(name, bases, attrs)[source]
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)[source]
Bases:
objectConfiguration for operation decorator behavior.
- Parameters:
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)[source]
Initialize operation configuration.
- Parameters:
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)[source]
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
- Parameters:
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
- Return type:
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
- Return type:
- Returns:
Decorated function with state management
- Parameters:
func (Callable | None)
required_states (Set[OperationalState] | None)
pre_transition (OperationalState | None)
success_transition (OperationalState | None)
failure_transition (OperationalState | None)
use_reference_counting (bool)