简体   繁体   English

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

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

I am building a simple app.我正在构建一个简单的应用程序。 Basically, it presents the temperature of the Raspberry Pi in a Website.基本上,它在网站中显示 Raspberry Pi 的温度。 Eventually, I plan to add more functionality to it.最终,我计划为其添加更多功能。 So basically after trying with WebSockets and not succeeding, I googled around but didn't find any answer.所以基本上在尝试使用 WebSockets 并没有成功之后,我用谷歌搜索但没有找到任何答案。 I want to update the temperature like every 2 or 5 seconds.我想每 2 或 5 秒更新一次温度。

I have tried some tutorials on WebSockets, but it didn't update the values in the web page.我已经尝试了一些关于 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 file: 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>

There is one error message but I don't know what it means:有一条错误消息,但我不知道它是什么意思:

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

Here's an example of how I would solve this:这是我如何解决此问题的示例:

I would probably split these scripts into .js files, but well.我可能会将这些脚本拆分为.js文件,但很好。 getTemp() asks for a new temperature to the server, writeTemp() updates the HTML with the new value, and addTimer() runs writeTemp() every 5 seconds. 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>

Okay, so the client sends an XMLHttpRequest (basically the same as a curl request, I would say) to the server each 5 seconds which looks like localhost/info/temp .好的,所以客户端每 5 秒向服务器发送一个 XMLHttpRequest(与curl请求基本相同,我会说),它看起来像localhost/info/temp

We serve this data by reading directly from a file which has the appropriate value from our webserver.我们通过直接从我们的网络服务器中具有适当值的文件中读取来提供这些数据。

@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

Of course, this file is probably empty as for now, so we will generate this with a background timer:当然,这个文件现在可能是空的,所以我们将使用后台计时器生成它:

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

You can move this script into measureTemp.sh , and then subthread it from your python initalisation setup, if you want to, or add it as a service on bootup after you have chmod +x measureTemp.sh 'd it.您可以将此脚本移动到measureTemp.sh ,然后从您的 python 初始化设置中将其子线程化(如果需要),或者在您使用chmod +x measureTemp.sh后在启动时将其添加为服务。

Alternatively you could just measure /sys/class/thermal/thermal_zone0/temp , directly, if you have permissions to read that.或者,如果您有阅读权限,您可以直接测量/sys/class/thermal/thermal_zone0/temp

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

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