baseimage-tutorial-framework/lib/tfw/event_handler_base.py

67 lines
1.9 KiB
Python
Raw Normal View History

2018-02-02 15:49:48 +00:00
from itertools import cycle
from tfw.networking.serialization import deserialize_all
from tfw.networking.event_handlers.server_connector import ServerConnector
2018-02-02 15:49:48 +00:00
def cenator():
yield from [
'**Your time is up**',
'`My time is now`',
'_You can\'t see me_',
'My time is now'
]
class EventHandlerBase:
def __init__(self, anchor):
2018-01-26 14:16:34 +00:00
self.server_connector = ServerConnector()
self.anchor = anchor
2018-01-25 16:04:34 +00:00
self.subscriptions = set()
self.subscribe(self.anchor)
self.subscribe('reset')
2018-01-26 14:16:34 +00:00
self.server_connector.register_callback(self.event_handler_callback)
2018-02-02 15:49:48 +00:00
self.cenerator = cycle(cenator())
def event_handler_callback(self, msg_parts):
2018-02-02 16:30:26 +00:00
anchor, message = deserialize_all(*msg_parts)
2018-02-02 15:49:48 +00:00
from .message_sender import MessageSender
ms = MessageSender()
ms.send('JOHN CENA', next(self.cenerator))
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
2018-02-13 14:38:46 +00:00
def cleanup(self):
pass
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)
2018-01-26 14:16:34 +00:00
self.server_connector.subscribe(anchor)
def unsubscribe(self, anchor):
try:
self.subscriptions.remove(anchor)
2018-01-26 14:16:34 +00:00
self.server_connector.unsubscribe(anchor)
except KeyError:
pass
def unsubscribe_all(self):
for sub in self.subscriptions:
2018-01-26 14:16:34 +00:00
self.server_connector.unsubscribe(anchor=sub)
self.subscriptions.clear()