Ejemplo n.º 1
0
 def send_to_all(cls, message, exclude_websockets=None):
     with cls.websockets_lock:
         for websocket in cls.websockets:
             if not exclude_websockets or websocket not in exclude_websockets:
                 try:
                     websocket.write_message(message)
                 except Exception:
                     traceback.print_exc()
Ejemplo n.º 2
0
    def on_message(self, message):
        global audio_packet_list, writing_file_1, adaptive_buffer
        if message:
            if len(message) == 400:
                # it's an audio packet
                print "audio packet received"

                if len(audio_packet_list) == 25:
                    print 'received audio termination request', datetime.now()

                    audio_array = np.concatenate(audio_packet_list)
                    audio_packet_list = []

                    to_send = {
                        'type': 'audio-array',
                        'array': audio_array.tolist()
                    }
                    for socket in browser_audio_sockets:
                        socket.write_message(json.dumps(to_send))

                print "packets received: ", len(audio_packet_list)
                audio_packet_raw = np.frombuffer(message, dtype=np.uint16)
                adaptive_buffer = np.roll(adaptive_buffer, 200)
                adaptive_buffer[0:200] = audio_packet_raw

                adaptive_mean = np.mean(adaptive_buffer)
                adaptive_std = np.std(adaptive_buffer)

                audio_packet = (audio_packet_raw -
                                adaptive_mean) / (10.0 * adaptive_std)
                audio_packet = np.clip(audio_packet, -1, 1)
                audio_packet_list.append(audio_packet)

            else:
                # it's an image packet - the audio ones are always exactly 200 long
                if message == "image done":
                    print "Full image received"
                    complete_image = 'images/cam_feed1.jpg' if writing_file_1 else 'images/cam_feed2.jpg'
                    new_image = 'images/cam_feed2.jpg' if writing_file_1 else 'images/cam_feed1.jpg'

                    f = open(new_image, 'w')
                    f.write('')
                    f.close()

                    writing_file_1 = not writing_file_1

                    print "File size", os.stat(complete_image).st_size
                    for websocket in cam_sockets:
                        websocket.write_message(complete_image)

                else:
                    print "Image packet received"
                    filename = 'images/cam_feed1.jpg' if writing_file_1 else 'images/cam_feed2.jpg'

                    f = open(filename, "ab")
                    f.write(message)
                    f.close()
Ejemplo n.º 3
0
def send_session(websocket):
    """ Function to send initial session data over web socket. """
    message = {'kind': 'session-data', 'data': globals.sessionData}
    jsonmessage = json.dumps(message)
    logging.debug(jsonmessage)
    websocket.write_message(jsonmessage)
    message = {'kind': 'status-update', 'data': {'files': list_files(), 'loading': {}, 'buckets': list_buckets()}}
    jsonmessage = json.dumps(message)
    logging.debug(jsonmessage)
    websocket.write_message(jsonmessage)
Ejemplo n.º 4
0
def send_messages(websocket, messages, extra=None):
    #messages_data = [message_to_dict(m) for m in messages]
    messages_data = {
        k: message_to_dict(v)
        for k, v in messages.items() if is_not_spam(v)
    }

    to_send = {'messages': messages_data}
    if extra:
        to_send.update(extra)

    websocket.write_message(to_send)
Ejemplo n.º 5
0
    def broadcast(cls, messages):
        logging.info("Sending new message to %r listeners", len(cls.websockets))
        body_str = json.dumps({"messages": messages})
        headers = [('Content-Type', 'text/json')]
        status_str = '200 OK'

        for websocket in cls.websockets.values():
            try:
                websocket.write_message(body_str)
            except Exception, excp:
                logging.warning("ERROR in writing to websocket: %s; closing", excp)
                try:
                    websocket.close()
                except Exception:
                    pass
Ejemplo n.º 6
0
Archivo: app.py Proyecto: fred3m/toyz
    def new_session(self, user_id, websocket, session_id=None):
        """
        Open a new websocket session for a given user
        
        Parameters
            user_id ( :py:class:`toyz.utils.core.ToyzUser` ): User id
            websocket (:py:class:`toyz.web.app.WebSocketHandler` ): new websocket opened
        """
        import datetime
        if user_id not in self.user_sessions:
            self.user_sessions[user_id] = {}
            print("Users logged in:", self.user_sessions.keys())

        if session_id is None:
            session_id = str(datetime.datetime.now()).replace(
                ' ', '__').replace('.', '-').replace(':', '_')
        self.user_sessions[user_id][session_id] = websocket
        shortcuts = db_utils.get_param(self.toyz_settings.db,
                                       'shortcuts',
                                       user_id=user_id)
        shortcuts = core.check_user_shortcuts(self.toyz_settings, user_id,
                                              shortcuts)
        websocket.session = {
            'user_id': user_id,
            'session_id': session_id,
            'path': os.path.join(shortcuts['temp'], session_id),
        }
        core.create_paths(websocket.session['path'])

        #initialize process for session jobs
        websocket.job_pipe, remote_pipe = multiprocessing.Pipe()
        websocket.process = multiprocessing.Process(target=job_process,
                                                    args=(session_id,
                                                          remote_pipe,
                                                          websocket.job_pipe))
        websocket.process.start()
        remote_pipe.close()
        process_events = (tornado.ioloop.IOLoop.READ
                          | tornado.ioloop.IOLoop.ERROR)
        tornado.ioloop.IOLoop.current().add_handler(websocket.job_pipe,
                                                    websocket.send_response,
                                                    process_events)

        websocket.write_message({
            'id': 'initialize',
            'user_id': user_id,
            'session_id': session_id,
        })
Ejemplo n.º 7
0
    def post(self):
        user = self.request.arguments['user'][0]

        #construct JSON Object
        data = [{'command':'spawnwebsocket', 'user':user}]
        jsonObject = json.dumps(data)

        for client in listeners.get('admin', ['default']):
            websocket = client.webSocket
            websocket.write_message(jsonObject)
        #websocket = listeners.get('admin',['default'])[0].webSocket

        #print 'THE WEBSOCKET = \n\n'
        #print websocket

        return 'true'
Ejemplo n.º 8
0
    def post(self):
        if 'message' in self.request.arguments:
            message = self.request.arguments['message'][0]
            group = self.request.arguments.get('group', ['default'])[0]
            print '%s:MESSAGE to %s:%s' % (time.time(), group, message)

            #For every Client Listener in the group specified in post data
            for client in listeners.get(group, []):
                client.write_message(message)

            websocket = listeners.get('admin', ['default'])[0].webSocket

            print 'THE WEBSOCKET = \n\n'
            print websocket
            websocket.write_message(message)
            return 'true'
        return 'false'
Ejemplo n.º 9
0
def periodic_check():
    #print("Periodic Callback with num sockets: " + str(len(websockets)))
    pc.scanlocations()
    for websocket in websockets:
        items = []
        for item in pc.processlist:
            itemcontent = {
                "hostname": item["hostname"],
                "processname": item["processname"],
                "hash": item["hash"],
                "sshstatus": item["sshstatus"],
                "processstatus": item["processstatus"],
                "journal": item["journal"]
            }
            items.append(itemcontent)
        msg = {"type": "update", "items": items}
        websocket.write_message(json.dumps(msg))
Ejemplo n.º 10
0
 def send_scene(self, websocket):
     for node in walk(self.tree):
         if node.object is not None:
             websocket.write_message(node.object, binary=True)
         for p in node.properties:
             websocket.write_message(p, binary=True)
         if node.transform is not None:
             websocket.write_message(node.transform, binary=True)
         if node.animation is not None:
             websocket.write_message(node.animation, binary=True)
Ejemplo n.º 11
0
Archivo: app.py Proyecto: fred3m/toyz
 def new_session(self, user_id, websocket, session_id=None):
     """
     Open a new websocket session for a given user
     
     Parameters
         user_id ( :py:class:`toyz.utils.core.ToyzUser` ): User id
         websocket (:py:class:`toyz.web.app.WebSocketHandler` ): new websocket opened
     """
     import datetime
     if user_id not in self.user_sessions:
         self.user_sessions[user_id] = {}
         print("Users logged in:", self.user_sessions.keys())
     
     if session_id is None:
         session_id = str(
             datetime.datetime.now()).replace(' ','__').replace('.','-').replace(':','_')
     self.user_sessions[user_id][session_id] = websocket
     shortcuts = db_utils.get_param(self.toyz_settings.db, 'shortcuts', 
         user_id=user_id)
     shortcuts = core.check_user_shortcuts(self.toyz_settings, user_id, shortcuts)
     websocket.session = {
         'user_id': user_id,
         'session_id': session_id,
         'path': os.path.join(shortcuts['temp'], session_id),
     }
     core.create_paths(websocket.session['path'])
     
     #initialize process for session jobs
     websocket.job_pipe, remote_pipe = multiprocessing.Pipe()
     websocket.process = multiprocessing.Process(
         target = job_process, args=(session_id, remote_pipe, websocket.job_pipe))
     websocket.process.start()
     remote_pipe.close()
     process_events = (tornado.ioloop.IOLoop.READ | tornado.ioloop.IOLoop.ERROR)
     tornado.ioloop.IOLoop.current().add_handler(
         websocket.job_pipe, websocket.send_response, process_events)
     
     websocket.write_message({
         'id': 'initialize',
         'user_id': user_id,
         'session_id': session_id,
     })
Ejemplo n.º 12
0
def forward_packet_to_ws_client(reserved_socket: socket.socket,
                                ws: ws.WebSocketHandler):
    asyncio.set_event_loop(asyncio.new_event_loop())
    message = ' '
    while message:
        message = reserved_socket.recv(pw.tcp_bufsize)
        #log.info("VCL  " + str(message))
        if message:
            ws.write_message(message=message, binary=binary_type)
        else:
            try:
                reserved_socket.shutdown(SHUT_RD)
            except:
                pass
            try:
                ws.close()
                pass
            except:
                pass
    pass
Ejemplo n.º 13
0
    def _write_data_response(websocket, data_points):
        """Generates a serialized data message with headers for deserialization.

        Writes output to websocket.
        """
        assert data_points
        model_info = model_meta.get_field_info(TimeSeriesDataPoint)
        field_names = TimeSeriesDataPointSerializer(data_points[0])\
            .get_field_names({}, model_info)
        response = {
            'headers': list(field_names),
            'data': [],
        }
        LOGGER.debug("Writing %d datapoints out.", len(data_points))
        for data_point in data_points:
            serializer = TimeSeriesDataPointSerializer(data_point)
            data = serializer.data
            data_entry = []
            for field_name in field_names:
                data_entry.append(data[field_name])
            response['data'].append(data_entry)
        websocket.write_message(json.dumps(response))
Ejemplo n.º 14
0
    def _write_data_response(websocket, data_points):
        """Generates a serialized data message with headers for deserialization.

        Writes output to websocket.
        """
        assert data_points
        model_info = model_meta.get_field_info(TimeSeriesDataPoint)
        field_names = TimeSeriesDataPointSerializer(data_points[0])\
            .get_field_names({}, model_info)
        response = {
            'headers': list(field_names),
            'data': [],
        }
        LOGGER.debug("Writing %d datapoints out.", len(data_points))
        for data_point in data_points:
            serializer = TimeSeriesDataPointSerializer(data_point)
            data = serializer.data
            data_entry = []
            for field_name in field_names:
                data_entry.append(data[field_name])
            response['data'].append(data_entry)
        websocket.write_message(json.dumps(response))
Ejemplo n.º 15
0
 def do_route(self,target_page_id=None,envelope=None,**kwargs):
     websocket=self.channels.get(target_page_id)
     if websocket:
         websocket.write_message(envelope)
Ejemplo n.º 16
0
 def forward_to_websockets(self, frames):
     cmd, path, data = frames
     for websocket in self.websocket_pool:
         websocket.write_message(data, binary=True)
Ejemplo n.º 17
0
 def send_to_websockets(self, msg):
     print("msg:", msg)
     for websocket in self.websocket_pool:
         websocket.write_message(msg[0])
     self.zmq_socket.send(b"ok")
 def on_message(self, message):
     for websocket in all_websocket:
         websocket.write_message(message)
 def post(self):
     msg = self.get_argument("msg", strip=True)
     LOGGER.debug(msg)
     for websocket in all_websocket:
         websocket.write_message(msg)
Ejemplo n.º 20
0
 def write_message_all(message, binary=False):
     s = GithubWebhook.StatusWebSocket
     with s.lock:
         for websocket in s.websockets:
             websocket.write_message(message, binary)
Ejemplo n.º 21
0
 def send_scene(self, websocket):
     for node in walk(self.tree):
         if node.object is not None:
             websocket.write_message(node.object, binary=True)
         if node.transform is not None:
             websocket.write_message(node.transform, binary=True)
Ejemplo n.º 22
0
 def write_message_all(message, binary=False):
     s = GithubWebhook.StatusWebSocket
     with s.lock:
         for websocket in s.websockets:
             websocket.write_message(message, binary)