Example #1
0
    def __init__(self, url, key):
        print("Connecting to " + url)
        WebSocketClient.__init__(self, url)

        self._sending_lock = threading.RLock()
        self._send_next_bin = None
        self._key = key
Example #2
0
    def __init__(self, url, supported_protocols):
        WebSocketClient.__init__(self, url)

        self.supported_protocols = supported_protocols
        self.logger = logging.getLogger(__name__)
        self.handlers = {}
        self._weakref = weakref.ref(self)
Example #3
0
 def __init__(self, url, debug=False):
     WebSocketClient.__init__(self, url)
     EventEmitter.__init__(self)
     self.debug = debug
     self._session = None
     self._uniq_id = 0
     self._callbacks = {}
Example #4
0
 def __init__(self,
              uri,
              decoder_pipeline,
              post_processor,
              full_post_processor=None):
     self.uri = uri
     self.decoder_pipeline = decoder_pipeline
     self.post_processor = post_processor
     self.full_post_processor = full_post_processor
     WebSocketClient.__init__(self, url=uri, heartbeat_freq=10)
     self.pipeline_initialized = False
     self.partial_transcript = ""
     if USE_NNET2:
         self.decoder_pipeline.set_result_handler(self._on_result)
         self.decoder_pipeline.set_full_result_handler(self._on_full_result)
         self.decoder_pipeline.set_error_handler(self._on_error)
     else:
         self.decoder_pipeline.set_word_handler(self._on_word)
         self.decoder_pipeline.set_error_handler(self._on_error)
     self.decoder_pipeline.set_eos_handler(self._on_eos)
     self.state = self.STATE_CREATED
     self.last_decoder_message = time.time()
     self.request_id = "<undefined>"
     self.timeout_decoder = 5
     self.num_segments = 0
     self.last_partial_result = ""
     self.post_processor_lock = threading.Lock()
     self.processing_condition = threading.Condition()
     self.num_processing_threads = 0
Example #5
0
    def __init__(self, url, defaultCallback):
        self.connected = False

        # check ws4py version
        env = pkg_resources.Environment()
        v = env['ws4py'][0].version.split(".")
        if (int(v[0]) * 100 + int(v[1]) * 10 + int(v[2])) < 35:
            raise RuntimeError("please use ws4py version 0.3.5 or higher")

        self.conUUid = uuid.uuid1()  # make uuid for connection

        self.conUrl = (
            url +
            "/websocket/data/" +
            str(self.conUUid.clock_seq_hi_variant) +
            "/" +
            str(self.conUUid) +
            "/websocket"
        )
        self.defaultCallback = defaultCallback
        self.functionCallbacks = {}
        logging.info("initialized " + self.conUrl)
        try:
            WebSocketClient.__init__(self, self.conUrl)
            self.connect()
            self.connected = True
            logging.info("connected: " + str(self.connected))
            threading.Thread(target=self.run_forever).start()
        except KeyboardInterrupt:
            self.disconnect()
            logging.error("KeyboardInterrupt")
        except Exception as e:
            self.disconnect()
            raise e
Example #6
0
 def __init__(self, uri, decoder_pipeline, post_processor, full_post_processor=None):
     self.uri = uri
     self.decoder_pipeline = decoder_pipeline
     self.post_processor = post_processor
     self.full_post_processor = full_post_processor
     WebSocketClient.__init__(self, url=uri, heartbeat_freq=10)
     self.pipeline_initialized = False
     self.partial_transcript = ""
     if USE_NNET2:
         self.decoder_pipeline.set_result_handler(self._on_result)
         self.decoder_pipeline.set_full_result_handler(self._on_full_result)
         self.decoder_pipeline.set_error_handler(self._on_error)
     else:
         self.decoder_pipeline.set_word_handler(self._on_word)
         self.decoder_pipeline.set_error_handler(self._on_error)
     self.decoder_pipeline.set_eos_handler(self._on_eos)
     self.state = self.STATE_CREATED
     self.last_decoder_message = time.time()
     self.request_id = "<undefined>"
     self.timeout_decoder = 5
     self.num_segments = 0
     self.last_partial_result = ""
     self.post_processor_lock = threading.Lock()
     self.processing_condition = threading.Condition()
     self.num_processing_threads = 0
Example #7
0
	def __init__(self,token,most_recent=0,most_recent_callback=None):
		self.mostRecent = most_recent
		self.mostRecentUpdated = most_recent_callback or self.mostRecentUpdated
		self.lastPing = time.time()
		self.client = Client(token)
		self.devices = {}
		WebSocketClient.__init__(self,STREAM_BASE_URL.format(token))
Example #8
0
    def __init__(self, url, print_raw):
        WebSocketClient.__init__(self, url)
        self.print_raw = print_raw

        # We keep track of methods and subs that have been sent from the
        # client so that we only return to the prompt or quit the app
        # once we get back all the results from the server.
        #
        # `id`
        #
        #   The operation id, informed by the client and returned by the
        #   server to make sure both are talking about the same thing.
        #
        # `result_acked`
        #
        #   Flag to make sure we were answered.
        #
        # `data_acked`
        #
        #   Flag to make sure we received the correct data from the
        #   message we were waiting for.
        self.pending_condition = threading.Condition()
        self.pending = {}
        self.brick = init_nxt()
        self.mrt, self.mlft, self.bm = init_drive_motors(self.brick)
        self.us = nxt.get_sensor(self.brick, nxt.PORT_4)
Example #9
0
    def __init__(self, url, config, statesworker):
        # init WS
        WebSocketClient.__init__(self, url)

        # variables
        self.__config = config
        self.__connected = False
        self.__run = True

        # recv sync
        self.recv_event_e.set()

        # actions map
        self.__actions = {
            codes.APP_NOT_EXIST: self.__act_retry_hs,
            codes.AGENT_UPDATE: self.__act_update,
            codes.RECIPE_DATA: self.__act_recipe,
            codes.WAIT_DATA: self.__act_wait,
        }

        # init
        self.__error_dir = self.__init_dir()
        self.__error_proc = self.__mount_proc()
        self.__update_ud()
        self.__config['init'] = self.__get_id()

        # states worker
        self.__states_worker = statesworker
Example #10
0
 def __init__(self,
              uri,
              decoder_pipeline,
              post_processor,
              full_post_processor=None):
     self.uri = uri
     self.decoder_pipeline = decoder_pipeline
     self.post_processor = post_processor
     self.full_post_processor = full_post_processor
     WebSocketClient.__init__(self, url=uri, heartbeat_freq=10)
     self.pipeline_initialized = False
     self.partial_transcript = ""
     if USE_NNET2:  # for DecoderPipeline2
         self.decoder_pipeline.set_result_handler(self._on_result)
         self.decoder_pipeline.set_full_result_handler(self._on_full_result)
         self.decoder_pipeline.set_error_handler(self._on_error)
     else:
         self.decoder_pipeline.set_word_handler(self._on_word)
         self.decoder_pipeline.set_error_handler(self._on_error)
     self.decoder_pipeline.set_eos_handler(self._on_eos)
     self.state = self.STATE_CREATED
     self.last_decoder_message = time.time()
     self.request_id = "<undefined>"
     self.timeout_decoder = 5  # not used?
     self.num_segments = 0
     self.last_partial_result = ""
     self.post_processor_lock = tornado.locks.Lock()  # lock for coroutines
     self.processing_condition = tornado.locks.Condition(
     )  # condition allows one or more coroutines to wait until notified
     self.num_processing_threads = 0
Example #11
0
 def __init__(self, token, most_recent=0, most_recent_callback=None):
     self.mostRecent = most_recent
     self.mostRecentUpdated = most_recent_callback or self.mostRecentUpdated
     self.lastPing = time.time()
     self.client = Client(token)
     self.devices = {}
     WebSocketClient.__init__(self, STREAM_BASE_URL.format(token))
Example #12
0
    def __init__(self, url, config, statesworker):
        # init WS
        WebSocketClient.__init__(self, url)

        # variables
        self.__config = config
        self.__connected = False
        self.__run = True

        # recv sync
        self.recv_event_e.set()

        # actions map
        self.__actions = {
            codes.APP_NOT_EXIST : self.__act_retry_hs,
            codes.AGENT_UPDATE  : self.__act_update,
            codes.RECIPE_DATA   : self.__act_recipe,
            codes.WAIT_DATA     : self.__act_wait,
        }

        # init
        self.__error_dir = self.__init_dir()
        self.__error_proc = self.__mount_proc()
        self.__update_ud()
        self.__config['init'] = self.__get_id()

        # states worker
        self.__states_worker = statesworker
Example #13
0
    def __init__(self, host=_my_localhost, channel=None):
        """initialize a 'FireflyClient' object and build websocket.

        Parameters
        ----------
        host : str
            Firefly host.
        channel : str
            WebSocket channel id.
        """

        if host.startswith('http://'):
            host = host[7:]

        self.this_host = host

        url = 'ws://%s/firefly/sticky/firefly/events' % host  # web socket url
        if channel:
            url += '?channelID=%s' % channel
        WebSocketClient.__init__(self, url)

        self.url_root = 'http://' + host + self._fftools_cmd
        self.url_bw = 'http://' + self.this_host + '/firefly/firefly.html;wsch='

        self.listeners = {}
        self.channel = channel
        self.session = requests.Session()
        # print 'websocket url:%s' % url
        self.connect()
Example #14
0
    def connectDDP(self, timeout=3, isReconnect=False):
        if isReconnect:
            self._dbPrint("Attempting reconnect with timeout: %i seconds. . ." % timeout)
            self.close_connection()  # try to free up some OS resources
            time.sleep(timeout)
            WebSocketClient.__init__(self, self.urlArg)
        else:
            self._dbPrint("Starting DDP connection. . .")

        try:
            self._attemptConnection()
        # except (DDPError, ConnectionRefusedError) as e:
        except Exception as e:
            self._dbPrint("ddpClient._attemptConnection() raised an exception:")
            print(e)
            timeoutExponent = 1.2

            if not self.attemptReconnect:
                raise e
            self.connectDDP(isReconnect=True, timeout=timeout * timeoutExponent)
        else:
            if isReconnect:
                self._dbPrint("Reconnect successful!")
                [cb() for cb in self.reconnectCallbacks]
                self.run_forever()
            else:
                self._dbPrint("DDP connection established!")
Example #15
0
    def inner(self):
        while True:
            self.logger.info("Connecting ...")
            try:
                self.setup()
                self.connect()
                func(self)
            except KeyboardInterrupt:
                self.close()
                return
            except WebSocketException as e:
                self.logger.exception("WebSocketException")
            except ConnectionError as e:
                self.logger.error("Could not connect to server!")
            except Exception:
                self.logger.exception("Exception")
            finally:
                self.terminate_outgoing_thread()
                self.logger.info("Trying to reconnect in %d seconds (%d attempt) ..." % (self.reconnect_delay, self.reconnect_attempt))
                time.sleep(self.reconnect_delay)

                if self.reconnect_delay < 120:
                    self.reconnect_delay *= 2

                self.reconnect_attempt += 1
                WebSocketClient.__init__(self, self.url)
Example #16
0
    def __init__(self, url, debugPrint=False, printDDP=False, raiseDDPErrors=False, printDDPErrors=True, attemptReconnect=True):
        # Call the ws init functions
        self.urlArg = url
        WebSocketClient.__init__(self, url)

        self._dbPrint = Printer(debugPrint=debugPrint)
        self._printDDPError = Printer(debugPrint=printDDPErrors)
        self._printDDP = Printer(debugPrint=printDDP)

        # Record the outstanding method calls to link wrt requests
        self.requestsToTrack = []
        self.requestReplies = {}
        self.subNameToID = {}

        # Place to collect collections
        self.collections = CollectionCollection()

        # Store the flags for what to do in various scenarios
        self.debugPrint = debugPrint
        self.raiseDDPErrors = raiseDDPErrors
        self.printDDP = printDDP
        self.printDDPErrors = printDDPErrors
        self.attemptReconnect = attemptReconnect

        self.closeCallbacks = []
        self.reconnectCallbacks = []

        # Set the connected flag to False
        self.DDP_Connected = False

        # Flag to see if we requested a close connection
        self.closeRequested = False
Example #17
0
    def __init__(self, host=_my_localhost, channel=None):
        """initialize a 'FireflyClient' object and build websocket.

        Parameters
        ----------
        host : str
            Firefly host.
        channel : str
            WebSocket channel id.
        """

        if host.startswith('http://'):
            host = host[7:]

        self.this_host = host

        url = 'ws://%s/firefly/sticky/firefly/events' % host  # web socket url
        if channel:
            url += '?channelID=%s' % channel
        WebSocketClient.__init__(self, url)

        self.url_root = 'http://' + host + self._fftools_cmd
        self.url_bw = 'http://' + self.this_host + '/firefly/firefly.html;wsch='

        self.listeners = {}
        self.channel = channel
        self.session = requests.Session()
        # print 'websocket url:%s' % url
        self.connect()
Example #18
0
    def __init__(self, url, defaultCallback):
        self.connected = False

        # check ws4py version
        env = pkg_resources.Environment()
        v = env['ws4py'][0].version.split(".")
        if (int(v[0]) * 100 + int(v[1]) * 10 + int(v[2])) < 35:
            raise RuntimeError("please use ws4py version 0.3.5 or higher")

        self.conUUid = uuid.uuid1()  # make uuid for connection

        self.conUrl = (url + "/websocket/data/" +
                       str(self.conUUid.clock_seq_hi_variant) + "/" +
                       str(self.conUUid) + "/websocket")
        self.defaultCallback = defaultCallback
        self.functionCallbacks = {}
        logging.info("initialized " + self.conUrl)
        try:
            WebSocketClient.__init__(self, self.conUrl)
            self.connect()
            self.connected = True
            logging.info("connected: " + str(self.connected))
            threading.Thread(target=self.run_forever).start()
        except KeyboardInterrupt:
            self.disconnect()
            logging.error("KeyboardInterrupt")
        except Exception as e:
            self.disconnect()
            raise e
Example #19
0
 def __init__(self, url, debug=False):
     self.debug = debug
     # by default socket connections don't timeout. this causes issues
     # where reconnects can get stuck
     # TODO: make this configurable?
     socket.setdefaulttimeout(10)
     WebSocketClient.__init__(self, url)
     EventEmitter.__init__(self)
Example #20
0
 def __init__(self,
              info,
              serveraddress='wss://broadcastlv.chat.bilibili.com/sub'):
     self.serveraddress = serveraddress
     WebSocketClient.__init__(self, serveraddress)
     DanmuWebSocket.event = event
     DanmuWebSocket.headerLength = 16
     self.Info = info
Example #21
0
    def __init__(self, headers={}):
        if not _quiet:
            print("Connecting to " + _url)
        WebSocketClient.__init__(self, _url, headers=headers)

        self._ready_notify = threading.Condition()
        self._ready = False
        self._sending_lock = threading.RLock()
Example #22
0
 def reconnect(self):
     WebSocketClient.__init__(self, self.urlstring)
     self._connected = False
     self.connect()
     self.client_thread = threading.Thread(target=self.run_forever)
     self.client_thread.start()
     while not self._connected:
         time.sleep(0.1)
Example #23
0
    def __init__(self, webSocketDebuggerUrl, onload=None):
        WebSocketClient.__init__(self, webSocketDebuggerUrl)

        self.onload = onload
        self.pendingCallbacks = {}
        self.freeIds = []

        self.connect()
Example #24
0
 def __init__(self, url, account, password, character, client_name="Python FChat Library"):
     WebSocketClient.__init__(self, url)
     self.account = account
     self.password = password
     self.character = character
     self.client_name = client_name
     self.reconnect_delay = 1
     self.reconnect_attempt = 0
Example #25
0
 def reconnect(self):
     WebSocketClient.__init__(self, self.urlstring)
     self._connected = False
     self.connect()
     self.client_thread = threading.Thread(target=self.run_forever)
     self.client_thread.start()
     while not self._connected:
         time.sleep(0.1)
Example #26
0
 def __init__(self):
     ws_url = 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize'
     self.listening = False
     try:
         WebSocketClient.__init__(self, ws_url,
         headers=[("X-Watson-Authorization-Token",auth_token)])
         self.connect()
     except: print "Failed to open WebSocket."
 def __init__(self, url, debug=False):
     self.debug = debug
     # by default socket connections don't timeout. this causes issues
     # where reconnects can get stuck
     # TODO: make this configurable?
     socket.setdefaulttimeout(10)
     WebSocketClient.__init__(self, url)
     EventEmitter.__init__(self)
Example #28
0
 def __init__(self, ri, trans_url):
     url = trans_url + '/websocket'
     if url[0:5] == "https":
         url = 'wss' + url[5:]
     else:
         url = 'ws' + url[4:]
     self.ri = ri
     self.url = url
     WebSocketClient.__init__(self, url)
Example #29
0
 def __init__(self, host='127.0.0.1', port=50637, endpoint='wsreload',
              protocols=None, extensions=None,
              default_query=None, open_query=None):
     WebSocketClient.__init__(
         self, 'ws://%s:%s/%s' % (host, port, endpoint),
         protocols, extensions)
     self.default_query = default_query
     self.open_query = open_query
     self.connect()
Example #30
0
 def __init__(self, url, headers, chunkIterator, responseQueue, contentType,
              config):
     self.chunkIterator = chunkIterator
     self.responseQueue = responseQueue
     self.contentType = contentType
     self.listeningMessages = 0
     self.config = config
     WebSocketClient.__init__(self, url, headers=headers.items())
     logger.debug("IBM initialized")
Example #31
0
        def __init__(self, botfriend, botfriendData, *args, **kwargs):

            self.botfriend = botfriend
            self.botfriendData = BotfriendData
            self.args = args
            self.kwargs = kwargs
            self.url = self.botfriendData.serverURL

            WebSocketClient.__init__(self, self.url, *args, **kwargs)
Example #32
0
 def __init__(self, ri, trans_url):
   url = trans_url + '/websocket'
   if url[0:5] == "https":
     url = 'wss' + url[5:]
   else:
     url = 'ws' + url[4:]
   self.ri = ri
   self.url = url
   WebSocketClient.__init__(self,url)
Example #33
0
 def __init__(self, url):
     if ssl:
         WebSocketClient.__init__(
             self, url, ssl_options={'ssl_version': ssl.PROTOCOL_TLSv1})
     else:
         WebSocketClient.__init__(self, url)
     self.data = []
     self.partialdata = []
     self.partialdatanumber = 1
Example #34
0
    def __init__(self, url, protocols=None, version='13'):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        ThreadedClient.__init__(self, url, protocols=protocols, version=version, sock=sock)

        self._lock = Semaphore()
        self._th = Greenlet(self._receive)
        self._messages = Queue()

        self.extensions = []
 def __init__(self, url, protocols=None, version='8'):
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
     ThreadedClient.__init__(self, url, protocols=protocols, version=version, sock=sock)
     
     self._lock = Semaphore()
     self._th = Greenlet(self._receive)
     self._messages = Queue()
     
     self.extensions = []
Example #36
0
	def __init__(self, hostname, router):
		#it needs to be imported here because on the main body 'printer' is None
		from octoprint.server import printer

		self._router = router
		self._printer = printer
		self._printerListener = None
		self._subscribers = 0
		WebSocketClient.__init__(self, hostname)
Example #37
0
 def __init__(self, address_port):
     WebSocketClient.__init__(self, address_port)
     self.robot_position_x = None
     self.robot_position_y = None
     self.waypoint_coordinates_x = None
     self.waypoint_coordinates_y = None
     self.coordinates_message_received = False
     self.move_to_waypoint_when_coordinates_received = False
     self.navigation_finished = False
     self.navigation_succeeded = False
Example #38
0
 def __init__(self):
     ws_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
     environment = getEnv()
     base64string = base64.encodestring(environment).replace("\n", "")
     self.listening = False
     try:
         WebSocketClient.__init__(self, ws_url,
             headers=[("Authorization", "Basic %s" % base64string)])
         self.connect()
     except: print "Failed to open WebSocket."
Example #39
0
 def __init__(self, url, protocols=['https-only'],
              extensions=None, ssl_options=None, headers=None,
              start_reqid=1):
     WebSocketClient.__init__(self, url, protocols, extensions,
                              ssl_options=ssl_options, headers=headers)
     self.open_done = threading.Event()
     self.rid_lock = threading.RLock()
     self.msglock = threading.RLock()
     self.messages = {}
     self._cur_request_id = start_reqid
Example #40
0
 def __init__(self, mode):
     print "--------------", mode
     self.mode = mode
     self.point = mode % 20
     self.proxyId = "vote-" + ("%d" % (self.point))
     self.name = u"心電計-" + ("%d" % (self.point))
     self.xurl = _Url + self.proxyId
     print(_Url)
     WebSocketClient.__init__(self,
                              self.xurl,
                              protocols=['http-only', 'chat'])
Example #41
0
    def __init__(self, ip="127.0.0.1", port=9090):
        """Constructor.

        Warning: there is a know issue regarding resolving localhost to IPv6 address.

        Args:
            ip (str, optional): Rosbridge instance IPv4/Host address. Defaults to 'localhost'.
            port (int, optional): Rosbridge instance listening port number. Defaults to 9090.
        """
        ExecutorBase.__init__(self, ip=ip, port=port)
        ThreadedWebSocketClient.__init__(self, self._uri)
Example #42
0
	def __init__(self):
		username = "******"
		password = "******"
		ws_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
		auth_string = "%s:%s" % (username, password)
		base64string = base64.encodestring(auth_string).replace("\n", "")
		self.listening = False
		try:
			WebSocketClient.__init__(self, ws_url,headers=[("Authorization", "Basic %s" % base64string)])
			self.connect()
		except: print "Failed to open WebSocket."
Example #43
0
 def __init__(self):
     ws_url = 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize'
     self.listening = False
     try:
         WebSocketClient.__init__(self,
                                  ws_url,
                                  headers=[("X-Watson-Authorization-Token",
                                            auth_token)])
         self.connect()
     except:
         print "Failed to open WebSocket."
Example #44
0
    def __init__(self, url, key):
        print("Connecting to " + url)
        WebSocketClient.__init__(self, url)

        self._sending_lock = threading.RLock()
        self._send_next_bin = None
        self._key = key
        self._last_keepalive_reply = time.time()
        self._last_activity = time.time()

        threading.Timer(30, self.check_keepalives).start()
Example #45
0
	def __init__(self, hostname, router):
		#it needs to be imported here because on the main body 'printer' is None
		from octoprint.server import printer

		self._router = router
		self._printer = printer
		self._printerListener = None
		self._subscribers = 0
		self._cameraManager = cameraManager()
		self._logger = logging.getLogger(__name__)
		WebSocketClient.__init__(self, hostname)
Example #46
0
 def __init__(self,
              url,
              on_open=None,
              on_close=None,
              on_message=None,
              on_error=None,
              **kwargs):
     self.callbacks = dict(on_open=on_open,
                           on_close=on_close,
                           on_message=on_message,
                           on_error=on_error)
     WS4PyWebSocketClient.__init__(self, url, **kwargs)
Example #47
0
    def __init__(self, socket_address):
        WebSocketClient.__init__(self, socket_address)

        self.create_time = datetime.datetime.now()
        self.__update_task__ = None
        self.__manage_connection_task__ = None
        self.last_message_received_time = None
        self.is_connected = False
        self.is_connecting = False
        self.connect()

        self.hb = ws4py.websocket.Heartbeat(self)
        self.hb.start()
Example #48
0
    def __init__(self,
                 watsonSTTUsername,
                 watsonSTTPassword,
                 rate=16000,
                 bits=16,
                 buflen=1024,
                 model="en-US_BroadbandModel",
                 timeout=-1,
                 audioFilename=None,
                 progressPipe=None):
        # Store parameters to instance vars
        self.rate = rate
        self.bits = bits
        self.buflen = buflen
        self.model = model  # default is en-US_BroadbandModel
        self.audioFilename = os.path.splitext(
            audioFilename) if audioFilename else None
        self.timeout = timeout  # Will cause
        self.progressPipe = progressPipe

        # Handles
        self.arecordproc = None
        self.audioF = None

        # state variables
        self.listening = False
        self.suspended = False

        self.info("WatsonSTTWebSocketClient VERSION {0}".format(
            WatsonSTTWebSocketClient_VERSION))
        try:
            ws_url = WatsonSTTWebSocketClient_URL
            if self.model:
                ws_url = ws_url + ("?model={0}".format(self.model))

            # Make the basic authentication header string
            import base64
            authString = "%s:%s" % (watsonSTTUsername, watsonSTTPassword)
            base64Auth = base64.encodestring(authString).replace("\n", "")

            self.info("Init WebSocketClient to {0} with {1}".format(
                ws_url, authString))
            WebSocketClient.__init__(self,
                                     ws_url,
                                     headers=[("Authorization",
                                               "Basic %s" % base64Auth),
                                              ("model", self.model)])
            self.connect()
        except:
            self.info("Failed to open WebSocketClient.")
            raise
Example #49
0
 def _send(self, request):
     with self._connection_cv:
         if not self._connected:
             # Clear any previous error state before attempting to
             # reconnect.
             self._error = None
             WebSocketClient.__init__(self, self._endpoint,
                                      heartbeat_freq=None)
             self.connect()
         while not self._connected and not self._error:
             self._connection_cv.wait()
         if not self._connected:
             raise self._error
     self.send(json.dumps(request))
Example #50
0
 def __init__(self, host=myLocalhost, channel=None):
     if host.startswith("http://"):
         host = host[7:]
     self.thisHost = host
     url = "ws://%s/fftools/sticky/firefly/events" % host  # web socket url
     if channel:
         url += "?channelID=%s" % channel
     WebSocketClient.__init__(self, url)
     self.urlRoot = "http://" + host + self.fftoolsCmd
     self.urlBW = "http://" + self.thisHost + "/fftools/app.html?id=Loader&channelID="
     self.listeners = {}
     self.channel = channel
     self.session = requests.Session()
     self.connect()
Example #51
0
	def __init__(self):
		username = os.environ['WTTSusername']
		password = os.environ['WTTSpassword']
		ws_url = os.environ['WTTSurl']
		auth_string = "%s:%s" % (username, password)
		base64string = base64.encodestring(auth_string).replace("\n", "")
		self.listening = False
		print "def_init_(self), self.listening = False"
		try:
			WebSocketClient.__init__(self, ws_url,
			headers=[("Authorization", "Basic %s" % base64string)])
			self.connect()
			print "self.connect()"
		except: print "Failed to open WebSocket."
Example #52
0
 def __init__(self, serverUrl, protocols, connectionEstablishedHandler, dataReceivedEventHandler):
     '''
     Initializes the state of the client.
     
     Keyword arguments:
     serverURL                        -- the URL of the websocket server.
     protocols                        -- a list containing the websocket protocols supported by the websockets client.
     connectionEstablishedHandler     -- a function that will be invoked after establishing the websocket connection.
     dataReceivedHandler              -- a function that will be invoked after receiving data from the websocket.
     '''
     WebSocketClient.__init__(self, serverUrl, protocols)
     self.__logger = LogFactory.configureLogger(self, logging.INFO, LogFactory.DEFAULT_LOG_FILE)
     self.__connectionEstablishedHandler = connectionEstablishedHandler
     self.__dataReceivedEventHandler = dataReceivedEventHandler
Example #53
0
	def __init__(self, manager, server, port=80):
		url = self.WS_URL.format(server, str(port))
		WebSocketClient.__init__(self, url)
		self.connected = False
		self.subs = {}
		self.collections = {}
		self.pending_msg = []
		self.completed_msg = []
		self.current_errors = []
		self.logged_in = False
		self.manager = manager
		self.dispatcher = {"added": self.on_added, "error": self.on_error, 
							"result": self.on_result, "changed": self.on_changed,
							"ready": self.on_ready}
Example #54
0
 def __init__(self, serverUrl, protocols, connectionEstablishedHandler, dataReceivedEventHandler):
     '''
     Initializes the state of the client.
     
     Keyword arguments:
     serverURL                        -- the URL of the websocket server.
     protocols                        -- a list containing the websocket protocols supported by the websockets client.
     connectionEstablishedHandler     -- a function that will be invoked after establishing the websocket connection.
     dataReceivedHandler              -- a function that will be invoked after receiving data from the websocket.
     '''
     WebSocketClient.__init__(self, serverUrl, protocols)
     self.__logger = LogFactory.configureLogger(self, logging.INFO, LogFactory.DEFAULT_LOG_FILE)
     self.__connectionEstablishedHandler = connectionEstablishedHandler
     self.__dataReceivedEventHandler = dataReceivedEventHandler
Example #55
0
 def _send(self, request):
     with self._connection_cv:
         if not self._connected:
             # Clear any previous error state before attempting to
             # reconnect.
             self._error = None
             WebSocketClient.__init__(self, self._endpoint,
                                      heartbeat_freq=None)
             self.connect()
         while not self._connected and not self._error:
             self._connection_cv.wait()
         if not self._connected:
             raise self._error
     self.send(json.dumps(request))
 def __init__(self, host=myLocalhost, channel=None):
     if host.startswith('http://'):
         host = host[7:]
     self.thisHost = host
     url = 'ws://%s/fftools/sticky/firefly/events' % host #web socket url
     if channel:
         url+= '?channelID=%s' % channel
     WebSocketClient.__init__(self, url)
     self.urlRoot = 'http://' + host + self.fftoolsCmd
     self.urlBW = 'http://' + self.thisHost + '/fftools/app.html?id=Loader&channelID='
     self.listeners = {}
     self.channel = channel
     self.session = requests.Session()
     print 'websocket url:%s' % url
     self.connect()
Example #57
0
    def __init__(self, token, endpoint=constants.DEFAULT_STREAM_ENDPOINT,
                 timeout=constants.DEFAULT_TIMEOUT):
        ws_endpoint = '{0}/{1}'.format(
                endpoint.replace('http', 'ws', 1),
                WebSocketTransport._SIGNALFLOW_WEBSOCKET_ENDPOINT)

        transport._SignalFlowTransport.__init__(self, token, ws_endpoint,
                                                timeout)
        WebSocketClient.__init__(self, self._endpoint, heartbeat_freq=None)

        self._server_time = None
        self._connected = False
        self._error = None

        self._connection_cv = threading.Condition()
        self._channels = {}
    def __init__(self, url, debugPrint = False, raiseErrors = False, printErrors = True):
        WebSocketClient.__init__(self, url)
        self.debugPrint = debugPrint

        self.outstandingRequests = {}
        self.subNameToID = {}

        # Place to collect collections
        self.collections = CollectionCollection()

        self.raiseErrors = raiseErrors
        self.printErrors = printErrors

        self.DDP_Connected = False

        self.nrecieved = 0