state_machine (State Machine)

Author:

Description:

This Module helps implementing state machines.

Submodules:

Unittest:

See also the unittest documentation.

Module Documentation:

class state_machine.state_machine(default_state, log_lvl, **kwargs)
Parameters:
  • default_state – The default state which is set on initialisation.
  • log_lvl – The log level, this Module logs to (see Loging-Levels of Module logging)

Note

Additional keyword parameters well be stored as varibles of the instance (e.g. to give variables or methods for transition condition calculation).

A state machine class can be created by deriving it from this class. The transitions are defined by overriding the variable TRANSITIONS. This Variable is a dictionary, where the key is the start-state and the content is a tuple or list of transitions. Each transition is a tuple or list including the following information: (condition-method (str), transition-time (number), target_state (str)).

Note

The condition-method needs to be implemented as part of the new class.

Note

It is usefull to define the states as variables of this class.

Example:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys
sys.path.append('../..')
import logging
import os

import report
import state_machine

logger = logging.getLogger('root')
report.stdoutLoggingConfigure(log_name_lvl=[('root', 'DEBUG'), ])


class trafic_lights(state_machine.state_machine):
    LOG_PREFIX = 'TraficLights:'

    STATE_RED = 'state_red'
    STATE_GREEN = 'state_green'

    CONDITION_TRUE = 'condition_true'
    CONDITION_PEDASTRIAN_REQUEST = 'condition_pedastrian_request'

    TRANSITIONS = {
        STATE_RED: (
            (CONDITION_PEDASTRIAN_REQUEST, 1, STATE_GREEN),
        ),
        STATE_GREEN: (
            (CONDITION_TRUE, 3, STATE_RED),
        )
    }

    def condition_true(self):
        return True

    def set_padestrian_request(self):
        logger.log(self.__log_lvl__, '%s Pedestrian gave state change request.', self.LOG_PREFIX)
        self.pedastrian_request = True

    def condition_pedastrian_request(self):
        return self.pedastrian_request


sm = trafic_lights(trafic_lights.STATE_RED, logging.INFO, pedastrian_request=False)
sm.register_state_change_callback(sm.STATE_GREEN, sm.CONDITION_PEDASTRIAN_REQUEST, logger.info, 'Callback information: Traffic light had been changed to green caused by pedastrian request')
while not sm.previous_state_was(sm.STATE_GREEN):
    if sm.this_state_is(sm.STATE_RED) and sm.this_state_duration() > 0.2 and not sm.condition_pedastrian_request():
        sm.set_padestrian_request()
    sm.work()
2023-10-26 00:01:00,243: root.state_machine - INFO - TraficLights: State change ('__init__'): None -> 'state_red'
2023-10-26 00:01:00,443: root - INFO - TraficLights: Pedestrian gave state change request.
2023-10-26 00:01:01,443: root.state_machine - INFO - TraficLights: State change ('condition_pedastrian_request'): 'state_red' -> 'state_green'
2023-10-26 00:01:01,444: root.state_machine - DEBUG - Executing callback 0 - logging.info
2023-10-26 00:01:01,444: root - INFO - Callback information: Traffic light had been changed to green caused by pedastrian request
2023-10-26 00:01:04,444: root.state_machine - INFO - TraficLights: State change ('condition_true'): 'state_green' -> 'state_red'
last_transition_condition()
Returns:The last transition condition.
Return type:str

This method returns the last transition condition.

last_transition_condition_was(condition)
Parameters:condition (str) – The condition to be checked
Returns:True if the given condition was the last transition condition, else False.
Return type:bool

This methods returns the boolean information if the last transition condition is equivalent to the given condition.

previous_state()
Returns:The previous state.
Return type:str

This method returns the previous state of the state machine.

previous_state_duration()
Returns:The time how long the previous state was active.
Return type:float

This method returns the time how long the previous state was active.

previous_state_was(state)
Parameters:state (str) – The state to be checked
Returns:True if the given state was previously active, else False.
Return type:bool

This methods returns the boolean information if the state machine was previously in the given state.

register_state_change_callback(state, condition, callback, *args, **kwargs)
Parameters:
  • state (str) – The target state. The callback will be executed, if the state machine changes to this state. None means all states.
  • condition (str) – The transition condition. The callback will be executed, if this condition is responsible for the state change. None means all conditions.
  • callback – The callback to be executed.

Note

Additional arguments and keyword parameters are supported. These arguments and parameters will be used as arguments and parameters for the callback execution.

This methods allows to register callbacks which will be executed on state changes.

this_state()
Returns:The current state.

This method returns the current state of the state machine.

this_state_duration()
Returns:The time how long the current state is active.
Return type:float

This method returns the time how long the current state is active.

this_state_is(state)
Parameters:state (str) – The state to be checked
Returns:True if the given state is currently active, else False.
Return type:bool

This methods returns the boolean information if the state machine is currently in the given state.

work()

This Method needs to be executed cyclicly to enable the state machine.