baseimage-tutorial-framework/src/event_handlers/event_handler_base.py

51 lines
1.6 KiB
Python
Raw Normal View History

import json
class EventHandlerBase:
def __init__(self, messaging, 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()