baseimage-tutorial-framework/lib/tfw/event_handler_base.py
2018-02-02 18:39:06 +01:00

49 lines
1.5 KiB
Python

from .networking.serialization import deserialize_all
from .networking.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()