Repository navigation
fix(mqtt): resync MQTT discovery after reconnect - #743
Conversation
- Initial connect failure no longer disables MQTT; paho retries - Reconnect hook re-publishes discovery entities - Atomic flag prevents overlapping discovery syncs
|
Nice catch on the root cause. With One thing needs fixing before this can merge. The rest are smaller. Blocking: we now publish to a client that has no connectionWhile paho is retrying the initial connection, // paho.mqtt.golang v1.5.1 client.go:197
case s == connected:
return true
case c.options.ConnectRetry && s == connecting:
return trueEvery method on Worse,
Those stored messages do not show up later either. One line in func (c *Client) IsConnected() bool {
// IsConnectionOpen is only true when a connection is actually established.
// IsConnected also returns true during ConnectRetry backoff.
return c.client != nil && c.client.IsConnectionOpen()
}
|
Summary
When the initial MQTT connection fails (e.g., broker unreachable at startup), the paho client is configured with
SetConnectRetry(true)andSetAutoReconnect(true), so it keeps retrying in the background. However, the application previously nulled out the publisher and skipped registeringMqttPublisherMiddlewareon the initial connect failure, so even a successful reconnect never restored publishing or discovery sync — a restart was required.This PR keeps the MQTT integration alive across connect failures and re-syncs all discovery entities whenever the connection is (re)established.
Type of Change
Related Issues
None.
Changes Made
webapp/backend/pkg/web/server.go: do not null out the publisher when the initial connect fails; always registerMqttPublisherMiddlewareso publishing resumes automatically once paho reconnectswebapp/backend/pkg/web/server.go: register a reconnect hook before connecting so both the initial connection and every automatic reconnect trigger a full device syncwebapp/backend/pkg/mqtt/client.go: addSetOnReconnectcallback invoked on every (re)established connectionwebapp/backend/pkg/mqtt/publisher.go: exposeSetOnReconnectedto forward the callbackwebapp/backend/pkg/web/server.go: guardloadInitialMqttDatawith anatomic.Boolto prevent concurrent duplicate syncsTesting
go build ./...inwebapp/backendgo test ./pkg/mqtt/... ./pkg/web/...and fullgo test ./...passgo vet ./pkg/mqtt/... ./pkg/web/...cleanBehavior verified: after a broker outage the client reconnects in the background, publishes the online availability state, and re-syncs discovery/state for all devices without a restart
I have tested this locally
I have added/updated tests that prove my fix/feature works
All existing tests pass
Checklist
Screenshots (if applicable)
Not applicable.
Additional Notes
None.