2017-11-27 17:36:02 +00:00
|
|
|
import json
|
|
|
|
|
2017-12-02 14:19:05 +00:00
|
|
|
from event_handler_base import EventHandlerBase
|
2017-11-27 17:36:02 +00:00
|
|
|
|
|
|
|
|
2017-12-02 14:19:05 +00:00
|
|
|
class StatefulEventHandler(EventHandlerBase):
|
2017-12-03 01:13:19 +00:00
|
|
|
def __init__(self, anchor, event_handler_function, zmq_context=None):
|
|
|
|
super().__init__(anchor, zmq_context)
|
|
|
|
self.event_handler_function = event_handler_function
|
2017-11-27 17:36:02 +00:00
|
|
|
self.generator = None
|
|
|
|
self.subscribe('reset')
|
|
|
|
|
2017-12-05 16:51:34 +00:00
|
|
|
def event_handler_callback(msg_parts):
|
2017-11-27 17:36:02 +00:00
|
|
|
anchor, message = msg_parts
|
|
|
|
if anchor == b'reset':
|
2017-12-05 17:35:22 +00:00
|
|
|
self.reset()
|
2017-11-27 17:36:02 +00:00
|
|
|
return
|
|
|
|
data_json = json.loads(message)
|
|
|
|
if self.generator is None:
|
2017-12-05 16:51:34 +00:00
|
|
|
self.generator = self.event_handler_function(data_json, self)
|
2017-12-05 17:36:26 +00:00
|
|
|
try:
|
|
|
|
response_anchor, response_data = next(self.generator)
|
|
|
|
except StopIteration:
|
|
|
|
self.reset()
|
|
|
|
return
|
2017-12-05 17:37:20 +00:00
|
|
|
self.subscribe(response_anchor)
|
2017-11-27 17:36:02 +00:00
|
|
|
response_data = json.dumps({
|
|
|
|
'anchor': response_anchor,
|
|
|
|
'data': response_data,
|
|
|
|
})
|
|
|
|
response = [r.encode('utf-8') for r in (response_anchor, response_data)]
|
|
|
|
self.zmq_push_socket.send_multipart(response)
|
|
|
|
|
2017-12-05 16:51:34 +00:00
|
|
|
self.zmq_sub_stream.on_recv(event_handler_callback)
|
2017-12-05 17:35:22 +00:00
|
|
|
|
|
|
|
def unsubscribe_all(self):
|
|
|
|
super().unsubscribe_all()
|
|
|
|
self.subscribe('reset')
|
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
self.generator = None
|
|
|
|
self.unsubscribe_all()
|
|
|
|
self.subscribe(self.anchor)
|