我正在使用Flask-MQTT
并且可以接收消息。我一直在关注以下guide。收到消息时,我想在模板中显示数据,但无法这样做。下面是我的代码。
from flask import Flask, render_template
from flask_mqtt import Mqtt
app = Flask(__name__, template_folder='./views')
app.config['MQTT_BROKER_URL'] = 'URL'
app.config['MQTT_BROKER_PORT'] = 0000
app.config['MQTT_REFRESH_TIME'] = 1.0
mqtt = Mqtt(app)
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
mqtt.subscribe('#')
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
@app.route('/')
def index():
return render_template('graph.html')
如何在我创建的graph.html
模板中显示来自MQTT的新数据?
答案 0 :(得分:1)
使用套接字允许服务器与Web客户端/模板之间的实时通信。 Flask-MQTT documentation已经提供了一个很好的示例,说明如何使用Flask-SocketIO来实现此服务器端。在客户端,请使用Javascript library of SocketIO。
服务器端,每次接收到MQTT消息时,它都应使用mqtt_message
将socketio.emit()
事件(包含消息数据)推送到套接字。
客户端socket.on()
用于侦听mqtt_message
事件并处理新事件。
以下是基于您的代码的基本工作实现。我在这里连接到test.mosquitto.org
进行测试。每次接收到新的MQTT消息时,其数据都会在新行中附加到模板(并记录到JavaScript控制台)。
服务器端:
import eventlet
from flask import Flask, render_template
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
eventlet.monkey_patch()
app = Flask(__name__, template_folder='./views')
app.config['MQTT_BROKER_URL'] = 'test.mosquitto.org'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_REFRESH_TIME'] = 1.0
mqtt = Mqtt(app)
socketio = SocketIO(app)
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
mqtt.subscribe('#')
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
# emit a mqtt_message event to the socket containing the message data
socketio.emit('mqtt_message', data=data)
@app.route('/')
def index():
return render_template('graph.html')
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(level, buf)
socketio.run(app, host='localhost', port=5000, use_reloader=True, debug=True)
客户端(模板views/graph.html
):
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
// listen for mqtt_message events
// when a new message is received, log and append the data to the page
socket.on('mqtt_message', function(data) {
console.log(data);
var text = '(' + data['topic'] + ' qos: ' + data['qos'] + ') ' + data['payload'];
$('#subscribe_messages').append(text + '<br><br>');
})
});
</script>
<div id="subscribe_messages"></div>
是这样的: