To provide some feedback I vould like to show the code which works fine
for me as a FSM machine. As speed is not the crucial issue for my
application, I have decided to use an approach showed in the Skip
Montanaro's code.
http://orca.mojam.com/~skip/python/fsm.py
(it is using dictionary to store state/transition dependencies).
Tanks to all for your previous postings.
Petr Jakes
State machine example, for the pull/push button mentioned earlier in
this discussion thread
class FSM:
'''the "states" dictionary contains user defined "state/transition
table" in the format:
{'start_state': {'event': {'guard': ('action', 'end_state')}},
according to the actual "start_state", "event" and "guard"
combination,
the "execute" method reads the relevant "action" and "end_state"
from the "states" dictionary, then executes "action" and setup
"end_state" '''
def __init__(self):
self.states = {}
def add(self,start_state, event_trigger,event_guard,
action,newstate):
"""add a new "state/transition" information to the state
machine dictionary"""
if self.states.has_key(start_state)== False :
self.states[start_state]={}
if self.states[start_state].has_key(event_trigger)== False :
self.states[start_state][event_trigger]={}
if
self.states[start_state][event_trigger].has_key(event_guard)== False :
self.states[start_state][event_trigger][event_guard]={}
self.states[start_state][event_trigger][event_guard]=(action,
newstate)
def start(self, state):
"""set the start state"""
self.state = state
def execute(self, event,guard=None):
'''according to the actual "start_state", "event" and "guard"
combination
read the relevant "action" and "end_state from the
"states" dictionary,
then execute "action" and setup "end_state" '''
action, end_state = self.states[self.state][event][guard]
if action is not None:
apply(action, (self.state, event))
self.state = end_state
return
'''actions they has to be executed while the event occurs'''
def motor_off(state, input): print "pushing the switch to the OFF
position"
def motor_on(state, input): print "lifting the switch to the ON
position"
fsm = FSM()
'''we have to define "state/transition table" first,
wher state transitions are defined as:
('start_state', 'event', 'guard', 'action', 'end_state)'''
fsm.add("ON","lift",None,None,"ON")
fsm.add("ON","push",None,motor_off,"OFF")
fsm.add("OFF","push",None,None,"OFF")
fsm.add("OFF","lift",None,motor_on,"ON")
fsm.start("ON")
print "start state is", fsm.state
events=("push","push","push","lift","lift","push","lift","push","lift","lift","lift","push","lift")
for event in (events):
fsm.execute(event)
print "switch is ", fsm.state