Version: v0.7.2 Latest Latest

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

Go to latest
Published: Jun 6, 2023 License: Apache-2.0 Imports: 18 Imported by: 2



Package mqtt defines how devices map onto an MQTT transport. It also includes a number of MQTT related helpers, like configuration flags for CLI libraries



This section is empty.


View Source
var (
	ErrNoAddress        = errors.New("at least one address must be provided")
	ErrTopicInvalidChar = errors.New("topic contains invalid characters")
	ErrNoConfig         = errors.New("no config provided")


func Flags

func Flags(str FlagStrFunc, b FlagBoolFunc) func() (*Config, error)

Flags will use the provided callbacks to set up mqtt-specific cli arguments:

mqtt.address   (localhost:1883) - Address of server                (MQTT_ADDRESS)
mqtt.username                   - Username                         (MQTT_USERNAME)
mqtt.password                   - Password                         (MQTT_PASSWORD)
mqtt.tls                        - Enable TLS (bool flag)           (MQTT_TLS)
  mqtt.tls-insecure             - Skip cert validation (bool flag) (MQTT_TLS_INSECURE)                       - CN of server (i.e. hostname)     (MQTT_COMMON_NAME)                       - Path to authority certificate    (MQTT_CA_PATH)
  mqtt.cert                     - Path to client certificate       (MQTT_CERT_PATH)
  mqtt.key                      - Path to certificate key          (MQTT_KEY_PATH)
topic.announce                  - Topic for announcements          (HEMTJANST_TOPIC_ANNOUNCE)                  - Topic for discovery              (HEMTJANST_TOPIC_DISCOVER)
topic.leave                     - Topic for leaving                (HEMTJANST_TOPIC_LEAVE)

The callback interfaces are compatible with the standard library flag-package. If using the flag-package, you can easily set up the mqtt transport with CLI flags by doing this

(Note that it's important to call mqtt.Flags() before flag.Parse())

package main
import (
func main() {
  myCustomFlag := flag.String("custom", "", "Set up your own flags here")
  mqCfg := mqtt.MustFlags(flag.String, flag.Bool)
  transport, err := mqtt.New(context.TODO(), mqCfg())

func MustFlags

func MustFlags(str FlagStrFunc, b FlagBoolFunc) func() *Config

func TopicTest

func TopicTest(topic, sub string) bool


type Code added in v0.6.0

type Code byte

Code is a wrapper for mqtt codes with utils for displaying the error. The type does not check if the code is an error or not, it always implements the error interface for convenience

func (Code) Error added in v0.6.0

func (c Code) Error() string

Error returns the same information as String(), with the prefix "mqtt: "

func (Code) String added in v0.6.0

func (c Code) String() string

String returns the same information as Text(), with the integer code appended

func (Code) Text added in v0.6.0

func (c Code) Text() string

Text returns a textual representation of the code

type Config

type Config struct {
	// ClientID will be used as mqtt Client ID and LastWillID
	ClientID string

	// Address is a slice of MQTT addresses (host:port / ip:port)
	Address []string

	// Username used to authenticate to MQTT
	Username string

	// Password used to authenticate to MQTT
	Password string

	// TLS configuration
	TLS *tls.Config

	// AnnounceTopic is the prefix announcements will have. Default is "announce"
	AnnounceTopic string

	// DiscoverTopic is where the library will send or listen for discoveries. Default is "discover"
	DiscoverTopic string

	// LeaveTopic is where the will is sent when the client exists. Default is "leave"
	LeaveTopic string

	// DiscoverDelay is the time between first subscribing to announcements, and sending a discover.
	// The delay should be long enough to be able to receive all retained announcements, but not too long
	// to make initial startup too slow. Default is 5 seconds
	DiscoverDelay time.Duration

type Err added in v0.6.0

type Err string
const (
	ErrIsAlreadyRunning Err = "already running"
	ErrIsCancelled      Err = "cancelled"

func (Err) Error added in v0.6.0

func (e Err) Error() string

type EventType

type EventType int
const (
	TypeAnnounce EventType = iota

type FlagBoolFunc

type FlagBoolFunc func(name string, def bool, usage string) *bool

FlagBoolFunc is passed to the Flags() function, it is compatible with the standard library flag.Bool() function

type FlagStrFunc

type FlagStrFunc func(name, def, usage string) *string

FlagStrFunc is passed to the Flags() function, it is compatible with the standard library flag.String() function

type MQTT

type MQTT interface {
	// Start connects to mqtt and block until disconnected.
	// "ok" is true if the client is still valid and should be reused by calling Start() again
	// Example of running with reconnect:
	//   for {
	//     ok, err := client.Start(ctx)
	//     if !ok {
	//       break
	//     }
	//     log.Printf("Error %v - retrying in 5 seconds", err)
	//     time.Sleep(5 * time.Second)
	//   }
	Start() (ok bool, err error)
	TopicName(t EventType) string
	DeviceState() chan *device.State
	PublishMeta(topic string, payload []byte)
	Publish(topic string, payload []byte, retain bool)
	SubscribeRaw(topic string) chan *Packet
	Unsubscribe(topic string) bool
	Resubscribe(oldTopic, newTopic string) bool
	Subscribe(topic string) chan []byte
	Discover() chan struct{}
	LastWillID() string

func New

func New(ctx context.Context, c *Config) (MQTT, error)

type MessageHandler

type MessageHandler interface {
	OnRaw(p *libmqtt.PublishPacket)
	OnAnnounce(p *libmqtt.PublishPacket)
	OnLeave(p *libmqtt.PublishPacket)
	OnDiscover(p *libmqtt.PublishPacket)
	OnFeature(p *libmqtt.PublishPacket)
	TopicName(t EventType) string

type Packet

type Packet libmqtt.PublishPacket

Jump to

Keyboard shortcuts

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