簡體   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