Python flask_socketio.emit() Examples

The following are 18 code examples of flask_socketio.emit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_socketio , or try the search function .
Example #1
Source File: socket_logging.py    From OmegaUI with GNU General Public License v3.0 6 votes vote down vote up
def background_thread(uid_with_size):
    uid, size = uid_with_size.split(';')
    r = redis.StrictRedis(oc.cfg['default']['redis'], 6379, db=0)
    r.set(uid+'size', size)
    pubsub = r.pubsub()
    pubsub.subscribe('l'+uid)
    count = 0
    for message in pubsub.listen():
        # Filter out events like Redis connections.
        if message['type'] != 'message':
            continue
        count += 1
        socketio.sleep(0.01)
        try:
            data = json.loads(message['data'].decode('utf8'))
            msg = uid + data['name'] + ': ' + data['levelname'] + ': ' + data['msg']
            socketio.emit('log_response', {'data': msg, 'count': count}, namespace='/omega_log')
        except:
            pass 
Example #2
Source File: process.py    From Lie_to_me with MIT License 6 votes vote down vote up
def process_video(filepath):
    """
        Processes Video Submitted by User
    """
    global video_fps_rate

    width, height, fps_rate = convert_to_frames(filepath)  # convert the video to images
    ordered_files = sorted(os.listdir(frames_dir), key=lambda x: (int(re.sub(r'\D','',x)),x))

    # Convert all frames to base64 images and begin calling
    for index, frame in enumerate(ordered_files):
        with open(os.path.join(frames_dir, frame), 'rb') as image_file:
            encoded_string = base64.b64encode(image_file.read())
            base64_frames[index] = encoded_string.decode('utf-8')

    cleanup_video_frames()

    video_fps_rate[0] = fps_rate

    # Frames are ready - start sending them to for pooling
    # Let's emit a message indicating that we're about to start sending files
    socketio.emit('canvas_width_height', {'width': width, 'height': height}) 
Example #3
Source File: sync_namespace.py    From hydrus with MIT License 5 votes vote down vote up
def on_reconnect(self):
        print('A client reconnected.')
        emit('connect', {'last_job_id': get_last_modification_job_id(self.db_session)}) 
Example #4
Source File: server.py    From watson-online-store with Apache License 2.0 5 votes vote down vote up
def do_connect():
    """On web UI connect, do something here."""
    # On web UI connect, send a generic greeting via Flask SocketIO.
    # Uncomment for debugging. Not great for normal use case.
    # emit('my_response', {'data': 'Hello!'})
    pass 
Example #5
Source File: server.py    From watson-online-store with Apache License 2.0 5 votes vote down vote up
def send_message(self, message):
        """Function to send a message to the web-ui via Flask SocketIO."""
        lines = message.split('\n')
        for line in lines:
            image = None
            if 'output_format[png]' in line:
                line, http_tail = line.split('http', 1)
                image = 'http' + http_tail

            emit('my_response', {'data': line.strip(), 'image': image}) 
Example #6
Source File: socket_logging.py    From OmegaUI with GNU General Public License v3.0 5 votes vote down vote up
def connect():
    print('Client connected', flask.request.sid)
    fsio.emit('log_response', {'data': 'Connected', 'count': 0}) 
Example #7
Source File: socket_logging.py    From OmegaUI with GNU General Public License v3.0 5 votes vote down vote up
def test_message(message):
    flask.session['receive_count'] = flask.session.get('receive_count', 0) + 1
    pool.spawn(background_thread, message['data'])
    fsio.emit('log_response', {'data': message['data'], 'count': flask.session['receive_count']}) 
Example #8
Source File: process.py    From Lie_to_me with MIT License 5 votes vote down vote up
def process_audio(filepath):
    """ Process Audio component of Video
    """
    json_path = os.path.join(basedir, 'static', 'data', 'tmp_json')

    mean_energy = []
    max_pitch_amp = []
    vowel_duration = []
    pitch_contour = []

    output = convert_audio(filepath)

    for files in output:
        frames, framelength = audio.split(files)
        filteredframes = audio.applyhamming(frames)
        energy = audio.energy(filteredframes)
        fourier = audio.fourier(filteredframes)
        frames = audio.inverse_fourier(fourier)
        pitchamp, pitchperiod = audio.sampling(frames)

        # Implemented Features, read audio.py for return values
        data1 = audio.meanenergy(energy)
        data2 = audio.maxpitchamp(pitchamp)
        data3 = audio.vowelduration(pitchamp, data2)
        data4 = audio.fundamentalf(pitchperiod, framelength)

        mean_energy.append(data1)
        max_pitch_amp.append(data2)
        vowel_duration.append(data3)
        pitch_contour.append(data4)

    with shelve.open(os.path.join(json_path, 'audio_data.shlf')) as shelf:
        shelf['mean_energy'] = mean_energy
        shelf['max_pitch_amp'] = max_pitch_amp
        shelf['vowel_duration'] = vowel_duration
        shelf['pitch_contour'] = pitch_contour

    socketio.emit('data_complete', 'Audio_Complete')

    cleanup_audio() 
Example #9
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_settings(json):
    """
        Get the form data from the web front end, and save theses values to settings.conf
        Then restart the services which have a dependency with these parameters.
        param json: A json variable containing the source fom and the new paramaters
    """
    print("received settings form", json)
    source_section = json.pop().get("source_form")
    print("section: ", source_section)
    if source_section == "change_password":
        if json[0].get("value") == json[1].get("value"):
            rtkbaseconfig.update_setting("general", "new_web_password", json[0].get("value"))
            update_password(rtkbaseconfig)
            socketio.emit("password updated", namespace="/test")

        else:
            print("ERREUR, MAUVAIS PASS")
    else:
        for form_input in json:
            print("name: ", form_input.get("name"))
            print("value: ", form_input.get("value"))
            rtkbaseconfig.update_setting(source_section, form_input.get("name"), form_input.get("value"), write_file=False)
        rtkbaseconfig.write_file()

        #Restart service if needed
        if source_section == "main":
            restartServices(("main", "ntrip", "rtcm_svr", "file"))
        elif source_section == "ntrip":
            restartServices(("ntrip",))
        elif source_section == "rtcm_svr":
            restartServices(("rtcm_svr",))
        elif source_section == "local_storage":
            restartServices(("file",)) 
Example #10
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def readRINEXVersion():
    rinex_version = rtk.logm.getRINEXVersion()
    rtk.socketio.emit("current RINEX version", {"version": rinex_version}, namespace="/test") 
Example #11
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def getAvailableSpace():
    rtk.socketio.emit("available space", reach_tools.getFreeSpace(path_to_gnss_log), namespace="/test")

#### Delete log button handler #### 
Example #12
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def getAvailableLogs():
    print("DEBUG updating logs")
    rtk.logm.updateAvailableLogs()
    print("Updated logs list is " + str(rtk.logm.available_logs))
    rtk.socketio.emit("available logs", rtk.logm.available_logs, namespace="/test")

#### str2str launch/shutdown handling #### 
Example #13
Source File: application.py    From async_flask with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def randomNumberGenerator():
    """
    Generate a random number every 1 second and emit to a socketio instance (broadcast)
    Ideally to be run in a separate thread?
    """
    #infinite loop of magical random numbers
    print("Making random numbers")
    while not thread_stop_event.isSet():
        number = round(random()*10, 3)
        print(number)
        socketio.emit('newnumber', {'number': number}, namespace='/test')
        socketio.sleep(5) 
Example #14
Source File: sync_namespace.py    From hydrus with MIT License 5 votes vote down vote up
def on_get_modification_table_diff(self, data):
        """Get modification table diff and emit it to the client.
        :param data: Dict with 'agent_job_id' key.
        """
        if 'agent_job_id' in data:
            agent_job_id = data['agent_job_id']
            modification_table_diff = get_modification_table_diff(self.db_session,
                                                                  agent_job_id)
        else:
            modification_table_diff = get_modification_table_diff(self.db_session)
        emit('modification_table_diff', modification_table_diff) 
Example #15
Source File: sync_namespace.py    From hydrus with MIT License 5 votes vote down vote up
def on_connect(self):
        print('A client connected')
        emit('connect', {'last_job_id': get_last_modification_job_id(self.db_session)}) 
Example #16
Source File: app.py    From hyperface with MIT License 4 votes vote down vote up
def new_server(viewer_queue, stop_page, port, secret_key):
    # create server
    app = Flask(__name__, static_url_path='/static')
    app.config['SECRET_KEY'] = secret_key
    # must be 'threading' for broadcast emitting
    socketio = SocketIO(app, async_mode='threading',
                        logger=False, engineio_logger=False)

    # rooting
    @app.route('/')
    def __index():
        logger.info('Render viewer page')
        return render_template('index.html', script="index.js")

    if stop_page:
        @app.route('/stop')
        def __stop():
            socketio.stop()
            logger.info('Server stop request')
            return 'This server is stopped'

    @socketio.on('connect', namespace=IO_NAMESPACE)
    def __on_viewer_connect():
        logger.info('New viewer connection is established')

    @socketio.on('disconnect', namespace=IO_NAMESPACE)
    def __on_viewer_disconnect():
        logger.info('Viewer connection is closed')

    @socketio.on('update', namespace=IO_NAMESPACE)
    def __on_update():
        logger.info('Image updating request is received')
        # get all of current data
        emit_data = buffering_thread.get_data_all()
        # emit all
        logger.debug('Emit for update all')
        emit('update', emit_data, namespace=IO_NAMESPACE)

    def update_event(tab, name, data):
        emit_data = [[tab, name, data]]  # single data
        # broadcast emit
        logger.debug('Broadcast emit for update (tab: %s, name: %s)' %
                     (str(tab), str(name)))
        socketio.emit('update', emit_data, namespace=IO_NAMESPACE)

    # create image updating thread
    if viewer_queue:
        logger.info('Start image buffering thread')
        buffering_thread = ImageBufferingThread(viewer_queue)
        buffering_thread.daemon = True
        buffering_thread.start()
        buffering_thread.register_update_event_func(update_event)

    # start server
    logger.info('Start server on port %d' % port)
    socketio.run(app, host='0.0.0.0', port=port, debug=False, log_output=False)
    logger.info('Stop server on port %d' % port) 
Example #17
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 1 votes vote down vote up
def update_rtkbase():
    """
        Check if a RTKBase exists, download it and update rtkbase
    """
    #Check if an update is available
    update_url = check_update(emit=False).get("url")
    if update_url is None:
        return

    import tarfile
    #Download update
    update_archive = "/var/tmp/rtkbase_update.tar.gz"
    try:
        response = requests.get(update_url)
        with open(update_archive, "wb") as f:
            f.write(response.content)
    except Exception as e:
        print("Error: Can't download update - ", e)

    #Get the "root" folder in the archive
    tar = tarfile.open(update_archive)
    for tarinfo in tar:
        if tarinfo.isdir():
            primary_folder = tarinfo.name
            break
    
    #Extract archive
    tar.extractall("/var/tmp")

    #launch update script
    rtk.shutdownBase()
    rtkbase_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
    source_path = os.path.join("/var/tmp/", primary_folder)
    script_path = os.path.join(source_path, "rtkbase_update.sh")
    current_release = rtkbaseconfig.get("general", "version").strip("v")
    standard_user = rtkbaseconfig.get("general", "user")
    os.execl(script_path, "unused arg0", source_path, rtkbase_path, app.config["DOWNLOAD_FOLDER"].split("/")[-1], current_release, standard_user) 
Example #18
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 1 votes vote down vote up
def check_update(source_url = None, current_release = None, prerelease=False, emit = True):
    """
        Check if a RTKBase update exists
        :param source_url: the url where we will try to find an update. It uses the github api.
        :param current_release: The current RTKBase release
        :param prerelease: True/False Get prerelease or not
        :param emit: send the result to the web front end with socketio
        :return The new release version inside a dict (release version and url for this release)
    """
    new_release = {}
    source_url = source_url if source_url is not None else "https://api.github.com/repos/stefal/rtkbase/releases"
    current_release = current_release if current_release is not None else rtkbaseconfig.get("general", "version").strip("v")
    current_release = current_release.replace("-beta", "").replace("-alpha", "").replace("-rc", "")
    
    try:    
        response = requests.get(source_url)
        response = response.json()
        for release in response:
            if release.get("prerelease") & prerelease or release.get("prerelease") == False:
                latest_release = release.get("tag_name").strip("v").replace("-beta", "").replace("-alpha", "").replace("-rc", "")
                if latest_release > current_release and latest_release <= rtkbaseconfig.get("general", "checkpoint_version"):
                    new_release = {"new_release" : release.get("tag_name"), "url" : release.get("assets")[0].get("browser_download_url"), "comment" : release.get("body")}
                    break
             
    except Exception as e:
        print("Check update error: ", e)
        
    if emit:
        socketio.emit("new release", json.dumps(new_release), namespace="/test")
    print
    return new_release