2018-06-29 20:03:19 +00:00
|
|
|
# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
|
|
|
|
# All Rights Reserved. See LICENSE file for details.
|
|
|
|
|
2018-07-12 13:20:35 +00:00
|
|
|
from tfw import EventHandlerBase
|
2018-06-29 20:03:19 +00:00
|
|
|
from tfw.config.logs import logging
|
|
|
|
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2018-07-12 13:20:35 +00:00
|
|
|
class FSMManagingEventHandler(EventHandlerBase):
|
2018-06-29 20:03:19 +00:00
|
|
|
def __init__(self, key, fsm_type):
|
|
|
|
super().__init__(key)
|
|
|
|
self.fsm = fsm_type()
|
|
|
|
self._fsm_updater = FSMUpdater(self.fsm)
|
|
|
|
|
|
|
|
self.command_handlers = {
|
|
|
|
'trigger': self.handle_trigger,
|
|
|
|
'update': self.handle_update
|
|
|
|
}
|
|
|
|
|
|
|
|
def handle_event(self, message):
|
|
|
|
try:
|
|
|
|
data = message['data']
|
|
|
|
message['data'] = self.command_handlers[data['command']](data)
|
2018-07-12 13:20:35 +00:00
|
|
|
self.server_connector.broadcast(self._fsm_updater.generate_fsm_update())
|
2018-06-29 20:03:19 +00:00
|
|
|
return message
|
|
|
|
except KeyError:
|
|
|
|
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)
|
|
|
|
|
|
|
|
def handle_trigger(self, data):
|
2018-07-14 18:45:26 +00:00
|
|
|
trigger = data['value']
|
|
|
|
self.fsm.step(trigger)
|
2018-07-12 13:20:35 +00:00
|
|
|
return data
|
2018-06-29 20:03:19 +00:00
|
|
|
|
|
|
|
def handle_update(self, data):
|
2018-07-12 13:20:35 +00:00
|
|
|
return data
|
2018-06-29 20:03:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
class FSMUpdater:
|
|
|
|
def __init__(self, fsm):
|
|
|
|
self.fsm = fsm
|
|
|
|
|
2018-07-12 13:20:35 +00:00
|
|
|
def generate_fsm_update(self):
|
|
|
|
return {
|
|
|
|
'key': 'fsm_update',
|
|
|
|
'data': self.get_fsm_state_and_transitions()
|
|
|
|
}
|
|
|
|
|
2018-06-29 20:03:19 +00:00
|
|
|
def get_fsm_state_and_transitions(self):
|
|
|
|
state = self.fsm.state
|
|
|
|
valid_transitions = [
|
|
|
|
{'trigger': trigger}
|
2018-07-04 13:48:16 +00:00
|
|
|
for trigger in self.fsm.get_triggers(self.fsm.state)
|
2018-06-29 20:03:19 +00:00
|
|
|
]
|
2018-07-14 18:45:26 +00:00
|
|
|
last_trigger = self.fsm.trigger_history[-1] if self.fsm.trigger_history else None
|
2018-06-29 20:03:19 +00:00
|
|
|
return {
|
|
|
|
'current_state': state,
|
2018-07-14 18:45:26 +00:00
|
|
|
'valid_transitions': valid_transitions,
|
|
|
|
'last_trigger': last_trigger
|
2018-06-29 20:03:19 +00:00
|
|
|
}
|