Documentation
¶
Overview ¶
Package connectmq is an MQTT client preconfigured for the free public broker broker.connectmq.com, built on Eclipse Paho (github.com/eclipse/paho.mqtt.golang).
It connects anonymously over TCP (1883), TLS (8883), WebSocket (8083) or secure WebSocket (8084), and adds context-aware Publish, Subscribe, Messages and WaitForMessage helpers on top of Paho.
Everything on the public broker can be read by anyone: use it for testing only, and put your topics under a random prefix (see TopicPrefix). For production, create a private broker at https://connectmq.com and set Options.Host, Options.Username and Options.Password.
Example ¶
Publish and subscribe on the public broker with one connection.
package main
import (
"context"
"fmt"
"log"
"time"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
ctx := context.Background()
c, err := connectmq.Connect(ctx, nil) // mqtts://broker.connectmq.com:8883
if err != nil {
log.Fatal(err)
}
defer c.Close()
prefix := connectmq.TopicPrefix() // e.g. "connectmq/demo/7f3a91"
unsubscribe, err := c.Subscribe(ctx, prefix+"/#", 0, func(m connectmq.Message) {
fmt.Println(m.Topic, m.String())
})
if err != nil {
log.Fatal(err)
}
defer unsubscribe()
// Values other than []byte and string are sent as JSON.
if err := c.Publish(ctx, prefix+"/temperature", map[string]float64{"value": 21.5}, 1, false); err != nil {
log.Fatal(err)
}
time.Sleep(time.Second)
}
Output:
Index ¶
- Constants
- func BrokerURL(t Transport, host string) string
- func Publish(ctx context.Context, topic string, payload any, qos byte, retain bool, ...) error
- func TopicMatches(filter, topic string) bool
- func TopicPrefix() string
- type Client
- func (c *Client) Close()
- func (c *Client) IsConnected() bool
- func (c *Client) Messages(ctx context.Context, filter string, qos byte) (<-chan Message, error)
- func (c *Client) Paho() paho.Client
- func (c *Client) Publish(ctx context.Context, topic string, payload any, qos byte, retain bool) error
- func (c *Client) Subscribe(ctx context.Context, filter string, qos byte, handler func(Message)) (unsubscribe func() error, err error)
- func (c *Client) URL() string
- func (c *Client) WaitForMessage(ctx context.Context, filter string) (Message, error)
- type Message
- type Options
- type TestResult
- type Transport
Examples ¶
Constants ¶
const BrokerHost = "broker.connectmq.com"
BrokerHost is the host name of the ConnectMQ public broker.
Variables ¶
This section is empty.
Functions ¶
func BrokerURL ¶
BrokerURL returns the URL of a broker endpoint, for example "mqtts://broker.connectmq.com:8883". An empty host means BrokerHost.
Example ¶
package main
import (
"fmt"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
fmt.Println(connectmq.BrokerURL(connectmq.WSS, ""))
}
Output: wss://broker.connectmq.com:8084/mqtt
func Publish ¶
func Publish(ctx context.Context, topic string, payload any, qos byte, retain bool, opts *Options) error
Publish sends one message using a short-lived connection (nil opts means the public broker over TLS).
func TopicMatches ¶
TopicMatches reports whether topic matches an MQTT topic filter with the wildcards + and #, including shared subscriptions ($share/group/filter).
Example ¶
package main
import (
"fmt"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
fmt.Println(connectmq.TopicMatches("plant/+/temp", "plant/line1/temp"))
fmt.Println(connectmq.TopicMatches("plant/#", "plant/line1/temp"))
fmt.Println(connectmq.TopicMatches("plant/+", "plant/line1/temp"))
}
Output: true true false
func TopicPrefix ¶
func TopicPrefix() string
TopicPrefix returns a random topic prefix such as "connectmq/demo/7f3a91". The public area is shared, so a random prefix keeps your topics apart from other testers.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a connected MQTT client. Close it when done.
func Connect ¶
Connect opens a connection to the broker described by opts (nil means the public broker over TLS).
Example (PrivateBroker) ¶
Connect to a private ConnectMQ broker.
package main
import (
"context"
"log"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
c, err := connectmq.Connect(context.Background(), &connectmq.Options{
Host: "YOUR_BROKER_HOST",
Transport: connectmq.TLS,
Username: "device01",
Password: "secret",
})
if err != nil {
log.Fatal(err)
}
defer c.Close()
}
Output:
func (*Client) IsConnected ¶
IsConnected reports whether the connection is currently up.
func (*Client) Messages ¶
Messages subscribes to filter and delivers messages on the returned channel until ctx is cancelled; the channel is then closed and the subscription removed. Messages are dropped if the channel buffer (64) is full.
Example ¶
package main
import (
"context"
"fmt"
"log"
"time"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
c, err := connectmq.Connect(ctx, &connectmq.Options{Transport: connectmq.WSS})
if err != nil {
log.Fatal(err)
}
defer c.Close()
messages, err := c.Messages(ctx, "connectmq/demo/7f3a91/sensors/+", 0)
if err != nil {
log.Fatal(err)
}
for m := range messages { // ends when ctx is done
var reading struct{ Temperature float64 }
if err := m.JSON(&reading); err == nil {
fmt.Println(m.Topic, reading.Temperature)
}
}
}
Output:
func (*Client) Paho ¶
Paho returns the underlying Paho client, for anything not covered by this package.
func (*Client) Publish ¶
func (c *Client) Publish(ctx context.Context, topic string, payload any, qos byte, retain bool) error
Publish sends a message. A []byte or string payload is sent as is; any other value is encoded as JSON. Publish an empty payload with retain=true to clear a retained message. For QoS 1 and 2 it waits for the broker's acknowledgement.
func (*Client) Subscribe ¶
func (c *Client) Subscribe(ctx context.Context, filter string, qos byte, handler func(Message)) (unsubscribe func() error, err error)
Subscribe calls handler for every message matching filter, on a Paho goroutine. The returned function unsubscribes. Only one handler per filter is active at a time.
func (*Client) WaitForMessage ¶
WaitForMessage returns the next message matching filter, or an error when ctx ends. Retained messages count, so it returns immediately if one is stored for the topic.
Example ¶
package main
import (
"context"
"fmt"
"log"
"time"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
c, err := connectmq.Connect(ctx, nil)
if err != nil {
log.Fatal(err)
}
defer c.Close()
m, err := c.WaitForMessage(ctx, "connectmq/demo/7f3a91/reply")
if err != nil {
log.Fatal(err)
}
fmt.Println(m.String())
}
Output:
type Options ¶
type Options struct {
Transport Transport // default TLS
Host string // default broker.connectmq.com
Port int // default: the standard port of Transport
ClientID string // default "go-" plus a random suffix; must be unique
Username string // for private brokers
Password string // for private brokers
KeepAlive time.Duration // default 60s
Timeout time.Duration // connect and acknowledgement timeout, default 10s
// Configure, when set, is called with the Paho options before connecting,
// for settings such as a last will or custom TLS certificates.
Configure func(*paho.ClientOptions)
}
Options configures Connect. The zero value connects anonymously to the public broker over TLS with a random client ID.
type TestResult ¶
type TestResult struct {
URL string
OK bool
Connect time.Duration
RoundTrip time.Duration
Err error
}
TestResult is the result of Test.
func Test ¶
func Test(ctx context.Context, opts *Options) TestResult
Test connects, subscribes, publishes and receives a test message. Errors are reported in TestResult.Err.
Example ¶
package main
import (
"context"
"fmt"
connectmq "github.com/connectmq/mqtt-go"
)
func main() {
r := connectmq.Test(context.Background(), &connectmq.Options{Transport: connectmq.TLS})
if r.OK {
fmt.Printf("connected in %v, round-trip %v\n", r.Connect, r.RoundTrip)
} else {
fmt.Println("failed:", r.Err)
}
}
Output: