gpt4 book ai didi

python - 事件驱动的有限状态机中的转换

转载 作者:行者123 更新时间:2023-11-30 22:05:23 24 4
gpt4 key购买 nike

我正在使用Transitions在Python中实现事件驱动的有限状态机。

我想实现一个 FSM,其中转换由通过避免 if/elif 语句进行处理的事件触发。

例如:我有一个简单的灯 FSM,如果它(以非确定性方式)发生 'goInlampOn' 事件,我们将移至“on”状态,如果 'goInlampOff' 事件到达,我们进入 '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)

最佳答案

正如 @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

我为 OnOff 定义了一些占位符类,因为我假设您想使用自定义状态类。 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}

这很大程度上取决于您的用例以及您使用此状态机实际控制的系统,哪种行为是首选。

关于python - 事件驱动的有限状态机中的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53036689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com