使用 Flask-websockets 不在异步网页上更新文本

问题描述

我正在尝试使用 Python Flask 服务器和来自 Arduino 设备的 MQTT 值使此网页异步更新。所有值都通过并正确保存,但这些值未显示在网页上。

我认为这可能与尝试使用 $('#warmity').text 写入 id 标签有关

这是相关的 HTML:

   <script type="text/javascript" charset="utf-8">
      $(document).ready(function() {
        var socket = io.connect('http://' + document.domain + ':' + location.port);
        socket.on('connect',function() {
          socket.emit('my event',{data: 'I\'m connected!'});
        });
        socket.on('dht_temperature',function(msg) {
      var nDate = new Date();
          $('#readingsUpdated').text(nDate.getHours() + 'h:' + nDate.getMinutes() +
             'm:' + nDate.getSeconds() + 's').html();
          $('#temperature').text(msg.data).html();
        });
        socket.on('dht_humidity',function(msg) {
          $('#humidity').text(msg.data).html();
        });
      });
   </script>
   
<body>
   <h1>RPi Web Server - ESP8266 MQTT</h1>
   {% for pin in pins %}
   <h2>{{ pins[pin].name }}
   {% if pins[pin].state == 'True' %}
      is currently <strong>on</strong></h2><div class="row"><div class="col-md-2">
      <a href="/esp8266/{{pin}}/0" class="btn btn-block btn-lg btn-default" role="button">Turn off</a></div></div>
   {% else %}
      is currently <strong>off</strong></h2><div class="row"><div class="col-md-2">
      <a href="/esp8266/{{pin}}/1" class="btn btn-block btn-lg btn-primary" role="button">Turn on</a></div></div>
   {% endif %}
   {% endfor %}
   <h3>DHT Readings (updated <span id="readingsUpdated"></span>)</h3>
   <h3>Temperature: <span id="temperature"></span>ºC</h3>
   <h3>Humidity: <span id="humidity"></span>%</h3>
</body>
</html>

这里是 Python 脚本

import paho.mqtt.client as mqtt
from flask import Flask,render_template,request
from flask_socketio import SocketIO,emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client,userdata,flags,rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("/esp8266/temperature")
    client.subscribe("/esp8266/humidity")

# The callback for when a PUBLISH message is received from the ESP8266.
def on_message(client,message):
    #socketio.emit('my variable')
    print("Received message '" + str(message.payload) + "' on topic '"
        + message.topic + "' with QoS " + str(message.qos))
    if message.topic == "/esp8266/temperature":
        print("temperature update")
    socketio.emit('dht_temperature',{'data': message.payload})
    if message.topic == "/esp8266/humidity":
        print("humidity update")
    socketio.emit('dht_humidity',{'data': message.payload})

mqttc=mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("localhost",1883,60)
mqttc.loop_start()

# Create a dictionary called pins to store the pin number,name,and pin state:
pins = {
   4 : {'name' : 'GPIO 4','board' : 'esp8266','topic' : 'esp8266/4','state' : 'False'},5 : {'name' : 'GPIO 5','topic' : 'esp8266/5','state' : 'False'}
   }

# Put the pin dictionary into the template data dictionary:
templateData = {
   'pins' : pins
   }

@app.route("/")
def main():
   # Pass the template data into the template main.html and return it to the user
   return render_template('main.html',async_mode=socketio.async_mode,**templateData)

# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<board>/<changePin>/<action>")
def action(board,changePin,action):
   # Convert the pin from the URL into an integer:
   changePin = int(changePin)
   # Get the device name for the pin being changed:
   devicePin = pins[changePin]['name']
   # If the action part of the URL is "1" execute the code indented below:
   if action == "1" and board == 'esp8266':
      mqttc.publish(pins[changePin]['topic'],"1")
      pins[changePin]['state'] = 'True'
   if action == "0" and board == 'esp8266':
      mqttc.publish(pins[changePin]['topic'],"0")
      pins[changePin]['state'] = 'False'
   # Along with the pin dictionary,put the message into the template data dictionary:
   templateData = {
      'pins' : pins
   }
   return render_template('main.html',**templateData)

@socketio.on('my event')
def handle_my_custom_event(json):
    print('received json data here: ' + str(json))

if __name__ == "__main__":
   socketio.run(app,host='0.0.0.0',port=8181,debug=True)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)