Esempio n. 1
0
    def start(self, code):
        def run(sdk_conn):
            '''The run method runs once Cozmo SDK is connected.'''
            self._robot = sdk_conn.wait_for_robot()
            self._origin = self._robot.pose
            self.cubes_to_numbers = {}
            for key in self._robot.world.light_cubes:
                self.cubes_to_numbers[self._robot.world.light_cubes.get(
                    key).object_id] = key
            self.resetCubes()
            self.resetCustomObjects()

            self._robot.camera.image_stream_enabled = True

            bot = self

            import cozmo
            exec(code, locals(), locals())

        from ws4py.client.threadedclient import WebSocketClient
        self._camClient = WebSocketClient('ws://localhost:9090/camPub')
        self._camClient.connect()

        self._wsClient = WebSocketClient('ws://localhost:9090/WsPub')
        self._wsClient.connect()

        self._dataPubThread = threading.Thread(
            target=self.feedRobotDataInThread)
        self._dataPubThread.daemon = True
        self._dataPubThread.start()

        cozmo.setup_basic_logging()
        cozmo.robot.Robot.drive_off_charger_on_connect = False
        cozmo.connect(run)
        self._robot = None
Esempio n. 2
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
Esempio n. 3
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!")
    def setUp(self, sock):
        self.sock = MagicMock(spec=socket.socket)
        sock.socket.return_value = self.sock
        sock.getaddrinfo.return_value = [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
                                          ("127.0.0.1", 80, 0, 0))]

        self.client = WebSocketClient(url="ws://127.0.0.1/")
Esempio n. 5
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
Esempio n. 6
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))
Esempio n. 7
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
Esempio n. 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)
Esempio n. 9
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
Esempio n. 10
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)
Esempio n. 11
0
    def __init__(self, **kwargs):
        self.token = ''

        gateway = requests.get(endpoints.GATEWAY)
        if gateway.status_code != 200:
            raise GatewayNotFound()
        gateway_js = gateway.json()
        url = gateway_js.get('url')
        if url is None:
            raise GatewayNotFound()

        self.ws = WebSocketClient(url,
                                  protocols=['http-only', 'chat', 'voice'])

        # this is kind of hacky, but it's to avoid deadlocks.
        # i.e. python does not allow me to have the current thread running if it's self
        # it throws a 'cannot join current thread' RuntimeError
        # So instead of doing a basic inheritance scheme, we're overriding the member functions.

        self.ws.opened = self._opened
        self.ws.closed = self._closed
        self.ws.received_message = self._received_message

        # the actual headers for the request...
        # we only override 'authorization' since the rest could use the defaults.
        self.headers = {
            'authorization': self.token,
        }
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 14
0
    def _create_websocket(self, url, reconnect=False):
        if url is None:
            raise GatewayNotFound()
        log.info('websocket gateway found')
        self.ws = WebSocketClient(url, protocols=['http-only', 'chat'])

        # this is kind of hacky, but it's to avoid deadlocks.
        # i.e. python does not allow me to have the current thread running if it's self
        # it throws a 'cannot join current thread' RuntimeError
        # So instead of doing a basic inheritance scheme, we're overriding the member functions.

        self.ws.opened = self._opened
        self.ws.closed = self._closed
        self.ws.received_message = self._received_message
        self.ws.connect()
        log.info('websocket has connected')

        if reconnect == False:
            second_payload = {
                'op': 2,
                'd': {
                    'token': self.token,
                    'properties': {
                        '$os': sys.platform,
                        '$browser': 'discord.py',
                        '$device': 'discord.py',
                        '$referrer': '',
                        '$referring_domain': ''
                    },
                    'v': 2
                }
            }

            self.ws.send(json.dumps(second_payload))
Esempio n. 15
0
    def __init__(self, WebSocket=None, notify_file=None, config=None):

        self.notify_lock = RLock()

        if not config:
            self.config = ConfigService()
        else:
            self.config = config

        if not notify_file:
            notify_file = self.config.get('general', 'notify_file')

        if not WebSocket:
            SOCKET_HOST = self.config.get('socket', 'host')
            SOCKET_PORT = self.config.get('socket', 'port')
            self.ws = WebSocketClient('ws://' + SOCKET_HOST + ':' +
                                      SOCKET_PORT + '/')
            self.ws.connect()
        else:
            self.ws = WebSocket

        self.notify_file = notify_file

        self.backtrack = int(self.config.get('notify', 'backtrack', 30))
        self.event_id = 0
        self.events = []
Esempio n. 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
Esempio n. 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()
class SocketWrapper:
    def __init__(self, IP):
        sock = socket.gethostbyname(socket.gethostname())

        # self.addr = "ws://{}:81/ws".format(sock)
        print('Connecting...')
        self.addr = IP
        self.socket = WebSocketClient(self.addr)

        self.socket.connect()
        print('Socket connected:', IP)

    def send_motion(self, ID, arg1, arg2):
        if ID == "~":
            ID = 126
        elif ID == "#":
            ID = 35

        if arg1 == "F":
            arg1 = 70

        payload = [ID, arg1, arg2]
        payload = bytearray(payload)

        self.socket.send(bytearray(payload), True)

    def close(self):
        self.close()
Esempio n. 19
0
 def send_with_header(self, json_data, blob=None):
     if (not json_data.get("id","").startswith("downlink-keepalive")) and json_data.get("type") != "STATS":
         self.record_activity()
     with self._sending_lock:
         WebSocketClient.send(self, json.dumps(json_data), False)
         if blob is not None:
             WebSocketClient.send(self, blob, True)
Esempio n. 20
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
Esempio n. 21
0
 def waitForEvents(self):
     """
     Pause and do not exit.  Wait over events from the server.
     This is optional. You should not use this method in ipython notebook
     Event will get called anyway.
     """
     WebSocketClient.run_forever(self)
Esempio n. 22
0
    def __init__(self, **kwargs):
        self._is_logged_in = False
        self.user = None
        self.servers = []
        self.private_channels = []
        self.token = ''
        self.events = {
            'on_ready': _null_event,
            'on_disconnect': _null_event,
            'on_error': _null_event,
            'on_response': _null_event,
            'on_message': _null_event
        }

        self.ws = WebSocketClient(endpoints.WEBSOCKET_HUB,
                                  protocols=['http-only', 'chat'])

        # this is kind of hacky, but it's to avoid deadlocks.
        # i.e. python does not allow me to have the current thread running if it's self
        # it throws a 'cannot join current thread' RuntimeError
        # So instead of doing a basic inheritance scheme, we're overriding the member functions.

        self.ws.opened = self._opened
        self.ws.closed = self._closed
        self.ws.received_message = self._received_message
        self.ws.connect()

        # the actual headers for the request...
        # we only override 'authorization' since the rest could use the defaults.
        self.headers = {
            'authorization': self.token,
        }
Esempio n. 23
0
 def send(self,data,binary = False):
     self._lock.acquire()
     if binary:
         WS4PyWebSocketClient.send(self,data,True)
     else:
         WS4PyWebSocketClient.send(self,data)
     self._lock.release()
Esempio n. 24
0
 def waitForEvents(self):
     """
     Pause and do not exit.  Wait over events from the server.
     This is optional. You should not use this method in ipython notebook
     Event will get called anyway.
     """
     WebSocketClient.run_forever(self)
Esempio n. 25
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))
Esempio n. 26
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
Esempio n. 27
0
def printlog(percent, num):

    global ws
    global host
    global port

    stats = {
        'percent': str(percent),
        'img_number': str(cs),
        'tot_images': str(slices)
    }
    post_processing = {
        'name': name,
        'pid': str(myPID),
        'started': str(t0),
        'completed': str(completed),
        'completed_time': str(completed_time),
        'stats': stats
    }
    str_log = {'post_processing': post_processing}
    #str_log='{"post_processing":{"name": "'+name+'","pid": "'+str(myPID)+'","started": "'+str(t0)+'","completed": "'+str(completed)+'","completed_time": "'+str(completed_time)+'","stats":{"percent":"'+str(percent)+'","img_number":'+str(cs)+',"tot_images":'+str(slices)+'}}}'
    message = {'type': 'post_processing', 'data': str_log}

    try:
        ws.send(json.dumps(message))
    except Exception, e:
        print str(e)
        ws = WebSocketClient('ws://' + host + ':' + port + '/')
        ws.connect()
	def stream_audio(self):
		#self.listening = True if online server response on received_message
		while not self.listening:
			time.sleep(0.1)

		CHUNK = 1024
		FORMAT = pyaudio.paInt16
		CHANNELS = 1
		RATE = 16000
		print "test"
		p = pyaudio.PyAudio()
		stream = p.open(format=FORMAT,
				channels=CHANNELS,
				rate=RATE,
				input=True,
				output=True,
				frames_per_buffer=CHUNK)
		start = time.time()
		while self.listening:
			data = stream.read(CHUNK)
			#print data
			self.send(bytearray(data),binary=True)
			if time.time() - start > 3:    # Records for n seconds
				self.send(json.dumps({'action': 'stop'}))
				return False
		stream.stop_stream()
		stream.close()
		p.terminate()

	 	self.listening = False
	 	self.stream_audio_thread.join()
		WebSocketClient.closed(self)
Esempio n. 29
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 = {}
Esempio n. 30
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()
Esempio n. 31
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)
Esempio n. 32
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)
Esempio n. 33
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()
Esempio n. 34
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
 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)
Esempio n. 36
0
 def send_with_header(self, json_data, blob=None):
     try:
         with self._sending_lock:
             WebSocketClient.send(self, json.dumps(json_data), False)
             if blob is not None:
                 WebSocketClient.send(self, blob, True)
     except TypeError:
         raise _server.SerializationError("Value must be JSON serializable")
Esempio n. 37
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
Esempio n. 38
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."
Esempio n. 39
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)
Esempio n. 40
0
    def __init__(self, webSocketDebuggerUrl, onload=None):
        WebSocketClient.__init__(self, webSocketDebuggerUrl)

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

        self.connect()
Esempio n. 41
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)
Esempio n. 42
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)
Esempio n. 43
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)
Esempio n. 44
0
    def __init__(self, url):
        self.ws = WebSocketClient(url)
        self.queue = Queue.Queue()

        def onmessage(m):
            print "received: %s" % m
            self.queue.put(unicode(str(m), 'utf-8'))

        self.ws.received_message = onmessage
Esempio n. 45
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()
Esempio n. 46
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 = []
Esempio n. 47
0
	def send(self, data):
		try:
			WebSocketClient.send(self, data)

		except socket.error as e:
			self._logger.error('Error raised during send: %s' % e)

			#Something happened to the link. Let's try to reset it
			self.close()
Esempio n. 48
0
 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 = []
Esempio n. 49
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
Esempio n. 50
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)
Esempio n. 51
0
 def close(self, code=1000, reason=''):
     try:
         WebSocketClient.close(self, code=code, reason=reason)
     except:
         pass
     try:
         WebSocketClient.close_connection(self)
     except:
         pass
     self.connected = False
Esempio n. 52
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
Esempio n. 53
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)
Esempio n. 54
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."
Esempio n. 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))
Esempio n. 56
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}
Esempio n. 57
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
Esempio n. 58
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()
Esempio n. 59
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."