mqtt

package module
v1.13.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

Forge MQTT, an MQTT publish and subscribe client for Go applications built on Forge

Forge MQTT: MQTT publish and subscribe client for Go

Forge MQTT is the MQTT extension for Forge, the Go backend framework. It connects your app to an MQTT broker such as Mosquitto, EMQX or HiveMQ when the app starts, and gives you one shared client for publishing and subscribing with QoS 0, 1 and 2, retained messages, topic wildcards, a last will message, TLS and username and password auth. It fits IoT backends, device telemetry and anything else that already speaks MQTT. Under the hood it is the Eclipse Paho Go client, and you can reach the Paho client directly when you need to.

Go CI Go Reference Apache 2.0

Documentation · Quick start · Features · Publishing · Subscribing · Connection · Configuration · FAQ

Quick start

You need Go 1.26 or later and an MQTT broker. Add the extension:

go get github.com/xraph/forge@latest
go get github.com/xraph/forge/extensions/mqtt@latest
go get github.com/eclipse/paho.mqtt.golang

This app subscribes to sensors/+/temperature, logs every reading it receives, and publishes the body of POST /readings to sensors/demo/temperature:

package main

import (
	"context"
	"io"
	"log"
	"net/http"

	paho "github.com/eclipse/paho.mqtt.golang"
	"github.com/xraph/forge"
	"github.com/xraph/forge/extensions/mqtt"
)

func main() {
	app := forge.NewApp(forge.AppConfig{
		Name:        "sensors",
		HTTPAddress: ":8080",
		Extensions: []forge.Extension{
			mqtt.NewExtension(
				mqtt.WithBroker("tcp://localhost:1883"),
				mqtt.WithClientID("sensors-api"),
			),
		},
	})

	// The extension connects during startup, so subscribe once it's up.
	err := app.RegisterHookFn(forge.PhaseAfterStart, "subscribe-readings",
		func(ctx context.Context, a forge.App) error {
			m, err := forge.Inject[mqtt.MQTT](a.Container())
			if err != nil {
				return err
			}

			return m.Subscribe("sensors/+/temperature", 1, func(_ paho.Client, msg paho.Message) {
				log.Printf("%s: %s", msg.Topic(), msg.Payload())
			})
		})
	if err != nil {
		log.Fatal(err)
	}

	// POST a reading and it's published to sensors/demo/temperature.
	err = app.Router().POST("/readings", func(ctx forge.Context) error {
		m, err := forge.Inject[mqtt.MQTT](app.Container())
		if err != nil {
			return err
		}

		body, err := io.ReadAll(ctx.Request().Body)
		if err != nil {
			return err
		}

		if err := m.Publish("sensors/demo/temperature", 1, false, body); err != nil {
			return err
		}

		return ctx.JSON(http.StatusAccepted, map[string]string{"status": "published"})
	})
	if err != nil {
		log.Fatal(err)
	}

	if err := app.Run(); err != nil {
		log.Fatal(err)
	}
}

No broker yet? Mosquitto runs in Docker with one command:

docker run -d --name mosquitto -p 1883:1883 eclipse-mosquitto:2 mosquitto -c /mosquitto-no-auth.conf

Run the app and post a reading:

go mod tidy
go run .

# in another terminal
curl -X POST localhost:8080/readings -d '21.5'

You'll see sensors/demo/temperature: 21.5 in the app's log. Publish from any other MQTT client (mosquitto_pub -t sensors/kitchen/temperature -m 19) and that shows up too, because the + wildcard matches any single topic level.

Features

You need Forge MQTT gives you
To publish from handlers and jobs Publish (waits for the broker) and PublishAsync, with []byte, string or JSON payloads
To react to device messages Subscribe and SubscribeMultiple with + and # wildcards, and Unsubscribe
Delivery guarantees QoS 0, 1 or 2 per message and per subscription, plus retained messages
To know when a device drops off A last will and testament message set at connect time
Connections that heal Automatic reconnect with a capped backoff, and a persistent session when you want one
Secure brokers TLS with client certificates and a custom CA, username and password
In-flight messages that survive a restart A file-backed Paho message store
Visibility Forge metrics, GetStats counters and GetSubscriptions

The extension registers *mqtt.MQTTService by type and under the alias mqtt, and the mqtt.MQTT interface backed by the same instance. Resolve either one:

m, err := forge.Inject[mqtt.MQTT](app.Container())
svc, err := forge.Inject[*mqtt.MQTTService](app.Container())

The extension's Start connects to the broker and waits up to connect_timeout for the broker to accept. If the broker does not accept in time, the app does not start and app.Run() returns the connection error. On shutdown it disconnects with a 250 ms quiesce period so in-flight work can finish.

Publish messages

// Wait for the broker to acknowledge (for QoS 1 and 2).
err := m.Publish("devices/42/commands", 1, false, []byte("reboot"))

// Strings go out as-is. Anything else is JSON-encoded.
err = m.Publish("devices/42/state", 1, true, map[string]any{"online": true, "fw": "1.4.2"})

// Hand it to Paho and return straight away.
err = m.PublishAsync("telemetry/42", 0, false, reading)

The arguments are the topic, the QoS, the retained flag and the payload. Set retained to true and the broker keeps the last message on that topic, so a client that subscribes later gets the current value right away. That is the usual way to publish device state.

Publish blocks until Paho finishes the publish and returns its error. PublishAsync returns once the message is queued, and if delivery fails later, the extension logs the failure and you do not get an error back. Both return an error when the client isn't connected, so a publish during a reconnect fails fast.

Subscribe to topics

Handlers are Paho message handlers, func(paho.Client, paho.Message):

err := m.Subscribe("devices/+/state", 1, func(_ paho.Client, msg paho.Message) {
	log.Printf("%s is now %s", msg.Topic(), msg.Payload())
})

// Several filters, each with its own QoS, one handler.
err = m.SubscribeMultiple(map[string]byte{
	"devices/+/state": 1,
	"alerts/#":        2,
}, handleDeviceEvent)

err = m.Unsubscribe("alerts/#")

+ matches one topic level and # matches everything below a level. Paho calls your handler on its own goroutine, and with order_matters on (the default) messages reach your handlers one at a time, in the order they arrived. A slow handler holds up the next message, so if your handler does real work, hand it off to a worker and return.

GetSubscriptions() lists the topic filters and QoS the client has subscribed to, which helps when you are debugging a filter that never matches.

AddRoute(topic, handler) registers a Paho route on the connected client without sending a SUBSCRIBE packet. Use it for messages that arrive on a persistent session you subscribed to in an earlier run.

Connections and reconnects

With auto_reconnect on (the default), Paho reconnects after a dropped connection, backing off up to max_reconnect_delay. IsConnected() tells you the current state, Reconnect() forces a connect attempt, and GetStats().Reconnects counts the attempts.

Pay attention to clean_session. It defaults to true, which means the broker throws your subscriptions away when the connection drops, and the extension does not subscribe again after an automatic reconnect. If your service has to keep receiving through a network blip, turn clean sessions off and keep the client ID stable, so the broker holds the session and its subscriptions for you:

mqtt.NewExtension(
	mqtt.WithBroker("ssl://broker.example.com:8883"),
	mqtt.WithClientID("sensors-api-1"),
	mqtt.WithCleanSession(false),
)

Every instance of your service needs its own client ID. Two clients with the same ID keep disconnecting each other, and you'll see mqtt connection lost in the logs over and over.

A last will tells everyone else when your service disappears without a clean disconnect. The broker publishes it for you:

mqtt.WithWill("services/sensors-api/status", "offline", 1, true)

TLS and authentication

mqtt.NewExtension(
	mqtt.WithBroker("ssl://broker.example.com:8883"),
	mqtt.WithCredentials("sensors-api", os.Getenv("MQTT_PASSWORD")),
	mqtt.WithTLS("/etc/mqtt/client.pem", "/etc/mqtt/client-key.pem", "/etc/mqtt/ca.pem", false),
)

WithTLS takes a client certificate, its key, a CA file and a skip-verify flag. With verification on, validation requires both the certificate and the key, so connecting over TLS with only a CA file (no client certificate) does not pass validation today. Use the ssl:// or tls:// scheme in the broker URL for TLS, and ws:// or wss:// if your broker only accepts WebSockets.

Configuration

Configure the extension in code, with options or with a whole mqtt.Config built from mqtt.DefaultConfig():

cfg := mqtt.DefaultConfig()
cfg.Broker = "tcp://mosquitto:1883"
cfg.ClientID = "sensors-api-1"
cfg.CleanSession = false
cfg.DefaultQoS = 1
cfg.MessageStore = "file"
cfg.StoreDirectory = "/var/lib/sensors/mqtt"

ext := mqtt.NewExtension(mqtt.WithConfig(cfg))

The options are WithBroker, WithClientID, WithCredentials, WithTLS, WithQoS, WithCleanSession, WithKeepAlive, WithAutoReconnect, WithWill, WithMetrics, WithTracing, WithRequireConfig and WithConfig. WithQoS sets default_qos, which nothing reads yet, so pass the QoS you want on each Publish and Subscribe. NewExtensionWithConfig(cfg) does the same as NewExtension(WithConfig(cfg)).

The extension also reads extensions.mqtt from your config file, falling back to a top-level mqtt key. The file overrides the defaults and your options override the file, so a broker, client_id or clean_session: false in YAML takes effect with a plain mqtt.NewExtension().

These are the fields of mqtt.Config, with their YAML names:

Key Default What it does
broker tcp://localhost:1883 Broker URL (tcp, ssl, tls, ws or wss)
client_id forge-mqtt-client Client ID, unique per connection
username, password empty Broker credentials
clean_session true Start a fresh session on every connect
connect_timeout 30s How long Connect waits
keep_alive, ping_timeout 60s, 10s Keepalive interval and ping timeout
auto_reconnect, max_reconnect_delay true, 10m Reconnect after a drop, and the backoff cap
resume_subs true Paho's resume of stored subscribe packets on a persistent session
write_timeout 30s Timeout for a blocked write
default_qos 1 Validated (0 to 2) but not applied: you pass QoS on each call
message_channel_depth 100 Paho's internal message buffer
order_matters true Deliver messages to handlers one at a time, in order
message_store, store_directory memory, empty memory or file (a file store needs a directory)
will_enabled, will_topic, will_payload, will_qos, will_retained off Last will and testament
enable_tls, tls_cert_file, tls_key_file, tls_ca_file, tls_skip_verify off TLS
enable_metrics true Record the metrics below
enable_logging true Log connects, drops, reconnects and publishes

max_reconnect_attempts exists on the struct, but nothing reads it yet.

enable_tracing and WithTracing are deprecated and do nothing. The queue, events, conduit and kafka extensions carry trace context in message headers, but this extension can't. The paho client we use (v1.5.1) speaks MQTT 3.1.1, and that version has no user properties, so a message has nowhere to hold a traceparent. The field stays so your existing config keeps loading. If you need traces across an MQTT hop today, put the traceparent in your payload yourself. Real support has to wait for an MQTT v5 client.

With enable_metrics on, the extension records mqtt.messages.published and mqtt.messages.received counters labelled by topic, mqtt.connections labelled status=connected or status=disconnected, and mqtt.reconnects. GetStats() gives you the connection state, connect time, message counts, the time of the last message, the subscription count and reconnects.

Documentation

Topic Where
Overview and what the extension registers MQTT extension docs
Publishing, subscribing, QoS, sessions and TLS Features
Every config field and option Configuration
Method reference Functions and pkg.go.dev
How extensions load config and join the lifecycle Forge extension system

FAQ

How do I use MQTT in a Go service?

Add mqtt.NewExtension(mqtt.WithBroker(...), mqtt.WithClientID(...)) to your Forge app's extensions, resolve mqtt.MQTT with forge.Inject, and call Subscribe from an after-start hook and Publish wherever you need it. The quick start is a complete program.

Do my subscriptions survive a reconnect?

Not with the default clean session. The broker drops them when the connection goes, and the extension doesn't resubscribe. Use WithCleanSession(false) with a stable, unique client ID and the broker keeps them. See connections and reconnects.

Which QoS should I use?

QoS 0 for telemetry you can afford to lose, QoS 1 for most commands and events (your handler may see a duplicate, so make it idempotent), and QoS 2 only when a duplicate would do damage, since it costs an extra round trip per message.

Can I set connection callbacks like OnConnect?

Not through this extension yet. SetOnConnectHandler, SetConnectionLostHandler and SetReconnectingHandler are on the interface, but the client is already connected by the time you can call them, so they only log a warning. The extension's own handlers keep GetStats() and the metrics up to date, and you can read those.

Does it support MQTT 5?

No. Paho's paho.mqtt.golang speaks MQTT 3.1 and 3.1.1, and so does this extension.

Contributing

The extension is its own Go module inside the Forge repository. Test it from its directory:

cd extensions/mqtt
GOWORK=off go build ./...
GOWORK=off go vet ./...
GOWORK=off go test -short -count=1 ./...

The tests don't need a broker. Run golangci-lint run ./... from the same directory before you open a pull request, and see AGENTS.md for the toolchain, lint rules and commit format.

License

Forge MQTT is part of Forge and is available under the Apache License 2.0.

Documentation

Index

Constants

View Source
const (
	// ServiceKey is the DI key for the MQTT service.
	ServiceKey = "mqtt"
)

DI container keys for MQTT extension services.

Variables

View Source
var (
	// ErrNotConnected is returned when operation requires connection.
	ErrNotConnected = errors.New("mqtt: not connected")

	// ErrAlreadyConnected is returned when already connected.
	ErrAlreadyConnected = errors.New("mqtt: already connected")

	// ErrConnectionFailed is returned when connection fails.
	ErrConnectionFailed = errors.New("mqtt: connection failed")

	// ErrPublishFailed is returned when publish fails.
	ErrPublishFailed = errors.New("mqtt: publish failed")

	// ErrSubscribeFailed is returned when subscription fails.
	ErrSubscribeFailed = errors.New("mqtt: subscribe failed")

	// ErrUnsubscribeFailed is returned when unsubscribe fails.
	ErrUnsubscribeFailed = errors.New("mqtt: unsubscribe failed")

	// ErrInvalidQoS is returned when QoS value is invalid.
	ErrInvalidQoS = errors.New("mqtt: invalid QoS value")

	// ErrInvalidTopic is returned when topic is invalid.
	ErrInvalidTopic = errors.New("mqtt: invalid topic")

	// ErrTimeout is returned when operation times out.
	ErrTimeout = errors.New("mqtt: operation timeout")
)

Functions

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new MQTT extension.

func NewExtensionWithConfig

func NewExtensionWithConfig(config Config) forge.Extension

NewExtensionWithConfig creates a new MQTT extension with a complete config.

Types

type ClientStats

type ClientStats struct {
	Connected        bool
	ConnectTime      time.Time
	LastMessageTime  time.Time
	MessagesReceived int64
	MessagesSent     int64
	Subscriptions    int
	Reconnects       int64
}

ClientStats contains client statistics.

type Config

type Config struct {
	// Connection settings
	Broker            string        `json:"broker"              mapstructure:"broker"              yaml:"broker"`
	ClientID          string        `json:"client_id"           mapstructure:"client_id"           yaml:"client_id"`
	Username          string        `json:"username,omitempty"  mapstructure:"username"            yaml:"username,omitempty"`
	Password          string        `json:"password,omitempty"  mapstructure:"password"            yaml:"password,omitempty"`
	CleanSession      bool          `json:"clean_session"       mapstructure:"clean_session"       yaml:"clean_session"`
	ConnectTimeout    time.Duration `json:"connect_timeout"     mapstructure:"connect_timeout"     yaml:"connect_timeout"`
	KeepAlive         time.Duration `json:"keep_alive"          mapstructure:"keep_alive"          yaml:"keep_alive"`
	PingTimeout       time.Duration `json:"ping_timeout"        mapstructure:"ping_timeout"        yaml:"ping_timeout"`
	MaxReconnectDelay time.Duration `json:"max_reconnect_delay" mapstructure:"max_reconnect_delay" yaml:"max_reconnect_delay"`

	// TLS/SSL
	EnableTLS     bool   `json:"enable_tls"              mapstructure:"enable_tls"      yaml:"enable_tls"`
	TLSCertFile   string `json:"tls_cert_file,omitempty" mapstructure:"tls_cert_file"   yaml:"tls_cert_file,omitempty"`
	TLSKeyFile    string `json:"tls_key_file,omitempty"  mapstructure:"tls_key_file"    yaml:"tls_key_file,omitempty"`
	TLSCAFile     string `json:"tls_ca_file,omitempty"   mapstructure:"tls_ca_file"     yaml:"tls_ca_file,omitempty"`
	TLSSkipVerify bool   `json:"tls_skip_verify"         mapstructure:"tls_skip_verify" yaml:"tls_skip_verify"`

	// QoS settings
	DefaultQoS byte `json:"default_qos" mapstructure:"default_qos" yaml:"default_qos"`

	// Retry and reliability
	AutoReconnect        bool          `json:"auto_reconnect"         mapstructure:"auto_reconnect"         yaml:"auto_reconnect"`
	ResumeSubs           bool          `json:"resume_subs"            mapstructure:"resume_subs"            yaml:"resume_subs"`
	MaxReconnectAttempts int           `json:"max_reconnect_attempts" mapstructure:"max_reconnect_attempts" yaml:"max_reconnect_attempts"`
	WriteTimeout         time.Duration `json:"write_timeout"          mapstructure:"write_timeout"          yaml:"write_timeout"`

	// Message handling
	MessageChannelDepth uint   `json:"message_channel_depth"     mapstructure:"message_channel_depth" yaml:"message_channel_depth"`
	OrderMatters        bool   `json:"order_matters"             mapstructure:"order_matters"         yaml:"order_matters"`
	MessageStore        string `json:"message_store"             mapstructure:"message_store"         yaml:"message_store"` // "memory", "file"
	StoreDirectory      string `json:"store_directory,omitempty" mapstructure:"store_directory"       yaml:"store_directory,omitempty"`

	// Last Will and Testament
	WillEnabled  bool   `json:"will_enabled"           mapstructure:"will_enabled"  yaml:"will_enabled"`
	WillTopic    string `json:"will_topic,omitempty"   mapstructure:"will_topic"    yaml:"will_topic,omitempty"`
	WillPayload  string `json:"will_payload,omitempty" mapstructure:"will_payload"  yaml:"will_payload,omitempty"`
	WillQoS      byte   `json:"will_qos"               mapstructure:"will_qos"      yaml:"will_qos"`
	WillRetained bool   `json:"will_retained"          mapstructure:"will_retained" yaml:"will_retained"`

	// Observability
	EnableMetrics bool `json:"enable_metrics" mapstructure:"enable_metrics" yaml:"enable_metrics"`
	// EnableTracing is ignored.
	//
	// Deprecated: MQTT 3.1.1 has no user properties, so this extension can't carry trace
	// context. The field does nothing. It stays so existing config keeps loading.
	EnableTracing bool `json:"enable_tracing" mapstructure:"enable_tracing" yaml:"enable_tracing"`
	EnableLogging bool `json:"enable_logging" mapstructure:"enable_logging" yaml:"enable_logging"`

	// Config loading flags
	RequireConfig bool `json:"-" mapstructure:"-" yaml:"-"`
}

Config contains configuration for the MQTT extension.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default MQTT configuration.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for Config.

func WithAutoReconnect

func WithAutoReconnect(enable bool) ConfigOption

func WithBroker

func WithBroker(broker string) ConfigOption

func WithCleanSession

func WithCleanSession(clean bool) ConfigOption

func WithClientID

func WithClientID(clientID string) ConfigOption

func WithConfig

func WithConfig(config Config) ConfigOption

func WithCredentials

func WithCredentials(username, password string) ConfigOption

func WithKeepAlive

func WithKeepAlive(duration time.Duration) ConfigOption

func WithMetrics

func WithMetrics(enable bool) ConfigOption

func WithQoS

func WithQoS(qos byte) ConfigOption

func WithRequireConfig

func WithRequireConfig(require bool) ConfigOption

func WithTLS

func WithTLS(certFile, keyFile, caFile string, skipVerify bool) ConfigOption

func WithTracing deprecated

func WithTracing(enable bool) ConfigOption

WithTracing sets EnableTracing.

Deprecated: MQTT 3.1.1 has no user properties, so this extension can't carry trace context. The option does nothing. It stays so existing code keeps compiling.

func WithWill

func WithWill(topic, payload string, qos byte, retained bool) ConfigOption

type ConnectHandler

type ConnectHandler = mqttclient.OnConnectHandler

ConnectHandler is called when connection is established.

type ConnectionLostHandler

type ConnectionLostHandler = mqttclient.ConnectionLostHandler

ConnectionLostHandler is called when connection is lost.

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements forge.Extension for MQTT functionality. The extension is now a lightweight facade that loads config and registers services.

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks the extension health.

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the MQTT extension with the app.

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start resolves and starts the MQTT service, then marks the extension as started.

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop stops the MQTT service and marks the extension as stopped.

type MQTT

type MQTT interface {
	// Connection management
	Connect(ctx context.Context) error
	Disconnect(ctx context.Context) error
	IsConnected() bool
	Reconnect() error

	// Publishing
	Publish(topic string, qos byte, retained bool, payload any) error
	PublishAsync(topic string, qos byte, retained bool, payload any) error

	// Subscribing
	Subscribe(topic string, qos byte, handler MessageHandler) error
	SubscribeMultiple(filters map[string]byte, handler MessageHandler) error
	Unsubscribe(topics ...string) error

	// Message handling
	AddRoute(topic string, handler MessageHandler)
	SetDefaultHandler(handler MessageHandler)
	SetOnConnectHandler(handler ConnectHandler)
	SetConnectionLostHandler(handler ConnectionLostHandler)
	SetReconnectingHandler(handler ReconnectingHandler)

	// Client info
	GetClient() mqttclient.Client
	GetStats() ClientStats
	GetSubscriptions() []SubscriptionInfo

	// Health
	Ping(ctx context.Context) error
}

MQTT represents a unified MQTT client interface.

func NewMQTTClient

func NewMQTTClient(config Config, logger forge.Logger, metrics forge.Metrics) MQTT

NewMQTTClient creates a new MQTT client.

type MQTTService

type MQTTService struct {
	// contains filtered or unexported fields
}

MQTTService wraps an MQTT client and provides lifecycle management. It implements vessel's di.Service interface so Vessel can manage its lifecycle.

func NewMQTTService

func NewMQTTService(config Config, logger forge.Logger, metrics forge.Metrics) (*MQTTService, error)

NewMQTTService creates a new MQTT service with the given configuration. This is the constructor that will be registered with the DI container.

func (*MQTTService) AddRoute added in v0.9.7

func (s *MQTTService) AddRoute(topic string, handler MessageHandler)

func (*MQTTService) Client

func (s *MQTTService) Client() MQTT

Client returns the underlying MQTT client.

func (*MQTTService) Connect

func (s *MQTTService) Connect(ctx context.Context) error

func (*MQTTService) Disconnect

func (s *MQTTService) Disconnect(ctx context.Context) error

func (*MQTTService) GetClient added in v0.9.7

func (s *MQTTService) GetClient() mqttclient.Client

func (*MQTTService) GetStats added in v0.9.7

func (s *MQTTService) GetStats() ClientStats

func (*MQTTService) Health

func (s *MQTTService) Health(ctx context.Context) error

Health checks if the MQTT service is healthy.

func (*MQTTService) IsConnected

func (s *MQTTService) IsConnected() bool

func (*MQTTService) Name

func (s *MQTTService) Name() string

Name returns the service name for Vessel's lifecycle management.

func (*MQTTService) Ping

func (s *MQTTService) Ping(ctx context.Context) error

func (*MQTTService) Publish

func (s *MQTTService) Publish(topic string, qos byte, retained bool, payload any) error

func (*MQTTService) PublishAsync added in v0.9.7

func (s *MQTTService) PublishAsync(topic string, qos byte, retained bool, payload any) error

func (*MQTTService) Reconnect added in v0.9.7

func (s *MQTTService) Reconnect() error

func (*MQTTService) SetConnectionLostHandler added in v0.9.7

func (s *MQTTService) SetConnectionLostHandler(handler ConnectionLostHandler)

func (*MQTTService) SetDefaultHandler added in v0.9.7

func (s *MQTTService) SetDefaultHandler(handler MessageHandler)

func (*MQTTService) SetOnConnectHandler added in v0.9.7

func (s *MQTTService) SetOnConnectHandler(handler ConnectHandler)

func (*MQTTService) SetReconnectingHandler added in v0.9.7

func (s *MQTTService) SetReconnectingHandler(handler ReconnectingHandler)

func (*MQTTService) Start

func (s *MQTTService) Start(ctx context.Context) error

Start starts the MQTT service by connecting to broker. This is called automatically by Vessel during container.Start().

func (*MQTTService) Stop

func (s *MQTTService) Stop(ctx context.Context) error

Stop stops the MQTT service by disconnecting from broker. This is called automatically by Vessel during container.Stop().

func (*MQTTService) Subscribe

func (s *MQTTService) Subscribe(topic string, qos byte, handler MessageHandler) error

func (*MQTTService) SubscribeMultiple added in v0.9.7

func (s *MQTTService) SubscribeMultiple(filters map[string]byte, handler MessageHandler) error

func (*MQTTService) Unsubscribe

func (s *MQTTService) Unsubscribe(topics ...string) error

type MessageHandler

type MessageHandler = mqttclient.MessageHandler

MessageHandler processes incoming MQTT messages This is an alias to the paho MQTT MessageHandler for compatibility.

type ReconnectingHandler

type ReconnectingHandler = mqttclient.ReconnectHandler

ReconnectingHandler is called when client is reconnecting.

type SubscriptionInfo

type SubscriptionInfo struct {
	Topic   string
	QoS     byte
	Handler string // Handler function name
}

SubscriptionInfo contains subscription metadata.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL