2018-02-09 16:27:51 +00:00
|
|
|
from typing import List
|
|
|
|
|
2017-12-06 00:29:09 +00:00
|
|
|
from transitions import Machine
|
|
|
|
|
|
|
|
|
|
|
|
class FSMBase:
|
2018-01-31 14:10:05 +00:00
|
|
|
states, transitions = [], []
|
2017-12-06 00:29:09 +00:00
|
|
|
|
2018-02-09 16:27:51 +00:00
|
|
|
def __init__(self, initial: str = None, accepted_states: List[str] = None):
|
2018-02-23 11:07:30 +00:00
|
|
|
self.callbacks = []
|
2018-02-09 16:27:51 +00:00
|
|
|
self.accepted_states = accepted_states or [self.states[-1]]
|
2017-12-06 00:29:09 +00:00
|
|
|
self.machine = Machine(model=self,
|
|
|
|
states=self.states,
|
|
|
|
transitions=self.transitions,
|
|
|
|
initial=initial or self.states[0],
|
|
|
|
send_event=True,
|
|
|
|
ignore_invalid_triggers=True,
|
2018-02-23 11:07:30 +00:00
|
|
|
after_state_change='execute_callbacks')
|
2017-12-06 00:29:09 +00:00
|
|
|
|
2018-02-23 11:07:30 +00:00
|
|
|
def execute_callbacks(self, event_data):
|
|
|
|
for callback in self.callbacks:
|
|
|
|
callback(event_data.kwargs)
|
2018-01-29 16:24:17 +00:00
|
|
|
|
2018-02-23 11:07:30 +00:00
|
|
|
def subscribe(self, callback):
|
|
|
|
self.callbacks.append(callback)
|
2018-02-07 09:13:06 +00:00
|
|
|
|
2018-02-23 11:07:30 +00:00
|
|
|
def unsubscribe(self, callback):
|
|
|
|
self.callbacks.remove(callback)
|
2018-02-09 16:27:51 +00:00
|
|
|
|
|
|
|
def is_solved(self):
|
|
|
|
return self.state in self.accepted_states
|