baseimage-tutorial-framework/lib/tfw/networking/server_connector.py

53 lines
1.7 KiB
Python
Raw Normal View History

2019-06-10 13:32:45 +00:00
import logging
2018-01-31 14:50:52 +00:00
from functools import partial
import zmq
from zmq.eventloop.zmqstream import ZMQStream
2019-05-27 12:09:13 +00:00
from .scope import Scope
from .serialization import serialize_tfw_msg, with_deserialize_tfw_msg
LOG = logging.getLogger(__name__)
2018-01-31 14:50:52 +00:00
2019-07-09 07:12:21 +00:00
class ServerDownlinkConnector:
def __init__(self, connect_addr):
2019-05-27 18:02:09 +00:00
self._zmq_sub_socket = zmq.Context.instance().socket(zmq.SUB)
2019-05-21 11:55:28 +00:00
self._zmq_sub_socket.setsockopt(zmq.RCVHWM, 0)
2019-07-08 18:12:12 +00:00
self._zmq_sub_socket.connect(connect_addr)
self._zmq_sub_stream = ZMQStream(self._zmq_sub_socket)
self.subscribe = partial(self._zmq_sub_socket.setsockopt_string, zmq.SUBSCRIBE)
self.unsubscribe = partial(self._zmq_sub_socket.setsockopt_string, zmq.UNSUBSCRIBE)
def register_callback(self, callback):
callback = with_deserialize_tfw_msg(callback)
self._zmq_sub_stream.on_recv(callback)
2018-01-26 14:16:34 +00:00
2019-05-20 09:06:57 +00:00
def close(self):
self._zmq_sub_stream.close()
2019-07-09 07:12:21 +00:00
class ServerUplinkConnector:
def __init__(self, connect_addr):
2019-05-27 18:02:09 +00:00
self._zmq_push_socket = zmq.Context.instance().socket(zmq.PUSH)
2019-05-21 11:55:28 +00:00
self._zmq_push_socket.setsockopt(zmq.SNDHWM, 0)
2019-07-08 18:12:12 +00:00
self._zmq_push_socket.connect(connect_addr)
2019-05-26 16:26:33 +00:00
def send_message(self, message, scope=Scope.ZMQ):
message['scope'] = scope.value
self._zmq_push_socket.send_multipart(serialize_tfw_msg(message))
2019-05-20 09:06:57 +00:00
def close(self):
self._zmq_push_socket.close()
class ServerConnector(ServerDownlinkConnector, ServerUplinkConnector):
def __init__(self, downlink_connect_addr, uplink_connect_addr):
ServerDownlinkConnector.__init__(self, downlink_connect_addr)
ServerUplinkConnector.__init__(self, uplink_connect_addr)
2019-05-27 18:02:09 +00:00
2019-05-20 09:06:57 +00:00
def close(self):
ServerDownlinkConnector.close(self)
ServerUplinkConnector.close(self)