2018-02-06 13:19:41 +00:00
|
|
|
from tfw.networking.serialization import deserialize_all
|
|
|
|
from tfw.networking.event_handlers.server_connector import ServerConnector
|
2018-01-25 14:24:42 +00:00
|
|
|
|
2017-11-27 17:20:09 +00:00
|
|
|
|
2017-12-02 14:19:05 +00:00
|
|
|
class EventHandlerBase:
|
2018-01-25 14:24:42 +00:00
|
|
|
def __init__(self, anchor):
|
2018-01-26 14:16:34 +00:00
|
|
|
self.server_connector = ServerConnector()
|
2017-11-27 17:20:09 +00:00
|
|
|
self.anchor = anchor
|
2018-01-25 16:04:34 +00:00
|
|
|
self.subscriptions = set()
|
|
|
|
self.subscribe(self.anchor)
|
|
|
|
self.subscribe('reset')
|
2018-01-26 14:16:34 +00:00
|
|
|
self.server_connector.register_callback(self.event_handler_callback)
|
2018-01-17 13:26:16 +00:00
|
|
|
|
|
|
|
def event_handler_callback(self, msg_parts):
|
2018-02-02 16:30:26 +00:00
|
|
|
anchor, message = deserialize_all(*msg_parts)
|
2018-02-02 17:39:06 +00:00
|
|
|
response = self.handle_event(anchor, message) if anchor != 'reset' else self.handle_reset(message)
|
2018-01-17 13:26:16 +00:00
|
|
|
if response is None: return
|
2018-02-02 17:39:06 +00:00
|
|
|
self.server_connector.send(anchor, response)
|
2018-01-17 13:26:16 +00:00
|
|
|
|
|
|
|
def handle_event(self, anchor, data_json):
|
|
|
|
raise NotImplementedError
|
2017-11-27 17:20:09 +00:00
|
|
|
|
2018-01-17 15:33:34 +00:00
|
|
|
def handle_reset(self, data_json):
|
|
|
|
return None
|
|
|
|
|
2017-11-27 17:20:54 +00:00
|
|
|
def message_other(self, anchor, data):
|
|
|
|
message = {
|
|
|
|
'anchor': anchor,
|
|
|
|
'data': data
|
|
|
|
}
|
2018-02-02 17:39:06 +00:00
|
|
|
self.server_connector.send(anchor, message)
|
2017-11-27 17:20:54 +00:00
|
|
|
|
2017-11-27 17:34:26 +00:00
|
|
|
def subscribe(self, anchor):
|
|
|
|
if anchor not in self.subscriptions:
|
|
|
|
self.subscriptions.add(anchor)
|
2018-01-26 14:16:34 +00:00
|
|
|
self.server_connector.subscribe(anchor)
|
2017-11-27 17:34:26 +00:00
|
|
|
|
|
|
|
def unsubscribe(self, anchor):
|
|
|
|
try:
|
|
|
|
self.subscriptions.remove(anchor)
|
2018-01-26 14:16:34 +00:00
|
|
|
self.server_connector.unsubscribe(anchor)
|
2017-11-27 17:34:26 +00:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def unsubscribe_all(self):
|
|
|
|
for sub in self.subscriptions:
|
2018-01-26 14:16:34 +00:00
|
|
|
self.server_connector.unsubscribe(anchor=sub)
|
2017-11-27 17:34:26 +00:00
|
|
|
self.subscriptions.clear()
|