繁体   English   中英

动态更新 Flask 应用程序中的文本以获取温度读数

[英]Dynamically updating the text in a Flask App for Temperature Readings

我正在构建一个简单的应用程序。 基本上,它在网站中显示 Raspberry Pi 的温度。 最终,我计划为其添加更多功能。 所以基本上在尝试使用 WebSockets 并没有成功之后,我用谷歌搜索但没有找到任何答案。 我想每 2 或 5 秒更新一次温度。

我已经尝试了一些关于 WebSockets 的教程,但它没有更新网页中的值。

from flask import Flask,render_template,request
from subprocess import PIPE, Popen
from flask_socketio import SocketIO
import threading
import time
import os
temp = 0
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

def get_temp():
    while(1):
        process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
        output, _error = process.communicate()
        socketio.emit('temp',{'temp',output})
        temp=output
        time.sleep(2000)
        print("DID")

x = threading.Thread(target=get_temp)
x.start()
print("START")
@app.route('/')
def hello_world():
    return render_template('st.html',raspi_model='3',raspi_temp=9)

st.html文件:


<html>
<body>
<h1>Raspberry Pi Control Page</h1>
<hr>
<p>Raspberry Pi Model : {{raspi_model}}</p>

<p id="asd">Current Tempreature : {{raspi_temp}}</p>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
    var socket = io();
    document.getElementById(id).innerHTML = socket.data

</script>
</body>
</html>

有一条错误消息,但我不知道它是什么意思:

WARNING in __init__: Flask-SocketIO is Running under Werkzeug, WebSocket is not available.

这是我如何解决此问题的示例:

我可能会将这些脚本拆分为.js文件,但很好。 getTemp()向服务器请求一个新的温度, writeTemp()用新值更新 HTML, addTimer() writeTemp()每 5 秒运行writeTemp()

<html>
    <head>
        <script type="text/javascript">
            function getTemp() {
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.open( "GET", "http://localhost/info/temp", false );
                xmlHttp.send( null );
                return xmlHttp.responseText;
            }
            function writeTemp() {
                var temperature = getTemp();
                document.getElementById("temperatureLabel").innerText = temperature + "C";
            }
            function addTimer() {
                setInterval(writeTemp, 5000)
            }
        </script>
    </head>
    <body onload="addTimer();">
        Temperature: <span id="temperatureLabel"></span>
    </body>
</html>

好的,所以客户端每 5 秒向服务器发送一个 XMLHttpRequest(与curl请求基本相同,我会说),它看起来像localhost/info/temp

我们通过直接从我们的网络服务器中具有适当值的文件中读取来提供这些数据。

@app.route("/info/<key>")
def info(key):
    if key == "temp":
        with open("/info/cpu_temp.dat", "r") as f:
            temp = f.read()
        return temp
    else:
        return "" # empty results if not valid

当然,这个文件现在可能是空的,所以我们将使用后台计时器生成它:

while true; do vcgencmd measure_temp > info/temp; sleep 5; done;`

您可以将此脚本移动到measureTemp.sh ,然后从您的 python 初始化设置中将其子线程化(如果需要),或者在您使用chmod +x measureTemp.sh后在启动时将其添加为服务。

或者,如果您有阅读权限,您可以直接测量/sys/class/thermal/thermal_zone0/temp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM