【问题标题】:Updating jquery with realtime sensor data through flask通过烧瓶使用实时传感器数据更新 jquery
【发布时间】:2020-12-15 11:09:56
【问题描述】:

我正在尝试通过烧瓶将实时数据从传感器发送到前端通过 jquery。现在我的脚本使用setInterval(..., 1000);通过ajax请求更新数据。

但是,我想在从烧瓶接收到新的传感器数据时更新 jquery 请求,因为传感器的帧速率不同并且很难设置特定的时间间隔以使其成为实时。

通过@app.route('/data')发送新数据时,是否可以在jquery代码中使用某种信号?

Python 脚本:

from flask import Flask,render_template,url_for,request,redirect, make_response, session
import json
from bluepy import btle
from bluepy.btle import Scanner, DefaultDelegate

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def main():

    return render_template('index.html')

@app.route('/data', methods=["GET", "POST"])
def data():

    # Connect to sensor and get current data value (Bluepy stuff)
    bluetooth_addresses = "d4:ca:3d:32:52"
    periph = btle.Peripheral(bluetooth_addresses)
    periph.writeCharacteristic(44, b"\x01\x00", withResponse=True)
    data = periph.getData() # data is a single value (e.g 0.23)
   
    # Keep receiving data from sensor when ready
    # while True:
    #     if periph.waitForNotifications(1.0):
    #         data = periph.getData() # data is a single value (e.g 0.23)

    response = make_response(json.dumps(data))
    response.content_type = 'application/json'
    return response

if __name__ == "__main__":
    app.run(debug=True)

html:

<!DOCTYPE html>
<html  lang="en" dir="ltr">
<head>
    <meta charset="utf-8">

    <title>Flask App </title>

    <!-- Bootstraps Java Scipts Links -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap4.4.1.min.css') }}">
    <script src="{{ url_for('static', filename='js/jquery3.4.1.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/popper1.16.0.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/bootstrap4.4.1.min.js') }}"></script>
</head>

<body>
    <button type="button" class="btn btn-primary" onclick="start_button()" id="start_button">Start</button>

    <script>
        var start_button = function(){
            $.get('/start',
                function(){
                    function log_data() {
                        $.ajax({
                          type: "GET",
                          url:'/data',
                          dataType: 'json',
                          success: function (result) {
                              console.log(result);
                          }
                        });
                    }
                    timer = setInterval(log_data, 1000/15);
                }
            )
        }
    </script>
</body>
</html>

【问题讨论】:

    标签: jquery flask


    【解决方案1】:

    对于实时数据,使用 'text/event-stream' MIME 类型

    return Response(generate_random_data(), mimetype='text/event-stream')

    yield a server-side event(我在下面的sn-p中使用了这种类型)

    这是我使用的前端sn-p的一部分:

            const source = new EventSource("/data");
    
            source.onmessage = function (event) {
                const data = JSON.parse(event.data);
                // data.value is the realtime value
                
            }
    

    【讨论】:

      猜你喜欢
      • 2018-08-11
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2022-08-18
      • 2017-05-17
      • 2019-01-25
      相关资源
      最近更新 更多