1

我一般是 JavaScript 和 HTML 的新手,所以我可能有一些愚蠢的问题......

我正在使用 Flask 显示一个图表,其中包含来自 Raspberry pi3 上的传感器的一些值。传感器通过串行端口连接。我想将我从串口读取的值传递给 index.html,这是我有图形的 javascript 代码(用 Rgraph 制作)的模板。

这是带有烧瓶和端口读数的 main.py。

from flask import Flask,render_template
import serial

app = Flask(__name__)
ser = serial.Serial('/dev/ttyACM0', 9600)

@app.route('/')
def hello_world():
return render_template("index.html")

#here I read one value from the serial port
@app.route('/getdata')
def test():
    return ser.readline()

if __name__ == '__main__':
    app.run()

我尝试使用的 index.html 模板是这里(在 github 上)。javascript 会生成一些随机数(从第 66 行到第 72 行),但我希望它从页面“/getdata”中读取一个数字并将其推送到数据数组中。

我考虑过使用 GET-POST 方法,但它变得相当复杂。也许有更简单的解决方案?或者,也许(但我认为这是不可能的),我可以直接从 javascript 读取串口?或者,也许,我做错了一切,我需要把所有东西都扔出窗外?

4

2 回答 2

1

一旦烧瓶呈现模板,您就无能为力了。它并不真正支持推送请求(至少据我所知不支持),但执行 Ajax 请求并不难

ajax_params = {
        url: '/getdata',
        type: 'GET',
        cache: false,
        dataType: 'json',
        error: function(jqXHR, status, error) {
            console.log("Ajax error " + error);
            console.log("status " + status);
            console.log(jqXHR);
        },
        success: datacb
    };

function datacb (resp, status, jqXHR) {
     /* update code here */
     console.log(resp);

     /* you may want to sleep here */

     $.ajax(ajax_params);
}

$.ajax(ajax_params);
于 2017-05-17T16:21:26.003 回答
1

除非您想在不重新加载 index.html 页面的情况下更新数据,否则您可以尝试以下操作:

from flask import Flask,render_template
import serial

app = Flask(__name__)
ser = serial.Serial('/dev/ttyACM0', 9600)

@app.route('/')
def hello_world():
    servalue = test();
    return render_template("index.html", value=servalue)

#here I read one value from the serial port
@app.route('/getdata')
def test():
    return ser.readline()

if __name__ == '__main__':
    app.run()

如果您想在不重新加载索引页面的情况下更新数据,您可能必须使用 AJAX,正如@debhand 建议的那样。

于 2017-05-17T16:33:26.037 回答