[Python] Socket.Io non consistent Data Stream

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am having trouble using socketio together with flask to display 'live' data. I receive data on my webapp, but it is very inconsistent. It is not predictable when Data will arrive.

    I am trying to display a simple sin curve for testing and it is turning out unrecognizable. Here I have logged some data that arrived as an example:

    Live data received: Object { 1 time: 194.79929999929748, value: 0.021253876945582027}
    Live data received: Object { 1 time: 240.1999998299949, value: 0.9913219514756684}
    Live data received: Object { 1 time: 285.79999999999284, value: 0.02482940667349397}
    Live data received: Object { 1 time: 331.19939999398926, value: -0.9718055527309507}
    Live data received: Object { 1 time: 331.39998899998925, value: -0.9892221305516083}
    Live date received: Object { 1 time: 376.79992999928018, value: -0.1899270803974535}
    Live data received: Object { 1 time: 422.99999999998454, value: 0.8979144124613327}
    Live data received: Object { 1 time: 468.3839999232813, value: -0.7849990633617221}
    Live data received: Object { 1 time: 514.2293939999801, value: -0.4638514751873342}
    Live date received: Object { 1 time: 514.9999999999861, value: 0.21939584858396854}
    Live date received: Object { 1 time: 561.1999999999966, value: 0.9167452046090582}
    Live data received: Object { 1 time: 561.3999999999907, value: 0.8105467146602126}


    The code printed by the python code drirectly in the console seems to be pretty consistent spitting out a new value every 100ms.

    My backend python code producing the sin wave looks like this:

    app = Flask(__name__)
    socketio = SocketIO(app)

    def generate_live_data():
    t = 0
    while True:
    time.sleep(0.1)
    t += 0.1
    value = math.sin(t)
    socketio.emit("live_data", {"time": t, "value": value})
    print(f"Live data received:", data)

    thread = Thread(target=generate_live_data, daemon=True)
    thread.start()

    if __name__ == "__main__":
    socketio.run(app, host="0.0.0.0", port=5000, debug=True)


    And my Frontent java-script framework looks like this:

    socket.on("live_data", data => {
    if (liveChart) {
    liveChart.data.labels.push(data.time.toFixed(1));
    liveChart.data.datasets[0].data.push(data.value.toFixed(2));
    if (liveChart.data.labels.length > 50) {
    liveChart.data.labels.shift();
    liveChart.data.datasets[0].data.shift();
    }
    liveChart.update();
    }
    });


    Is there anything wrong with my code, that might impact this slow and irregular updating of the chart?

    Continue reading...

Compartilhe esta Página