Commits

Anonymous committed d6c604a

basic implementation

Comments (0)

Files changed (1)

araldo_websocket/endpoints/websocket_endpoint.py

+""" araldo Endpoint for communication with WebSocket (client side)
+"""
+import gevent
+from gevent import monkey
+monkey.patch_all()
+from websocket import create_connection, enableTrace
+from araldo.endpoints import InBoundBase, OutBoundBase
+
+
+class InBound(InBoundBase):  # pylint: disable-msg=R0904
+    """ InBound endpoint implementation for connecting to a WebSocket server
+    """
+    def __init__(self, **kwargs):
+        """ Creates an InBound instance for relaying messages received
+            from a WebSocket server
+            :param config: configuration object
+            :param gevent_queue: queue for forwarding incoming messages
+        """
+        config = kwargs["config"]
+        websocket_url = config["websocket_url"]
+        do_trace = config["trace"]
+        enableTrace(do_trace)
+        self._websocket = create_connection(websocket_url)
+        InBoundBase.__init__(self, **kwargs)
+
+    @staticmethod
+    def plugin_id():
+        """ :return: ID of plugin
+        """
+        return "inbound-websocketclient"
+
+    def _run(self):  # pylint: disable-msg=E0202
+        """ Enter infinite gevent loop to receive messages from
+            WebSocket server and push it to gevent queue
+        """
+        while True:
+            try:
+                message_str = self._websocket.recv()
+                message = self._marshalling.to_internal_format(message_str)
+                self._logger.debug(
+                    "unmarshalled: %s",
+                    message)
+                self.gevent_queue.put((self.name(), message))
+            except Exception as error:
+                self._logger.debug(
+                    "Unable to unmarshal message; discarding (%s)",
+                    error)
+            gevent.sleep(0)
+
+    def check(self):
+        """ implementation of abstract method
+        """
+        raise NotImplementedError()
+
+
+class OutBound(OutBoundBase):
+    """ Outound implementation for sending messages to WebSocket server
+    """
+    def __init__(self, **kwargs):
+        config = kwargs["config"]
+        do_trace = config["trace"]
+        enableTrace(do_trace)
+        websocket_url = config["websocket_url"]
+        self._websocket = create_connection(websocket_url)
+        OutBoundBase.__init__(self, **kwargs)
+
+    @staticmethod
+    def plugin_id():
+        """ :return: ID of plugin
+        """
+        return "outbound-websocketclient"
+
+    def send(self, message):
+        message_str = self._marshalling.to_external_format(message)
+        self._logger.debug("message_str: %s", message_str)
+        # TODO: send to server