简体   繁体   中英

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. 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. I want to update the temperature like every 2 or 5 seconds.

I have tried some tutorials on WebSockets, but it didn't update the values in the web page.

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:


<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. getTemp() asks for a new temperature to the server, writeTemp() updates the HTML with the new value, and addTimer() runs writeTemp() every 5 seconds.

<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 .

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.

Alternatively you could just measure /sys/class/thermal/thermal_zone0/temp , directly, if you have permissions to read that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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