Description
The on_connect handler registered via @mqtt.on_connect() decorator is not invoked during the initial broker connection when using the lifespan pattern.
Root Cause
In fastmqtt.py, mqtt_startup() calls connection() which connects to the broker. The broker immediately fires __on_connect(), which checks:
if self.mqtt_handlers.user_connect_handler is not None:
self.mqtt_handlers.user_connect_handler(client, flags, rc, properties)
However, if handler registration (via decorators) occurs after mqtt_startup() completes, user_connect_handler is None at connection time, so the callback never fires.
Reproduction
@asynccontextmanager
async def lifespan(app: FastAPI):
await mqtt.mqtt_startup() # Connects immediately, on_connect fires here
yield
await mqtt.mqtt_shutdown()
@mqtt.on_connect()
def on_connect(client, flags, rc, properties):
# This never executes on initial connection
mqtt.client.subscribe("my/topic")
Expected Behavior
on_connect handler should be invoked for the initial connection, not just reconnections.
Suggested Fix
Either:
- Defer
__on_connect callback until handlers are registered
- Re-invoke handlers after
mqtt_startup() completes if connection is already established
- Document that all decorators must be processed before
mqtt_startup()
Environment
- fastapi-mqtt: 2.2.0
- Python: 3.11
Description
The
on_connecthandler registered via@mqtt.on_connect()decorator is not invoked during the initial broker connection when using the lifespan pattern.Root Cause
In
fastmqtt.py,mqtt_startup()callsconnection()which connects to the broker. The broker immediately fires__on_connect(), which checks:However, if handler registration (via decorators) occurs after
mqtt_startup()completes,user_connect_handlerisNoneat connection time, so the callback never fires.Reproduction
Expected Behavior
on_connecthandler should be invoked for the initial connection, not just reconnections.Suggested Fix
Either:
__on_connectcallback until handlers are registeredmqtt_startup()completes if connection is already establishedmqtt_startup()Environment