Solution
# app.py
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
mqtt = Mqtt(app)
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('publish')
def handle_publish(data):
mqtt.publish('top1', data['message'])
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
socketio.emit('mqtt_message', data=data)
if __name__ == '__main__':
mqtt.subscribe('top1')
socketio.run(app, host='0.0.0.0', port=5000, use_reloader=False, debug=True)
// connect and send 2 messages into top1
const s = io.connect('http://' + document.domain + ':' + location.port);
s.emit("publish", {"message": "hello1"});
s.emit("publish", {"message": "hello2"});
// you will see the messages into all tabs
# app.py
import datetime
import json
import time
from queue import Queue
import eventlet
from flask import Flask, render_template, Response
from flask_mqtt import Mqtt
eventlet.monkey_patch()
QUEUE = Queue()
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
mqtt = Mqtt(app)
mqtt.subscribe('top1')
@app.route('/')
def index():
return render_template('index.html')
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
QUEUE.put(data)
@app.route('/publish')
def publish():
mqtt.publish('top1', json.dumps({'dt': str(datetime.datetime.now())}).encode())
return 'ok'
@app.route('/chart-data')
def chart_data():
def events():
while True:
message = QUEUE.get()
if message is None:
time.sleep(1)
continue
yield "data: %s\n\n" % str(message)
return Response(events(), content_type='text/event-stream')