【发布时间】: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>
【问题讨论】: