我正在使用PyTransitions生成一个简单的有限状态机,并使用一个yml文件对其进行配置。示例可能如下所示:
initial: A
states:
- A
- B
- C
transitions:
- {trigger: "AtoC", source: "A", dest: "C"}
- {trigger: "CtoB", source: "C", dest: "B"}我的问题是,使用yml文件,我如何在状态输出中写入?例如,在状态A打开LED1,状态B打开LED2,状态C打开LED1和2。我在PyTransitions页面中找不到任何文档。
发布于 2021-10-04 16:47:23
我的问题是,使用yml文件,我如何在状态输出中写入?
状态没有专用的输出槽,但您可以使用transitions在进入或离开状态时触发某些操作。操作可以在回调中完成。这些操作需要在模型中实现。如果你想通过配置来做大多数事情,你可以定制Machine和使用的State类。例如,您可以创建一个自定义发光二极管,并为其分配一个名为led_states的值数组,其中每个值表示一个LEDState状态。该数组应用于名为update_leds的模型的after_state_change回调中的LED
from transitions import Machine, State
class LEDState(State):
ALL_OFF = [False] * 2 # number of LEDs
def __init__(self, name, on_enter=None, on_exit=None,
ignore_invalid_triggers=None, led_states=None):
# call the base class constructor without 'led_states'...
super().__init__(name, on_enter, on_exit, ignore_invalid_triggers)
# ... and assign its value to a custom property
# when 'led_states' is not passed, we assign the default
# setting 'ALL_OFF'
self.led_states = led_states if led_states is not None else self.ALL_OFF
# create a custom machine that uses 'LEDState'
# 'LEDMachine' will pass all parameters in the configuration
# dictionary to the constructor of 'LEDState'.
class LEDMachine(Machine):
state_cls = LEDState
class LEDModel:
def __init__(self, config):
self.machine = LEDMachine(model=self, **config, after_state_change='update_leds')
def update_leds(self):
print(f"---New State {self.state}---")
for idx, led in enumerate(self.machine.get_state(self.state).led_states):
print(f"Set LED {idx} {'ON' if led else 'OFF'}.")
# using a dictionary here instead of YAML
# but the process is the same
config = {
'name': 'LEDModel',
'initial': 'Off',
'states': [
{'name': 'Off'},
{'name': 'A', 'led_states': [True, False]},
{'name': 'B', 'led_states': [False, True]},
{'name': 'C', 'led_states': [True, True]}
]
}
model = LEDModel(config)
model.to_A()
# ---New State A---
# Set LED 0 ON.
# Set LED 1 OFF.
model.to_C()
# ---New State C---
# Set LED 0 ON.
# Set LED 1 ON.这只是实现此目的的一种方法。您也可以只传递一个数组,该数组包含表示所有LED的索引,这些LED应该为ON。当使用before_state_change退出状态时,我们会关闭所有LED
ALL_OFF = []
# ...
self.machine = LEDMachine(model=self, **config, before_state_change='reset_leds', after_state_change='set_lets')
# ...
def reset_leds(self):
for led_idx in range(num_leds):
print(f"Set {led_idx} 'OFF'.")
def set_lets(self):
for led_idx in self.machine.get_state(self.state).led_states:
print(f"Set LED {led_idx} 'ON'.")
# ...
{'name': 'A', 'led_states': [0]},
{'name': 'B', 'led_states': [1]},
{'name': 'C', 'led_states': [0, 1]}https://stackoverflow.com/questions/69409935
复制相似问题