-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_fsm.py
58 lines (40 loc) · 1.52 KB
/
simple_fsm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 19:26:02 2020
@author: BhaveshAchhada
"""
class fsm:
def __init__(self):
self.start_state = None
self.end_states = []
self.num_states = 0
self.current_state = None
self.state_handlers = {}
def add_state(self,state,handler,is_end_state = False):
state = state.lower()
if self.num_states == 0:
self.start_state = state
self.current_state = state
self.state_handlers[state] = handler
if is_end_state:
self.end_states.append(state)
self.num_states += 1
def run(self, cargo):
try:
handler = self.state_handlers[self.start_state]
except:
raise Exception("There must be at least one state.")
if len(self.end_states) == 0:
raise Exception("There must be at least one end state.")
while True:
(newState , cargo) = handler(cargo)
newState = newState.lower()
handler = self.state_handlers[newState]
# if newState in self.end_states:
# handler = self.state_handlers[newState]
# response = handler(cargo)
# # print( str(newState) + " - reached.")
# # break
# else:
# handler = self.state_handlers[newState]
# return response