好吧,这让我有点发疯了。我只想将一些MQTT数据记录到网页上。我正在使用websockets,但无法使浏览器客户端从服务器接收任何信息。我正在使用Flask w / Flask-MQTT和Flask-SocketIO。我现在只想在控制台上打印内容,大多数示例是“让用户使用表单订阅频道”。所以我有点迷路,因为我通常不使用websocket。
我想念什么?
服务器端:
import os
import eventlet
import json
from flask import Flask, render_template
from flask_mqtt import Mqtt
from flask_socketio import SocketIO, send, emit
app = Flask(__name__)
socketio = SocketIO(app)
mqtt = Mqtt(app)
app.config['MQTT_BROKER_URL'] = '127.0.0.1' # use the free broker from HIVEMQ
app.config['MQTT_BROKER_PORT'] = 1883 # default port for non-tls connection
app.config['MQTT_KEEPALIVE'] = 5 # set the time interval for sending a ping to the broker to 5 seconds
app.config['MQTT_TLS_ENABLED'] = False # set TLS to disabled for testing purposes
################### WEB VIEWS ###########################
@app.route('/')
def index():
return render_template('index.html')
################# FLASK MQTT ######################################
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
mqtt.subscribe('test/topic')
print("!connect",client,userdata,flags,rc)
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print("!onmessage",data)
socketio.emit('mqtt_message', data=data)
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(level, buf)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5005, use_reloader=False, debug=True)
客户端:
<html>
<head>
<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">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log("connected", socket);
});
socket.on('mqtt_message', function(data) {
console.log(data);
});
</script>
</head>
<body>
<p>nothing yet.</p>
</body>
</html>