Skip to content

Instantly share code, notes, and snippets.

@Sohaib90
Created February 15, 2023 12:04
Show Gist options
  • Save Sohaib90/07a616c0dfe8e8d4eab24d2d60ece2b1 to your computer and use it in GitHub Desktop.
Save Sohaib90/07a616c0dfe8e8d4eab24d2d60ece2b1 to your computer and use it in GitHub Desktop.
Testing the socket_io @mqtt.on_connect() callback
# Flask MQTT Web socket bridge
from flask_mqtt import Mqtt
import json
import eventlet
from flask import Flask,render_template
from flask_socketio import SocketIO, emit
from flask_bootstrap import Bootstrap
eventlet.monkey_patch()
app = Flask(__name__)
app.config['SECRET'] = 'my-secret'
app.config['MQTT_BROKER_URL'] = 'localhost'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_TLS_ENABLED'] = False
app.config['TEMPLATES_AUTO_RELOAD'] = True
mqtt = Mqtt(app)
socketio = SocketIO (app)
bootstrap = Bootstrap(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('publish')
def handle_publish(json_str):
data = json.loads(json_str)
mqtt.publish(data['topic'], data['message'], data['qos'])
@socketio.on('subscribe')
def handle_subscribe(json_str):
data = json.loads(json_str)
mqtt.subscribe(data['topic'], data['qos'])
@socketio.on('unsubscribe_all')
def handle_unsubscribe_all():
mqtt.unsubscribe_all()
@socketio.on('connect')
def on_socket_connect ():
print ('Connected to socket client.')
# mqtt.subscribe('mytopic')
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode(),
qos=message.qos,
)
emit('mqtt_message', data=data)
# This is never called:
@mqtt.on_connect()
def on_mqtt_connect (client, userdata, flags, rc):
print ('Connected to MQTT broker.')
mqtt.subscribe ('mytopic') # this would be ideal
print(mqtt.topics)
@mqtt.on_message()
def on_message(client, userdata, message):
socketio.send (message.payload.decode())
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000, use_reloader=False, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment