With Flask-MQTT and Flask-SocketIO, I'm trying to emit a socket message outside from the Flask-SocketIO event context to all connected clients, upon reception of an MQTT message. Yet, when doing so, the messages never seem to reach the clients.
It appears this has been a long known issue, but using app.app_context()
does not seem to work for me either.
Here is what I have for now:
app = Flask(__name__)
[app.config ...]
cors = CORS(app,resources={ "/*": {"origins":"*"} })
mqtt = Mqtt(app)
socketio = SocketIO(app)
[...]
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
with app.app_context():
# Send socket to all connected clients.
# Not working for some reasons...
socketio.emit("mqtt_message")
@socketio.on("connect")
def handle_socketio_connect():
# This works.
emit("hello")
if __name__ == "__main__":
socketio.run(app, [...] )
Packages versions:
- Flask-SocketIO, 3.0.1
- Flask-MQTT, 1.0.3
- Eventlet, 0.23.0