baseimage-tutorial-framework/lib/tfw/event_handler_base.py
2018-02-02 17:30:26 +01:00

52 lines
1.6 KiB
Python

import json
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)
data_json = json.loads(message)
response = self.handle_event(anchor, data_json) if anchor != 'reset' else self.handle_reset(data_json)
if response is None: return
self.server_connector.send(anchor, json.dumps(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, json.dumps(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()