Documentation
¶
Overview ¶
Package mqtt provides a thread-safe MQTT client handler for Go.
This package wraps the Eclipse Paho MQTT library to provide a simple, safe interface for connecting to a broker, publishing messages, and handling reconnections.
Features:
- Thread-safe Handler for a single MQTT client
- Automatic reconnect and retry on connection loss
- Synchronous publish with timeout support, refused while no connection is open
- Optional callbacks for connection and disconnection events
- Optional logger for the connection errors the broker reports at startup
- Safe initialization and shutdown of the client
Example usage ¶
handler, err := mqtt.New("tcp://broker:1883", "clientID",
mqtt.WithOnConnected(func() {
log.Println("MQTT connected")
}),
mqtt.WithOnConnectionLost(func(err error) {
log.Println("MQTT connection lost:", err)
}),
mqtt.WithLogger(slog.Default()),
)
if err != nil {
log.Fatal(err)
}
defer handler.Disconnect()
msg := mqtt.Message{
Topic: "sensors/temperature",
Payload: []byte("22.5"),
Qos: 1,
}
if err := handler.Publish(msg); err != nil {
log.Println("Publish failed:", err)
}
Publish only hands a message to the broker while a connection is actually open; otherwise it returns ErrNotConnected rather than dropping the message silently. Use IsConnectionOpen to ask for that state, not IsConnected.
Example (Usage) ¶
Example_usage connects to a broker and publishes one message.
It deliberately carries no "Output:" comment: it needs a real broker, so it is compiled as documentation but never executed by go test. Test_Example in mqtt_example_test.go runs the same steps when MQTT_TEST_BROKER names one.
package main
import (
"log"
"log/slog"
"github.com/womat/mqtt"
)
func main() {
// Credentials and TLS come from the URL, e.g. "ssl://user:password@broker:8883".
// New does not fail on an unreachable broker: it retries in the background.
h, err := mqtt.New("tcp://broker:1883", "sensor-livingroom",
mqtt.WithLogger(slog.Default()),
mqtt.WithOnConnected(func() { slog.Info("MQTT connected") }),
mqtt.WithOnConnectionLost(func(err error) { slog.Warn("MQTT connection lost", "error", err) }),
)
if err != nil {
log.Fatal(err)
}
defer h.Disconnect()
// Publish refuses to send while no connection is open (ErrNotConnected)
// rather than letting Paho drop the message silently.
err = h.Publish(mqtt.Message{
Topic: "sensors/livingroom/temperature",
Payload: []byte("22.5"),
Qos: 1,
})
if err != nil {
log.Println("publish failed:", err)
}
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrClientNotInitialized = errors.New("mqtt client not initialized") ErrTopicEmpty = errors.New("mqtt topic must not be empty") ErrInvalidQos = errors.New("mqtt qos must be 0, 1 or 2") ErrNotConnected = errors.New("mqtt not connected to the broker") ErrTimeout = errors.New("publish timeout") )
Functions ¶
This section is empty.
Types ¶
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler manages a thread-safe MQTT client connection.
func New ¶
New creates and initializes a new MQTT Handler for the given broker.
It sets up the client with automatic reconnect and retry on connection loss. The initial connection is attempted synchronously with a timeout. If it fails or times out, the Handler is still returned and will retry in the background, so that a service can start while its broker is down.
Optional callbacks for connection events can be provided via opts.
Parameters:
- broker: the MQTT broker URL (e.g., "tcp://localhost:1883"); credentials go into the URL ("tcp://user:password@host:1883"), and the schemes ssl://, tls:// and mqtts:// connect with TLS
- clientID: a unique client identifier
- opts: optional functional options, e.g. WithOnConnected, WithOnConnectionLost
Returns:
- *Handler: the initialized MQTT Handler, ready to use
- error: always nil; a failed initial connection is not an error here, it is retried in the background. Pass WithLogger to see it, or ask IsConnectionOpen whether the broker was actually reached.
func (*Handler) Disconnect ¶
func (m *Handler) Disconnect()
Disconnect safely ends the connection to the MQTT broker.
This method is thread-safe and sets the internal client to nil before actually disconnecting, so that concurrent Publish or Connect calls will see the client as uninitialized.
The disconnect uses a quiesce period to allow pending work to complete. If no client is initialized, this method does nothing.
func (*Handler) IsConnected ¶
IsConnected reports whether the MQTT client considers itself connected.
Because New enables both auto-reconnect and connect-retry, this is true while a connection is merely pending as well — including a first connect that has never succeeded. It answers "is this handler still trying?", not "is the broker reachable?"; for the latter use IsConnectionOpen.
func (*Handler) IsConnectionOpen ¶
IsConnectionOpen reports whether a connection to the broker is open right now. Unlike IsConnected it is false while a connect or reconnect is still pending, which makes it the state to check before publishing.
func (*Handler) Publish ¶
Publish sends a message to the MQTT broker synchronously. It waits up to publishTimeout for the broker to acknowledge the message.
The message is only handed to the client while a connection is actually open; otherwise Publish returns ErrNotConnected. That guard is not redundant: while Paho is reconnecting it discards a QoS 0 publish without reporting an error, and stores a QoS 1 or 2 publish in a session that the next connect clears. Without the guard, both cases would look like success or like a timeout for a message that is already gone.
type Option ¶
type Option func(*Handler)
Option configures a Handler.
func WithLogger ¶
WithLogger sets an optional logger. It is used for the connection errors that New would otherwise swallow; nothing else in this package logs.
func WithOnConnected ¶
func WithOnConnected(fn func()) Option
WithOnConnected sets a callback that is called when the client connects.
func WithOnConnectionLost ¶
WithOnConnectionLost sets a callback that is called when the connection is lost.