From 646a671ff309a0b1b53d402586eb3aa09f9db2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Sat, 14 Jul 2018 20:45:56 +0200 Subject: [PATCH] Add FSMAwareEventHandler which keeps track of FSM state --- lib/tfw/__init__.py | 2 +- lib/tfw/event_handler_base.py | 32 +++++++++++++++++++++++++------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/lib/tfw/__init__.py b/lib/tfw/__init__.py index 53e80d7..04d934d 100644 --- a/lib/tfw/__init__.py +++ b/lib/tfw/__init__.py @@ -1,7 +1,7 @@ # Copyright (C) 2018 Avatao.com Innovative Learning Kft. # All Rights Reserved. See LICENSE file for details. -from .event_handler_base import EventHandlerBase, TriggeredEventHandler, BroadcastingEventHandler +from .event_handler_base import EventHandlerBase, FSMAwareEventHandler, BroadcastingEventHandler from .fsm_base import FSMBase from .linear_fsm import LinearFSM from .yaml_fsm import YamlFSM diff --git a/lib/tfw/event_handler_base.py b/lib/tfw/event_handler_base.py index 41f6105..f6a094a 100644 --- a/lib/tfw/event_handler_base.py +++ b/lib/tfw/event_handler_base.py @@ -107,20 +107,38 @@ class EventHandlerBase(ABC): pass -class TriggeredEventHandler(EventHandlerBase, ABC): +class FSMAwareEventHandler(EventHandlerBase, ABC): # pylint: disable=abstract-method """ - Abstract base class for EventHandlers which are only triggered in case - TFWServer has successfully triggered an FSM step defined in __init__. + Abstract base class for EventHandlers which automatically + keep track of the state of the TFW FSM. """ - def __init__(self, key, trigger): + def __init__(self, key): super().__init__(key) - self.trigger = trigger + self.subscribe('fsm_update') + self.fsm_state = None def dispatch_handling(self, message): - if message.get('trigger') == self.trigger: + if message['key'] == 'fsm_update': + self._handle_fsm_update(message) + else: return super().dispatch_handling(message) - return None + + def _handle_fsm_update(self, message): + try: + new_state = message['data']['current_state'] + trigger = message['data']['last_trigger'] + if self.fsm_state != new_state: + self.handle_fsm_step(self.fsm_state, new_state, trigger) + self.fsm_state = new_state + except KeyError: + LOG.error('Invalid fsm_update message received!') + + def handle_fsm_step(self, from_state, to_state, trigger): + """ + Called in case the TFW FSM has stepped. + """ + pass class BroadcastingEventHandler(EventHandlerBase, ABC):