baseimage-tutorial-framework/lib/tfw/event_handler_base.py
2018-01-31 15:56:39 +01:00

54 lines
1.7 KiB
Python

import json
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 = msg_parts
data_json = json.loads(message)
response = self.handle_event(anchor, data_json) if anchor != b'reset' else self.handle_reset(data_json)
if response is None: return
encoded_response = json.dumps(response).encode('utf-8')
self.server_connector.send(anchor, encoded_response)
def handle_event(self, anchor, data_json):
raise NotImplementedError
def handle_reset(self, data_json):
return None
def message_other(self, anchor, data):
encoded_anchor = anchor.encode('utf-8')
message = {
'anchor': anchor,
'data': data
}
encoded_message = json.dumps(message).encode('utf-8')
self.server_connector.send(encoded_anchor, encoded_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()