mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-14 03:17:16 +00:00
45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
from tornado.web import Application
|
|
|
|
from tfw.networking.server.controller_responder import ControllerResponder
|
|
from tfw.networking.server.zmq_websocket_handler import ZMQWebSocketProxy
|
|
from tfw.networking.event_handlers.server_connector import ServerUplinkConnector
|
|
from tfw.config.logs import logging
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
class TFWServer:
|
|
def __init__(self, fsm_type):
|
|
self._fsm = fsm_type()
|
|
self.uplink = ServerUplinkConnector()
|
|
self._fsm.subscribe(self.fsm_callback)
|
|
self.application = Application(
|
|
[(r'/ws', ZMQWebSocketProxy, {'make_response': self.make_response,
|
|
'proxy_filter': self.proxy_filter})]
|
|
)
|
|
self.controller_responder = ControllerResponder(self.fsm)
|
|
|
|
@property
|
|
def fsm(self):
|
|
return self._fsm
|
|
|
|
def make_response(self, message):
|
|
return message
|
|
|
|
def proxy_filter(self, message):
|
|
try: return self.fsm.trigger(message['key'], message=message)
|
|
except AttributeError: return False
|
|
|
|
def fsm_callback(self, kwargs_dict):
|
|
self.uplink.send(*self.generate_fsm_update())
|
|
|
|
def generate_fsm_update(self):
|
|
key = 'FSMUpdate'
|
|
response = {'key': key,
|
|
'data': {'current_state': self.fsm.state,
|
|
'valid_transitions':
|
|
[{'trigger': trigger} for trigger in self.fsm.machine.get_triggers(self.fsm.state)]}}
|
|
return key, response
|
|
|
|
def listen(self, port):
|
|
self.application.listen(port)
|