2019-06-10 13:32:45 +00:00
|
|
|
import logging
|
|
|
|
|
2019-08-07 07:46:58 +00:00
|
|
|
from tfw.internals.crypto import KeyManager, sign_message
|
2019-08-23 13:27:03 +00:00
|
|
|
from tfw.internals.networking import Scope, Intent
|
2019-07-24 13:17:16 +00:00
|
|
|
|
|
|
|
from .fsm_updater import FSMUpdater
|
2018-06-29 20:03:19 +00:00
|
|
|
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2019-07-24 13:17:16 +00:00
|
|
|
class FSMHandler:
|
2019-08-08 13:05:37 +00:00
|
|
|
keys = ['fsm']
|
2019-08-30 12:45:53 +00:00
|
|
|
type_id = 'ControlEventHandler'
|
2019-08-08 13:05:37 +00:00
|
|
|
|
2019-08-27 11:15:59 +00:00
|
|
|
def __init__(self, *, fsm_type):
|
2019-08-23 13:27:03 +00:00
|
|
|
self.connector = None
|
2018-06-29 20:03:19 +00:00
|
|
|
self.fsm = fsm_type()
|
|
|
|
self._fsm_updater = FSMUpdater(self.fsm)
|
2018-07-16 12:31:52 +00:00
|
|
|
self.auth_key = KeyManager().auth_key
|
2018-06-29 20:03:19 +00:00
|
|
|
|
|
|
|
self.command_handlers = {
|
2019-08-28 14:34:55 +00:00
|
|
|
'fsm.trigger': self.handle_trigger,
|
2019-08-28 14:31:43 +00:00
|
|
|
'fsm.update' : self.handle_update
|
2018-06-29 20:03:19 +00:00
|
|
|
}
|
|
|
|
|
2019-08-26 09:10:39 +00:00
|
|
|
def handle_event(self, message, _):
|
2018-06-29 20:03:19 +00:00
|
|
|
try:
|
2019-08-07 07:46:58 +00:00
|
|
|
message = self.command_handlers[message['key']](message)
|
2018-07-23 15:16:37 +00:00
|
|
|
if message:
|
2018-07-24 15:16:57 +00:00
|
|
|
fsm_update_message = self._fsm_updater.fsm_update
|
2018-07-23 15:16:37 +00:00
|
|
|
sign_message(self.auth_key, fsm_update_message)
|
2019-08-26 09:10:39 +00:00
|
|
|
self.connector.send_message(fsm_update_message, Scope.BROADCAST, Intent.EVENT)
|
2018-06-29 20:03:19 +00:00
|
|
|
except KeyError:
|
|
|
|
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)
|
|
|
|
|
2019-08-28 14:31:43 +00:00
|
|
|
def handle_trigger(self, message): # pylint: disable=inconsistent-return-statements
|
2019-08-28 14:46:05 +00:00
|
|
|
if self.fsm.step(message['transition']):
|
2019-08-08 06:27:41 +00:00
|
|
|
return message
|
2018-06-29 20:03:19 +00:00
|
|
|
|
2019-08-23 13:27:03 +00:00
|
|
|
def handle_update(self, message):
|
2018-07-16 09:17:06 +00:00
|
|
|
# pylint: disable=no-self-use
|
2018-07-23 15:16:37 +00:00
|
|
|
return message
|