1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package weather
import (
"context"
"crypto/tls"
"fmt"
"net/url"
"os"
"time"
"github.com/eclipse/paho.golang/autopaho"
"github.com/eclipse/paho.golang/paho"
)
// MQTTConfig holds MQTT connection configuration
type MQTTConfig struct {
Broker string
ClientID string
Username string
Password string
KeepAlive time.Duration
SessionExpiry time.Duration
Timeout time.Duration
OnPublishReceived []func(paho.PublishReceived) (bool, error)
}
// CreateMQTTClient creates a MQTT client with the given configuration
func CreateMQTTClient(ctx context.Context, cfg MQTTConfig,
onConnect func(*autopaho.ConnectionManager, *paho.Connack)) (*autopaho.ConnectionManager, error) {
serverURL, err := url.Parse(cfg.Broker)
if err != nil {
return nil, fmt.Errorf("invalid MQTT broker URL: %w", err)
}
cliCfg := autopaho.ClientConfig{
ServerUrls: []*url.URL{serverURL},
KeepAlive: uint16(cfg.KeepAlive.Seconds()),
ClientConfig: paho.ClientConfig{
ClientID: fmt.Sprintf("%s-%d", cfg.ClientID, os.Getpid()),
OnPublishReceived: cfg.OnPublishReceived,
OnServerDisconnect: func(d *paho.Disconnect) {
// Default disconnect handler
},
},
ConnectUsername: cfg.Username,
ConnectPassword: []byte(cfg.Password),
ConnectTimeout: cfg.Timeout,
}
cliCfg.CleanStartOnInitialConnection = false
cliCfg.SessionExpiryInterval = uint32(cfg.SessionExpiry.Seconds())
if serverURL.Scheme == "ssl" || serverURL.Scheme == "tls" {
cliCfg.TlsCfg = &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
if onConnect != nil {
cliCfg.OnConnectionUp = onConnect
}
cm, err := autopaho.NewConnection(ctx, cliCfg)
if err != nil {
return nil, fmt.Errorf("failed to create MQTT connection: %w", err)
}
err = cm.AwaitConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to establish MQTT connection: %w", err)
}
return cm, nil
}
|