import json from messaging import Messaging class EventHandlerBase: def __init__(self, anchor): self.messaging = Messaging() self.anchor = anchor self.messaging.subscribe(self.anchor) self.subscriptions = {self.anchor} self.messaging.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.messaging.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.messaging.send(encoded_anchor, encoded_message) def subscribe(self, anchor): if anchor not in self.subscriptions: self.subscriptions.add(anchor) self.messaging.subscribe(anchor) def unsubscribe(self, anchor): try: self.subscriptions.remove(anchor) self.messaging.unsubscribe(anchor) except KeyError: pass def unsubscribe_all(self): for sub in self.subscriptions: self.messaging.unsubscribe(anchor=sub) self.subscriptions.clear()