[心得] flask MQTT 連結 Socket 即時顯示MQTT傳送之訊息
Python
import eventlet from flask import Flask, render_template from flask_mqtt import Mqtt from flask_socketio import SocketIO eventlet.monkey_patch() app = Flask(__name__) app.config['SECRET'] = 'my secret key' app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com' app.config['MQTT_BROKER_PORT'] = 1883 app.config['MQTT_USERNAME'] = '' app.config['MQTT_PASSWORD'] = '' app.config['MQTT_KEEPALIVE'] = 5 app.config['MQTT_TLS_ENABLED'] = False app.config['MQTT_CLEAN_SESSION'] = True mqtt = Mqtt(app) socketio = SocketIO(app) @mqtt.on_connect() def handle_connect(client, userdata, flags, rc): mqtt.subscribe('esp/test') @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('index.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)
<--------------------------------Html-------------------------------->>
<!--Socket.IO 的 CDN 連結 一定要加integrity=....略 不然不能用--> <script crossorigin="anonymous" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" referrerpolicy="no-referrer" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!--Socket.IO 的 CDN 連結 一定要加integrity=....略 不然不能用--> <script crossorigin="anonymous" integrity="sha512-WL6WGKMPBiM9PnHRYIn5YEtq0Z8XP4fkVb4qy7PP4vhmYQErJ/dySyXuFIMDf1eEYCXCrQrMJfkNwKc9gsjTjA==" referrerpolicy="no-referrer" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/socket.io.js"></script> <script charset="utf-8" type="text/javascript"> $(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']; //TEXT可自訂變數 $('#subscribe_messages').text(text); //$('#subscribe_messages').append(text + '<br><br>'); //.append 會一直增加 <h3> </h3> }) }); </script> <h3 class="panel-title" id="subscribe_messages">這是一個測試</h3> </pre>參考:
留言
張貼留言