mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-09 01:47:16 +00:00
49 lines
1.6 KiB
Python
49 lines
1.6 KiB
Python
from tfw.networking.serialization import deserialize_all
|
|
from tfw.networking.event_handlers.server_connector import ServerConnector
|
|
|
|
|
|
class EventHandlerBase:
|
|
def __init__(self, anchor):
|
|
self.server_connector = ServerConnector()
|
|
self.anchor = anchor
|
|
self.subscriptions = set()
|
|
self.subscribe(self.anchor)
|
|
self.subscribe('reset')
|
|
self.server_connector.register_callback(self.event_handler_callback)
|
|
|
|
def event_handler_callback(self, msg_parts):
|
|
anchor, message = deserialize_all(*msg_parts)
|
|
response = self.handle_event(anchor, message) if anchor != 'reset' else self.handle_reset(message)
|
|
if response is None: return
|
|
self.server_connector.send(anchor, response)
|
|
|
|
def handle_event(self, anchor, data_json):
|
|
raise NotImplementedError
|
|
|
|
def handle_reset(self, data_json):
|
|
return None
|
|
|
|
def message_other(self, anchor, data):
|
|
message = {
|
|
'anchor': anchor,
|
|
'data': data
|
|
}
|
|
self.server_connector.send(anchor, message)
|
|
|
|
def subscribe(self, anchor):
|
|
if anchor not in self.subscriptions:
|
|
self.subscriptions.add(anchor)
|
|
self.server_connector.subscribe(anchor)
|
|
|
|
def unsubscribe(self, anchor):
|
|
try:
|
|
self.subscriptions.remove(anchor)
|
|
self.server_connector.unsubscribe(anchor)
|
|
except KeyError:
|
|
pass
|
|
|
|
def unsubscribe_all(self):
|
|
for sub in self.subscriptions:
|
|
self.server_connector.unsubscribe(anchor=sub)
|
|
self.subscriptions.clear()
|