我正在python中使用Transitions来实现受驱动的有限状态机事件。
我想实现一个FSM,其中转换是通过避免if / elif语句处理的事件触发的。
例如:我有一个简单的灯泡FSM,如果它(以不确定性的方式)发生'goInlampOn'
事件,如果发生'goInlampOff'
事件,我们将移至“ on”状态到达时,我们进入'off'
状态。
所以我的问题是:
有没有一种方法可以在FSM类中创建一个名为process_event(event)
的方法,该方法可以使用我的FSM逻辑处理每个事件,而无需使用很长时间(在这种情况下不是很简单)的if-elif声明?
下面是代码示例:
class MyFsm(object):
transitions = [
{'trigger': 'switchOff', 'source':'on', 'dest':'off'},
{'trigger': 'switchOn', 'source':'off', 'dest':'on'}
]
def __init__(self):
''' initialating the FSM '''
self.machine = Machine(model=self, states=self.states,
transitions=self.transitions, initial='on')
on = On()
off = Off()
self.machine.add_state(off)
self.machine.add_state(on)
# A SMART SOLUTION TO IMPLEMENT THIS METHOD WITHOUT USING
# if state == off: ... elif state==on...
def process_event(self,event):
if self.state == 'off':
if event == 'goInlampOn':
self.switchOn()
elif self.state == 'on':
if event == 'goInlampOff':
self.switchOff()
在我介绍的情况下,只有2个州,但是如果我有10个或15个州?
我尝试实施我认为@aleneum向我建议的解决方案。但是,在这种解决方案中,我必须记录两次状态机的转换。
这是正确的 ?会有更好的解决方案(避免两次编写过渡)吗?
这是具有4个状态(A,B,C,D)的状态机,唯一允许的转换是:
1. A-> B
2. B-> C
3. C-> D
4. D-> A
5. C-> A
这里的代码:
from transitions import Machine
from states import A,B,C,D
class MyFsm(object):
transitions = [
{'trigger': 'go_in_B_fromA','source':'A','dest':'B'},
{'trigger': 'go_in_C_fromB','source':'B','dest':'C'},
{'trigger': 'go_in_D_fromC','source':'C','dest':'D'},
{'trigger': 'go_in_A_fromD','source':'D','dest':'A'},
{'trigger': 'go_in_A_fromC','source':'C','dest':'A'},
{'trigger': 'go_in_B_fromA','source':['C','D','B'],'dest':None},
{'trigger': 'go_in_C_fromB','source':['C','D','A'],'dest':None},
{'trigger': 'go_in_D_fromC','source':['B','D','A'],'dest':None},
{'trigger': 'go_in_A_fromD','source':['B','A','C'],'dest':None},
{'trigger': 'go_in_A_fromC','source':['D','A','B'],'dest':None}
]
def __init__(self):
self.machine = Machine(model=self, states = self.states ,transitions= self.transitions, initial = 'A' )
a = A()
b = B()
c = C()
d = D()
self.machine.add_state(a)
self.machine.add_state(b)
self.machine.add_state(c)
self.machine.add_state(d)
def process_event(self,event):
if event == 'go_in_B_fromA' :
self.go_in_B_fromA()
if event == 'go_in_C_fromB' :
self.go_in_C_fromB()
if event == 'go_in_D_fromC' :
self.go_in_D_fromC()
if event == 'go_in_A_fromD' :
self.go_in_A_fromD()
if event == 'go_in_A_fromC' :
self.go_in_A_fromC()
'''my main is something like this'''
myfsm = MyFsm()
while True:
event = event_from_external_bahaviour()
myfsm.process_event(event)
答案 0 :(得分:2)
我不确定我是否理解您的问题,因为使用过渡之类的库的目的是避免编写较长的if
-else if
链。而且,文档从未提及您应该重新实现process_event()
。
因此,我只能将文档解释为带有您的示例的过渡版本,而没有ifs
。希望对您有帮助。
from transitions import Machine
class Model:
def __init__(self):
self.machine = Machine(
model=self,
states=["on", "off"],
transitions=[
{
"trigger": "switchOff",
"source": "on",
"dest": "off",
},
{
"trigger": "switchOn",
"source": "off",
"dest": "on",
},
],
initial="on",
ignore_invalid_triggers=True,
)
m = Model()
assert m.state == "on"
# We are in state 'on' and there is not 'switchOn'
# transition defined: nothing happens.
#
# Without `ignore_invalid_triggers`, transitions
# would raise an exception.
m.switchOn()
assert m.state == "on"
# We still are in 'on' and 'switchOff' brings
# us to 'off.
m.switchOff()
assert m.state == "off"
例如,您可能会考虑阅读有关UML状态机的Wikipedia文章,因为过渡非常接近于实现它。
答案 1 :(得分:0)
如@martineau所述,事件的影响/模型的行为应由其当前状态确定。实际上,要使用状态机避免大块的if / then语句。 看一下以下代码片段:
from transitions.core import Machine, State, MachineError
class On(State):
def __init__(self, *args, **kwargs):
super(On, self).__init__(*args, **kwargs)
class Off(State):
def __init__(self, *args, **kwargs):
super(Off, self).__init__(*args, **kwargs)
class MyFsm(object):
transitions = [
{'trigger': 'switchOff', 'source':'on', 'dest':'off'},
{'trigger': 'switchOn', 'source':'off', 'dest':'on'}
]
def __init__(self):
# ignore_invalid_triggers will allow to process events not defined for a state
on = On(name='on', ignore_invalid_triggers=True)
off = Off(name='off', ignore_invalid_triggers=False)
self.machine = Machine(model=self, states=[on, off], transitions=self.transitions, initial='on')
machine = MyFsm()
print(machine.state) # >>> on
machine.switchOff()
print(machine.state) # >>> off
try:
# this will raise a MachineException because there is no transition 'switchOff'
# defined in state 'off'
machine.switchOff() # raises MachineException
raise Exception("This exception will not be raised")
except MachineError:
pass
print(machine.state) # >>> off
machine.switchOn()
print(machine.state) # >>> on
# this will NOT raise an Exception since we configured 'on'
# to ignore transitions not defined for this state
machine.switchOn()
print(machine.state) # >>> on
我为On
和Off
定义了一些占位符类,因为我假设您想使用自定义状态类。 transitions
使您可以仅触发模型的方法而无需跟踪当前状态。您的配置将确定将要发生的情况。如果触发了未针对您的状态定义的方法,则可以根据您的需要引发MachineError
。
考虑到您的示例,我建议只忽略无效的触发器,因为尝试两次打开或关闭灯都没什么大不了的。
如果您要避免无效触发器,则另一种解决方案是“循环”状态或使用internal转换:
# leaves and enters state off even if its already off
# processes all on_enter/exit callbacks
{'trigger': 'switchOff', 'source':['on', 'off'], 'dest':'off'}
# an internal transition is defined by having dest set to 'None'
# processes no state callbacks
{'trigger': 'switchOff', 'source': 'off', 'dest': None}
这在很大程度上取决于您的用例和使用此状态机实际控制的系统,哪种行为是首选。